target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
node_modules/react-router/es6/Redirect.js
rakshitmidha/Weather_App_React
import React from 'react'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { formatPattern } from './PatternUtils'; import { falsy } from './InternalPropTypes'; var _React$PropTypes = React.PropTypes; var string = _React$PropTypes.string; var object = _React$PropTypes.object; /** * A <Redirect> is used to declare another URL path a client should * be sent to when they request a given URL. * * Redirects are placed alongside routes in the route configuration * and are traversed in the same manner. */ var Redirect = React.createClass({ displayName: 'Redirect', statics: { createRouteFromReactElement: function createRouteFromReactElement(element) { var route = _createRouteFromReactElement(element); if (route.from) route.path = route.from; route.onEnter = function (nextState, replace) { var location = nextState.location; var params = nextState.params; var pathname = void 0; if (route.to.charAt(0) === '/') { pathname = formatPattern(route.to, params); } else if (!route.to) { pathname = location.pathname; } else { var routeIndex = nextState.routes.indexOf(route); var parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1); var pattern = parentPattern.replace(/\/*$/, '/') + route.to; pathname = formatPattern(pattern, params); } replace({ pathname: pathname, query: route.query || location.query, state: route.state || location.state }); }; return route; }, getRoutePattern: function getRoutePattern(routes, routeIndex) { var parentPattern = ''; for (var i = routeIndex; i >= 0; i--) { var route = routes[i]; var pattern = route.path || ''; parentPattern = pattern.replace(/\/*$/, '/') + parentPattern; if (pattern.indexOf('/') === 0) break; } return '/' + parentPattern; } }, propTypes: { path: string, from: string, // Alias for path to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Redirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default Redirect;
ajax/libs/forerunnerdb/1.3.866/fdb-core+views.js
wout/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/View":34,"./core":2}],2:[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":9,"../lib/Shim.IE8":33}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":29,"./Shared":32}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } 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, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } 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.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', 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.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ 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.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', 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) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //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._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // 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._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, 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._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param {Object} data The data / document to use for lookups. * @param {Object} options An options object. * @param {Operation} op An optional operation instance. Pass undefined * if not being used. * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, op, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, op, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, op, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ 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; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; //regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; } resultArr._visitedCount++; resultArr._visitedNodes = resultArr._visitedNodes || []; resultArr._visitedNodes.push(thisDataPathVal); result = this.sortAsc(thisDataPathValSubStr, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } 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 / path 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), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, 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, pathResolver); } 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; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // 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 indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // 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]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":29,"./Shared":32}],5:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; 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; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = 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 }; module.exports = checksum; },{}],6:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, Condition, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; 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 }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data 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 = true; // 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'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); Condition = _dereq_('./Condition'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * 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. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * 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. * @param {Function=} callback A callback method to call once the * operation has completed. * @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._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, 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: 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 by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(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'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @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 {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @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. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * 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 via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } 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 hash string jString = this.hash(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!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off 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.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * 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 * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @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, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // 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.call(this); } 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, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } 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. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Detect $replace operations and set flag if (update.$replace) { // Make sure we have an options object options = options || {}; // Set the $replace flag in the options object options.$replace = true; // Move the replacement object out into the main update object update = update.$replace; } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @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. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { 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 self._removeFromIndexes(referencedDoc); result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); self._insertIntoIndexes(referencedDoc); // 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 self._removeFromIndexes(referencedDoc); result = self.updateObject(referencedDoc, update, query, options, ''); self._insertIntoIndexes(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) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this, updated || []); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } else { if (callback) { callback.call(this, updated || []); } } } else { if (callback) { callback.call(this, 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. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base 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 via it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to * update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * 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, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Check if we have a $replace flag in the options object if (options && options.$replace === true) { operation = true; replaceObj = update; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } // Early exit return updated; } // DEVS PLEASE NOTE -- Early exit could have occurred above and code below will never be reached - Rob Evans - CEO - 05/08/2016 // 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 (!operation && 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; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } 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 (!operation && 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 '$splicePull': // Check that the target key is not undefined if (doc[i] !== undefined) { // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update[i].$index; if (tempIndex !== undefined) { // Check for in bounds index if (tempIndex < doc[i].length) { this._updateSplicePull(doc[i], tempIndex); updated = true; } } else { throw(this.logIdentifier() + ' Cannot splicePull without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePull from 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 identifying the documents to remove. If no * query object is passed, all documents will be removed from the collection. * @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.call(this, false, returnArr); } return returnArr; } else { returnArr = []; 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); returnArr.push(dataItem); }; // 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); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * 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 > 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.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('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 {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ 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); }; /** * The insert operation's callback. * @callback Collection~insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * 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 {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ 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 (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // 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 }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed}); this.deferEmit('change', {type: 'insert', data: inserted, failed: failed}); 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, capped = this.capped(), cappedSize = this.cappedSize(); 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); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; 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 'Trigger cancelled operation'; } } 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, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, 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, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // 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 (must be * actual reference to original document). * @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), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * 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 {String} search The string to search for. Case sensitive. * @param {Object=} 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.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; 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 || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // 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); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } 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 = [].concat(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) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); 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)) { } } }*/ if (!options.$aggregate) { // 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'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * 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 = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } 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 = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } 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) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = 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); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * 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); } };*/ /** * 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 }; };*/ /** * Sorts array by individual sort path. * @param {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @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); }; /** * 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 {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = [].concat(this._primaryIndex.lookup(query, options, op)); analysis.indexMatch.push({ lookup: lookupResult, 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 = [].concat(indexRef.lookup(query, options, op)); 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 (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, 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) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), 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(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents * that matches the subDocQuery parameter. * @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 {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * 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) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } 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 pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== 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[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // 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[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * 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.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } 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.dataSet); } 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!'); } }; /** * Creates a condition handler that will react to changes in data on the * collection. * @example Create a condition handler that reacts when data changes. * var coll = db.collection('test'), * condition = coll.when({_id: 'test1', val: 1}) * .then(function () { * console.log('Condition met!'); * }) * .else(function () { * console.log('Condition un-met'); * }); * * coll.insert({_id: 'test1', val: 1}); * * @see Condition * @param {Object} query The query that will trigger the condition's then() * callback. * @returns {Condition} */ Collection.prototype.when = function (query) { var queryId = this.objectId(); this._when = this._when || {}; this._when[queryId] = this._when[queryId] || new Condition(this, queryId, query); return this._when[queryId]; }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * 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 * @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 self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { 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!'); } return undefined; } 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); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.deferEmit('create', self._collection[name], 'collection', name); 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; },{"./Condition":8,"./Index2d":12,"./IndexBinaryTree":13,"./IndexHashMap":14,"./KeyValueStore":15,"./Metrics":16,"./Overload":28,"./Path":29,"./ReactorIO":30,"./Shared":32}],7:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {String=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.deferEmit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":6,"./Shared":32}],8:[function(_dereq_,module,exports){ "use strict"; /** * The condition class monitors a data source and updates it's internal * state depending on clauses that it has been given. When all clauses * are satisfied the then() callback is fired. If conditions were met * but data changed that made them un-met, the else() callback is fired. */ var //Overload = require('./Overload'), Shared, Condition; Shared = _dereq_('./Shared'); /** * Create a constructor method that calls the instance's init method. * This allows the constructor to be overridden by other modules because * they can override the init method with their own. */ Condition = function () { this.init.apply(this, arguments); }; Condition.prototype.init = function (dataSource, id, clause) { this._dataSource = dataSource; this._id = id; this._query = [clause]; this._started = false; this._state = [false]; this._satisfied = false; // Set this to true by default for faster performance this.earlyExit(true); }; // Tell ForerunnerDB about our new module Shared.addModule('Condition', Condition); // Mixin some commonly used methods Shared.mixin(Condition.prototype, 'Mixin.Common'); Shared.mixin(Condition.prototype, 'Mixin.ChainReactor'); Shared.synthesize(Condition.prototype, 'id'); Shared.synthesize(Condition.prototype, 'then'); Shared.synthesize(Condition.prototype, 'else'); Shared.synthesize(Condition.prototype, 'earlyExit'); Shared.synthesize(Condition.prototype, 'debug'); /** * Adds a new clause to the condition. * @param {Object} clause The query clause to add to the condition. * @returns {Condition} */ Condition.prototype.and = function (clause) { this._query.push(clause); this._state.push(false); return this; }; /** * Starts the condition so that changes to data will call callback * methods according to clauses being met. * @param {*} initialState Initial state of condition. * @returns {Condition} */ Condition.prototype.start = function (initialState) { if (!this._started) { var self = this; if (arguments.length !== 0) { this._satisfied = initialState; } // Resolve the current state this._updateStates(); self._onChange = function () { self._updateStates(); }; // Create a chain reactor link to the data source so we start receiving CRUD ops from it this._dataSource.on('change', self._onChange); this._started = true; } return this; }; /** * Updates the internal status of all the clauses against the underlying * data source. * @private */ Condition.prototype._updateStates = function () { var satisfied = true, i; for (i = 0; i < this._query.length; i++) { this._state[i] = this._dataSource.count(this._query[i]) > 0; if (this._debug) { console.log(this.logIdentifier() + ' Evaluating', this._query[i], '=', this._query[i]); } if (!this._state[i]) { satisfied = false; // Early exit since we have found a state that is not true if (this._earlyExit) { break; } } } if (this._satisfied !== satisfied) { // Our state has changed, fire the relevant operation if (satisfied) { // Fire the "then" operation if (this._then) { this._then(); } } else { // Fire the "else" operation if (this._else) { this._else(); } } this._satisfied = satisfied; } }; /** * Stops the condition so that callbacks will no longer fire. * @returns {Condition} */ Condition.prototype.stop = function () { if (this._started) { this._dataSource.off('change', this._onChange); delete this._onChange; this._started = false; } return this; }; /** * Drops the condition and removes it from memory. * @returns {Condition} */ Condition.prototype.drop = function () { this.stop(); delete this._dataSource.when[this._id]; return this; }; // Tell ForerunnerDB that our module has finished loading Shared.finishModule('Condition'); module.exports = Condition; },{"./Shared":32}],9:[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 (val) { 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; } } if (callback) { 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; } } } } if (callback) { 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; /** * 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":10,"./Metrics.js":16,"./Overload":28,"./Shared":32}],10:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, 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; } } if (callback) { 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'); Shared.mixin(Db.prototype, 'Mixin.Events'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.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.Checksum = Checksum; /** * 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._listeners; 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._listeners; 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._listeners; 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._listeners; 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; },{"./Checksum.js":5,"./Collection.js":6,"./Metrics.js":16,"./Overload":28,"./Shared":32}],11:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - [email protected] "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders, PI180 = Math.PI / 180, PI180R = 180 / Math.PI, earthRadius = 6371; // mean radius of the earth bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; /** * Converts degrees to radians. * @param {Number} degrees * @return {Number} radians */ GeoHash.prototype.radians = function radians (degrees) { return degrees * PI180; }; /** * Converts radians to degrees. * @param {Number} radians * @return {Number} degrees */ GeoHash.prototype.degrees = function (radians) { return radians * PI180R; }; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates a new lat/lng by travelling from the center point in the * bearing specified for the distance specified. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} distanceKm The distance to travel in kilometers. * @param {Number} bearing The bearing to travel in degrees (zero is * north). * @returns {{lat: Number, lng: Number}} */ GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) { var curLon = centerPoint[1], curLat = centerPoint[0], destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))), tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)), destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º return { lat: this.degrees(destLat), lng: this.degrees(destLon) }; }; /** * Calculates the extents of a bounding box around the center point which * encompasses the radius in kilometers passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param radiusKm Radius in kilometers. * @returns {{lat: Array, lng: Array}} */ GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) { var maxWest, maxEast, maxNorth, maxSouth, lat = [], lng = []; maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0); maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90); maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180); maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270); lat[0] = maxNorth.lat; lat[1] = maxSouth.lat; lng[0] = maxWest.lng; lng[1] = maxEast.lng; return { lat: lat, lng: lng }; }; /** * Calculates all the geohashes that make up the bounding box that surrounds * the circle created from the center point and radius passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} radiusKm The radius in kilometers to encompass. * @param {Number} precision The number of characters to limit the returned * geohash strings to. * @returns {Array} The array of geohashes that encompass the bounding box. */ GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) { var extent = this.calculateExtentByRadius(centerPoint, radiusKm), northWest = [extent.lat[0], extent.lng[0]], northEast = [extent.lat[0], extent.lng[1]], southWest = [extent.lat[1], extent.lng[0]], northWestHash = this.encode(northWest[0], northWest[1], precision), northEastHash = this.encode(northEast[0], northEast[1], precision), southWestHash = this.encode(southWest[0], southWest[1], precision), hash, widthCount = 0, heightCount = 0, widthIndex, heightIndex, hashArray = []; hash = northWestHash; hashArray.push(hash); // Walk from north west to north east until we find the north east geohash while (hash !== northEastHash) { hash = this.calculateAdjacent(hash, 'right'); widthCount++; hashArray.push(hash); } hash = northWestHash; // Walk from north west to south west until we find the south west geohash while (hash !== southWestHash) { hash = this.calculateAdjacent(hash, 'bottom'); heightCount++; } // We now know the width and height in hash boxes of the area, fill in the // rest of the hashes into the hashArray array for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) { hash = hashArray[widthIndex]; for (heightIndex = 0; heightIndex < heightCount; heightIndex++) { hash = this.calculateAdjacent(hash, 'bottom'); hashArray.push(hash); } } return hashArray; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to a longitude/latitude array. * The array contains three latitudes and three longitudes. The * first of each is the lower extent of the geohash bounding box, * the second is the upper extent and the third is the center * of the geohash bounding box. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { lat: lat, lng: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; if (typeof module !== 'undefined') { module.exports = GeoHash; } },{}],12:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.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.clear(); this._size = 0; 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 }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.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]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; /** * Looks up records that match the passed query and options. * @param query The query to execute. * @param options A query options object. * @param {Operation=} op Optional operation instance that allows * us to provide operation diagnostics and analytics back to the * main calling instance as the process is running. * @returns {*} */ Index2d.prototype.lookup = function (query, options, op) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options, op)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options, op) { var self = this, neighbours, visitedCount, visitedNodes, visitedData, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } if (precision === 0) { precision = 1; } // Calculate 9 box geohashes if (op) { op.time('index2d.calculateHashArea'); } neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision); if (op) { op.time('index2d.calculateHashArea'); } if (op) { op.data('index2d.near.precision', precision); op.data('index2d.near.hashArea', neighbours); op.data('index2d.near.maxDistanceKm', maxDistanceKm); op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]); } // Lookup all matching co-ordinates from the btree results = []; visitedCount = 0; visitedData = {}; visitedNodes = []; if (op) { op.time('index2d.near.getDocsInsideHashArea'); } for (i = 0; i < neighbours.length; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visitedData[neighbours[i]] = search; visitedCount += search._visitedCount; visitedNodes = visitedNodes.concat(search._visitedNodes); results = results.concat(search); } if (op) { op.time('index2d.near.getDocsInsideHashArea'); op.data('index2d.near.startsWith', visitedData); op.data('index2d.near.visitedTreeNodes', visitedNodes); } // Work with original data if (op) { op.time('index2d.near.lookupDocsById'); } results = this._collection._primaryIndex.lookup(results); if (op) { op.time('index2d.near.lookupDocsById'); } if (query.$distanceField) { // Decouple the results before we modify them results = this.decouple(results); } if (results.length) { distance = {}; if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { if (query.$distanceField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371)); } if (query.$geoHashField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision)); } // Add item as it is inside radius distance finalResults.push(results[i]); } } if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Sort by distance from center if (op) { op.time('index2d.near.sortResultsByDistance'); } finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); if (op) { op.time('index2d.near.sortResultsByDistance'); } } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.'); return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.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; }; Index2d.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; }; Index2d.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; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":4,"./GeoHash":11,"./Path":29,"./Shared":32}],13:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree 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 BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; 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.clear(); this._size = 0; 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; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; 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, options, op) { return this._btree.lookup(query, options, op); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; 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; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":29,"./Shared":32}],14:[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 = {}; this._size = 0; 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; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":29,"./Shared":32}],15:[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 {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk] !== undefined && val[pk] !== null) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * 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":32}],16:[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":27,"./Shared":32}],17:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],18:[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 = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ 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); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ 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); } } }, /** * Gets / sets the flag that will enable / disable chain reactor sending * from this instance. Chain reactor sending is enabled by default on all * instances. * @param {Boolean} val True or false to enable or disable chain sending. * @returns {*} */ chainEnabled: function (val) { if (val !== undefined) { this._chainDisabled = !val; return this; } return !this._chainDisabled; }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain && !this._chainDisabled); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain && !this._chainDisabled) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); 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() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], 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!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],19:[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, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * 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 && data !== "") { 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 JSON.parse(data, serialiser.reviver()); }, /** * 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; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * 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 'ForerunnerDB ' + 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'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":28,"./Serialiser":31}],20:[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; },{}],21:[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, fired = false, internalCallback = function () { if (!fired) { self.off(eventName, internalCallback); callback.apply(self, arguments); fired = true; } }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(eventName, id, internalCallback); callback.apply(self, arguments); fired = true; } }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event); }); } else { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } } return this; }, 'string, function': function (event, listener) { var self = this, arr, index; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, listener); }); } else { 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) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id, listener); }); } else { 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) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id); }); } else { 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 || {}; this._emitting = true; 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)); } } } } } } } this._emitting = false; this._processRemovalQueue(); return this; }, /** * If events are cleared with the off() method while the event emitter is * actively processing any events then the off() calls get added to a * queue to be executed after the event emitter is finished. This stops * errors that might occur by potentially modifying the event queue while * the emitter is running through them. This method is called after the * event emitter is finished processing. * @private */ _processRemovalQueue: function () { var i; if (this._eventRemovalQueue && this._eventRemovalQueue.length) { // Execute each removal call for (i = 0; i < this._eventRemovalQueue.length; i++) { this._eventRemovalQueue[i](); } // Clear the removal queue this._eventRemovalQueue = []; } }, /** * 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":28}],22:[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; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } 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; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // 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' || sourceType === 'null' || testType === 'null') { // Number or null 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 if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ 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} queryOptions The options the query was passed with. * @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 '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === 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 (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } 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 (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$fastIn': if (test instanceof Array) { // Source is a string or number, use indexOf to identify match in array return test.indexOf(source) !== -1; } else { console.log(this.logIdentifier() + ' Cannot use an $fastIn operator on a non-array key: ' + key, options.$rootQuery); return false; } 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; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.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)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.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 (resultKeyName === '$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 [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[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 { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions 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 pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[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] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],23:[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; },{}],24:[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; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * 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 {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} 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) { self.triggerStack = {}; // 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; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } 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._ignoreTriggers && 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, typeName, phaseName; if (!self._ignoreTriggers && 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 (self.debug()) { 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 "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // 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":28}],26:[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 + '" to val "' + val + '"'); } }, /** * 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); } }, /** * Removes an item from the passed array at the specified index. * @param {Array} arr The array to remove from. * @param {Number} index The index of the item to remove. * @param {Number} count The number of items to remove. * @private */ _updateSplicePull: function (arr, index, count) { if (!count) { count = 1; } arr.splice(index, count); }, /** * 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 set. * @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; },{}],27:[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":29,"./Shared":32}],28:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } 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, overloadName; // 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); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" 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 = ['array', '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; },{}],29:[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. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @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') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * 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; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * 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(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; 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], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * 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":32}],30:[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) { 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); delete this._listeners; } 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":32}],31:[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 () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],32:[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.866', modules: {}, plugins: {}, index: {}, _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]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @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. */ '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); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ '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":17,"./Mixin.ChainReactor":18,"./Mixin.Common":19,"./Mixin.Constants":20,"./Mixin.Events":21,"./Mixin.Matching":22,"./Mixin.Sorting":23,"./Mixin.Tags":24,"./Mixin.Triggers":25,"./Mixin.Updating":26,"./Overload":28}],33:[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 = {}; },{}],34:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'), Path, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.Matching'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); //Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Path = Shared.modules.Path; sharedPathSolver = new Path(); View.prototype.init = function (name, query, options) { var self = this; this.sharedPathSolver = sharedPathSolver; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._data = new Collection(this.name() + '_internal'); }; /** * This reactor IO node is given data changes from source data and * then acts as a firewall process between the source and view data. * Data needs to meet the requirements this IO node imposes before * the data is passed down the reactor chain (to the view). This * allows us to intercept data changes from the data source and act * on them such as applying transforms, checking the data matches * the view's query, applying joins to the data etc before sending it * down the reactor chain via the this.chainSend() calls. * * Update packets are especially complex to handle because an update * on the underlying source data could translate into an insert, * update or remove call on the view. Take a scenario where the view's * query limits the data seen from the source. If the source data is * updated and the data now falls inside the view's query limitations * the data is technically now an insert on the view, not an update. * The same is true in reverse where the update becomes a remove. If * the updated data already exists in the view and will still exist * after the update operation then the update can remain an update. * @param {Object} chainPacket The chain reactor packet representing the * data operation that has just been processed on the source data. * @param {View} self The reference to the view we are operating for. * @private */ View.prototype._handleChainIO = function (chainPacket, self) { var type = chainPacket.type, hasActiveJoin, hasActiveQuery, hasTransformIn, sharedData; // NOTE: "self" in this context is the view instance. // NOTE: "this" in this context is the ReactorIO node sitting in // between the source (sender) and the destination (listener) and // in this case the source is the view's "from" data source and the // destination is the view's _data collection. This means // that "this.chainSend()" is asking the ReactorIO node to send the // packet on to the destination listener. // EARLY EXIT: Check that the packet is not a CRUD operation if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') { // This packet is NOT a CRUD operation packet so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We only need to check packets under three conditions // 1) We have a limiting query on the view "active query", // 2) We have a query options with a $join clause on the view "active join" // 3) We have a transformIn operation registered on the view. // If none of these conditions exist we can just allow the chain // packet to proceed as normal hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join); hasActiveQuery = Boolean(self._querySettings.query); hasTransformIn = self._data._transformIn !== undefined; // EARLY EXIT: Check for any complex operation flags and if none // exist, send the packet on and exit early if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) { // We don't have any complex operation flags so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We have either an active query, active join or a transformIn // function registered on the view // We create a shared data object here so that the disparate method // calls can share data with each other via this object whilst // still remaining separate methods to keep code relatively clean. sharedData = { dataArr: [], removeArr: [] }; // Check the packet type to get the data arrays to work on if (chainPacket.type === 'insert') { // Check if the insert data is an array if (chainPacket.data.dataSet instanceof Array) { // Use the insert data array sharedData.dataArr = chainPacket.data.dataSet; } else { // Generate an array from the single insert object sharedData.dataArr = [chainPacket.data.dataSet]; } } else if (chainPacket.type === 'update') { // Use the dataSet array sharedData.dataArr = chainPacket.data.dataSet; } else if (chainPacket.type === 'remove') { if (chainPacket.data.dataSet instanceof Array) { // Use the remove data array sharedData.removeArr = chainPacket.data.dataSet; } else { // Generate an array from the single remove object sharedData.removeArr = [chainPacket.data.dataSet]; } } // Safety check if (!(sharedData.dataArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!'); sharedData.dataArr = []; } if (!(sharedData.removeArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!'); sharedData.removeArr = []; } // We need to operate in this order: // 1) Check if there is an active join - active joins are operated // against the SOURCE data. The joined data can potentially be // utilised by any active query or transformIn so we do this step first. // 2) Check if there is an active query - this is a query that is run // against the SOURCE data after any active joins have been resolved // on the source data. This allows an active query to operate on data // that would only exist after an active join has been executed. // If the source data does not fall inside the limiting factors of the // active query then we add it to a removal array. If it does fall // inside the limiting factors when we add it to an upsert array. This // is because data that falls inside the query could end up being // either new data or updated data after a transformIn operation. // 3) Check if there is a transformIn function. If a transformIn function // exist we run it against the data after doing any active join and // active query. if (hasActiveJoin) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } self._handleChainIO_ActiveJoin(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } } if (hasActiveQuery) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } self._handleChainIO_ActiveQuery(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } } if (hasTransformIn) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } self._handleChainIO_TransformIn(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } } // Check if we still have data to operate on and exit // if there is none left if (!sharedData.dataArr.length && !sharedData.removeArr.length) { // There is no more data to operate on, exit without // sending any data down the chain reactor (return true // will tell reactor to exit without continuing)! return true; } // Grab the public data collection's primary key sharedData.pk = self._data.primaryKey(); // We still have data left, let's work out how to handle it // first let's loop through the removals as these are easy if (sharedData.removeArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } self._handleChainIO_RemovePackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } } if (sharedData.dataArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } self._handleChainIO_UpsertPackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } } // Now return true to tell the chain reactor not to propagate // the data itself as we have done all that work here return true; }; View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) { var dataArr = sharedData.dataArr, removeArr; // Since we have an active join, all we need to do is operate // the join clause on each item in the packet's data array. removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {}); // Now that we've run our join keep in mind that joins can exclude data // if there is no matching joined data and the require: true clause in // the join options is enabled. This means we have to store a removal // array that tells us which items from the original data we sent to // join did not match the join data and were set with a require flag. // Now that we have our array of items to remove, let's run through the // original data and remove them from there. this.spliceArrayByIndexList(dataArr, removeArr); // Make sure we add any items we removed to the shared removeArr sharedData.removeArr = sharedData.removeArr.concat(removeArr); }; View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, i; // Now we need to run the data against the active query to // see if the data should be in the final data list or not, // so we use the _match method. // Loop backwards so we can safely splice from the array // while we are looping for (i = dataArr.length - 1; i >= 0; i--) { if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) { // The data didn't match the active query, add it // to the shared removeArr sharedData.removeArr.push(dataArr[i]); // Now remove it from the shared dataArr dataArr.splice(i, 1); } } }; View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, removeArr = sharedData.removeArr, dataIn = self._data._transformIn, i; // At this stage we take the remaining items still left in the data // array and run our transformIn method on each one, modifying it // from what it was to what it should be on the view. We also have // to run this on items we want to remove too because transforms can // affect primary keys and therefore stop us from identifying the // correct items to run removal operations on. // It is important that these are transformed BEFORE they are passed // to the CRUD methods because we use the CU data to check the position // of the item in the array and that can only happen if it is already // pre-transformed. The removal stuff also needs pre-transformed // because ids can be modified by a transform. for (i = 0; i < dataArr.length; i++) { // Assign the new value dataArr[i] = dataIn(dataArr[i]); } for (i = 0; i < removeArr.length; i++) { // Assign the new value removeArr[i] = dataIn(removeArr[i]); } }; View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) { var $or = [], pk = sharedData.pk, removeArr = sharedData.removeArr, packet = { dataSet: removeArr, query: { $or: $or } }, orObj, i; for (i = 0; i < removeArr.length; i++) { orObj = {}; orObj[pk] = removeArr[i][pk]; $or.push(orObj); } ioObj.chainSend('remove', packet); }; View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) { var data = this._data, primaryIndex = data._primaryIndex, primaryCrc = data._primaryCrc, pk = sharedData.pk, dataArr = sharedData.dataArr, arrItem, insertArr = [], updateArr = [], query, i; // Let's work out what type of operation this data should // generate between an insert or an update. for (i = 0; i < dataArr.length; i++) { arrItem = dataArr[i]; // Check if the data already exists in the data if (primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) { // The document exists in the data collection but data differs, update required updateArr.push(arrItem); } } else { // The document is missing from this collection, insert required insertArr.push(arrItem); } } if (insertArr.length) { ioObj.chainSend('insert', { dataSet: insertArr }); } if (updateArr.length) { for (i = 0; i < updateArr.length; i++) { arrItem = updateArr[i]; query = {}; query[pk] = arrItem[pk]; ioObj.chainSend('update', { query: query, update: arrItem, dataSet: [arrItem] }); } } }; /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function (query, update, options, callback) { var finalQuery = { $and: [this.query(), query] }; this._from.update.call(this._from, finalQuery, update, options, callback); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this._data.findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this._data.findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._data.findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this._data.findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._data; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); // Remove the current reference to the _from since we // are about to replace it with a new one delete this._from; } // Check if we have an existing reactor io that links the // previous _from source to the view's internal data if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } // Check if we were passed a source name rather than a // reference to a source object if (typeof(source) === 'string') { // We were passed a name, assume it is a collection and // get the reference to the collection of that name source = this._db.collection(source); } // Check if we were passed a reference to a view rather than // a collection. Views need to be handled slightly differently // since their data is stored in an internal data collection // rather than actually being a direct data source themselves. if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source._data; if (this.debug()) { console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking'); } } // Assign the new data source as the view's _from this._from = source; // Hook the new data source's drop event so we can unhook // it as a data source if it gets dropped. This is important // so that we don't run into problems using a dropped source // for active data. this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's _from source and determines how they should be interpreted by // this view. See the _handleChainIO() method which does all the chain packet // processing for the view. this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); }); // Set the view's internal data primary key to the same as the // current active _from data source this._data.primaryKey(source.primaryKey()); // Do the initial data lookup and populate the view's internal data // since at this point we don't actually have any data in the view // yet. var collData = source.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData, {}, callback); // If we have an active query and that query has an $orderBy clause, // update our active bucket which allows us to keep track of where // data should be placed in our internal data array. This is about // ordering of data and making sure that we maintain an ordered array // so that if we have data-binding we can place an item in the data- // bound view at the correct location. Active buckets use quick-sort // algorithms to quickly determine the position of an item inside an // existing array based on a sort protocol. if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData); // Rebuild active bucket as well 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() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Make sure we are working with an array if (!(chainPacket.data.dataSet instanceof Array)) { chainPacket.data.dataSet = [chainPacket.data.dataSet]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._data._insertHandle(arr[index], insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._data._data.length; this._data._insertHandle(chainPacket.data.dataSet, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"'); } primaryKey = this._data.primaryKey(); // Do the update updates = this._data._handleUpdate( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._data._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"'); } this._data.remove(chainPacket.data.query, chainPacket.options); if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the dataSet and remove the objects from the ActiveBucket arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { this._activeBucket.remove(arr[index]); } } break; default: break; } }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._data.ensureIndex.apply(this._data, arguments); }; /** /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._data.on.apply(this._data, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._data.off.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._data.emit.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::deferEmit() */ View.prototype.deferEmit = function () { return this._data.deferEmit.apply(this._data, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._data.distinct(key, query, options); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._data.primaryKey(); }; /** * @see Mixin.Triggers::addTrigger() */ View.prototype.addTrigger = function () { return this._data.addTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::removeTrigger() */ View.prototype.removeTrigger = function () { return this._data.removeTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::ignoreTriggers() */ View.prototype.ignoreTriggers = function () { return this._data.ignoreTriggers.apply(this._data, arguments); }; /** * @see Mixin.Triggers::addLinkIO() */ View.prototype.addLinkIO = function () { return this._data.addLinkIO.apply(this._data, arguments); }; /** * @see Mixin.Triggers::removeLinkIO() */ View.prototype.removeLinkIO = function () { return this._data.removeLinkIO.apply(this._data, arguments); }; /** * @see Mixin.Triggers::willTrigger() */ View.prototype.willTrigger = function () { return this._data.willTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::processTrigger() */ View.prototype.processTrigger = function () { return this._data.processTrigger.apply(this._data, arguments); }; /** * @see Mixin.Triggers::_triggerIndexOf() */ View.prototype._triggerIndexOf = function () { return this._data._triggerIndexOf.apply(this._data, arguments); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._data) { this._data.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._data; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this.decouple(this._querySettings); }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } if (query !== undefined) { this.emit('queryChange', query); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this.decouple(this._querySettings.query); }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } } if (query !== undefined) { this.emit('queryChange', query); } if (options !== undefined) { this.emit('queryOptionsChange', options); } if (query !== undefined || options !== undefined) { return this; } return this.decouple(this._querySettings); } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { // TODO: This could be wasteful if the previous options $orderBy was identical, do a hash and check first! this.rebuildActiveBucket(options.$orderBy); } if (options !== undefined) { this.emit('queryOptionsChange', options); } return this; } return this._querySettings.options; }; /** * Clears the existing active bucket and builds a new one based * on the passed orderBy object (if one is passed). * @param {Object=} orderBy The orderBy object describing how to * order any data. */ View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._data._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._data.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { var self = this, refreshResults, joinArr, i, k; if (this._from) { // Clear the private data collection which will propagate to the public data // collection automatically via the chain reactor node between them this._data.remove(); // Grab all the data from the underlying data source refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); // Insert the underlying data into the private data collection this._data.insert(refreshResults); // Store the current cursor data this._data._data.$cursor = refreshResults.$cursor; } if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) { // Define the change handler method self.__joinChange = self.__joinChange || function () { self._joinChange(); }; // Check for existing join collections if (this._joinCollections && this._joinCollections.length) { // Loop the join collections and remove change listeners // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange); } } // Now start hooking any new / existing joins joinArr = this._querySettings.options.$join; this._joinCollections = []; // Loop the joined collections and hook change events for (i = 0; i < joinArr.length; i++) { for (k in joinArr[i]) { if (joinArr[i].hasOwnProperty(k)) { this._joinCollections.push(k); } } } if (this._joinCollections.length) { // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange); } } } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Handles when a change has occurred on a collection that is joined * by query to this view. * @param objName * @param objType * @private */ View.prototype._joinChange = function (objName, objType) { this.emit('joinChange'); // TODO: This is a really dirty solution because it will require a complete // TODO: rebuild of the view data. We need to implement an IO handler to // TODO: selectively update the data of the view based on the joined // TODO: collection data operation. // FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call this.refresh(); }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._data.count.apply(this._data, arguments); }; // Call underlying View.prototype.subset = function () { return this._data.subset.apply(this._data, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" * and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var currentSettings, newSettings; currentSettings = this._data.transform(); this._data.transform(obj); newSettings = this._data.transform(); // Check if transforms are enabled, a dataIn method is set and these // settings did not match the previous transform settings if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) { // The data in the view is now stale, refresh it this.refresh(); } return newSettings; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return this._data.filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.data = function () { return this._data; }; /** * @see Collection.indexOf * @returns {*} */ View.prototype.indexOf = function () { return this._data.indexOf.apply(this._data, arguments); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this._data.db(db); // Apply the same debug settings this.debug(db.debug()); this._data.debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} name The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (name) { var self = this; // Handle being passed an instance if (name instanceof View) { return name; } if (this._view[name]) { return this._view[name]; } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + name); } this._view[name] = new View(name).db(this); self.deferEmit('create', self._view[name], 'view', name); return this._view[name]; }; /** * Determine if a view with the passed name already exists. * @param {String} name The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (name) { return Boolean(this._view[name]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":6,"./CollectionGroup":7,"./Overload":28,"./ReactorIO":30,"./Shared":32}]},{},[1]);
docs/src/pages/components/dividers/MiddleDividers.js
kybarg/material-ui
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Chip from '@material-ui/core/Chip'; import Button from '@material-ui/core/Button'; import Grid from '@material-ui/core/Grid'; import Divider from '@material-ui/core/Divider'; import Typography from '@material-ui/core/Typography'; const useStyles = makeStyles(theme => ({ root: { width: '100%', maxWidth: 360, backgroundColor: theme.palette.background.paper, }, chip: { marginRight: theme.spacing(1), }, section1: { margin: theme.spacing(3, 2), }, section2: { margin: theme.spacing(2), }, section3: { margin: theme.spacing(3, 1, 1), }, })); export default function MiddleDividers() { const classes = useStyles(); return ( <div className={classes.root}> <div className={classes.section1}> <Grid container alignItems="center"> <Grid item xs> <Typography gutterBottom variant="h4"> Toothbrush </Typography> </Grid> <Grid item> <Typography gutterBottom variant="h6"> $4.50 </Typography> </Grid> </Grid> <Typography color="textSecondary" variant="body2"> Pinstriped cornflower blue cotton blouse takes you on a walk to the park or just down the hall. </Typography> </div> <Divider variant="middle" /> <div className={classes.section2}> <Typography gutterBottom variant="body1"> Select type </Typography> <div> <Chip className={classes.chip} label="Extra Soft" /> <Chip className={classes.chip} color="primary" label="Soft" /> <Chip className={classes.chip} label="Medium" /> <Chip className={classes.chip} label="Hard" /> </div> </div> <div className={classes.section3}> <Button color="primary">Add to cart</Button> </div> </div> ); }
ajax/libs/ember-data.js/1.0.0-beta.17/ember-data.prod.js
iamJoeTaylor/cdnjs
(function() { "use strict"; var ember$data$lib$system$model$errors$invalid$$create = Ember.create; var ember$data$lib$system$model$errors$invalid$$EmberError = Ember.Error; /** 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$model$errors$invalid$$InvalidError(errors) { ember$data$lib$system$model$errors$invalid$$EmberError.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; } ember$data$lib$system$model$errors$invalid$$InvalidError.prototype = ember$data$lib$system$model$errors$invalid$$create(ember$data$lib$system$model$errors$invalid$$EmberError.prototype); var ember$data$lib$system$model$errors$invalid$$default = ember$data$lib$system$model$errors$invalid$$InvalidError; /** @module ember-data */ var ember$data$lib$system$adapter$$get = Ember.get; /** 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.Snapshot} snapshot @param {Object} options @return {Object} serialized snapshot */ serialize: function(snapshot, options) { return ember$data$lib$system$adapter$$get(snapshot.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} typeClass @return {Array} */ fixturesForType: function(typeClass) { if (typeClass.FIXTURES) { var fixtures = Ember.A(typeClass.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} typeClass @return {Promise|Array} */ queryFixtures: function(fixtures, query, typeClass) { }, /** @method updateFixtures @param {Subclass of DS.Model} typeClass @param {Array} fixture */ updateFixtures: function(typeClass, fixture) { if (!typeClass.FIXTURES) { typeClass.FIXTURES = []; } var fixtures = typeClass.FIXTURES; this.deleteLoadedFixture(typeClass, 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} typeClass @param {DS.Snapshot} snapshot */ mockJSON: function(store, typeClass, 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} typeClass @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ find: function(store, typeClass, id, snapshot) { var fixtures = this.fixturesForType(typeClass); var fixture; 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} typeClass @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: function(store, typeClass, ids, snapshots) { var fixtures = this.fixturesForType(typeClass); 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} typeClass @param {String} sinceToken @return {Promise} promise */ findAll: function(store, typeClass) { var fixtures = this.fixturesForType(typeClass); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} typeClass @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: function(store, typeClass, query, array) { var fixtures = this.fixturesForType(typeClass); fixtures = this.queryFixtures(fixtures, query, typeClass); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {subclass of DS.Model} typeClass @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: function(store, typeClass, snapshot) { var fixture = this.mockJSON(store, typeClass, snapshot); this.updateFixtures(typeClass, 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, typeClass, snapshot) { var fixture = this.mockJSON(store, typeClass, snapshot); this.updateFixtures(typeClass, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} typeClass @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: function(store, typeClass, snapshot) { this.deleteLoadedFixture(typeClass, snapshot); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param typeClass @param snapshot */ deleteLoadedFixture: function(typeClass, snapshot) { var existingFixture = this.findExistingFixture(typeClass, snapshot); if (existingFixture) { var index = ember$data$lib$adapters$fixture$adapter$$indexOf(typeClass.FIXTURES, existingFixture); typeClass.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param typeClass @param snapshot */ findExistingFixture: function(typeClass, snapshot) { var fixtures = this.fixturesForType(typeClass); 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} typeKey @param {String|Array|Object} id single id or array of ids or query @param {DS.Snapshot|Array} snapshot single snapshot or array of snapshots @param {String} requestType @return {String} url */ buildURL: function(typeKey, id, snapshot, requestType) { switch (requestType) { case 'find': return this.urlForFind(id, typeKey, snapshot); case 'findAll': return this.urlForFindAll(typeKey); case 'findQuery': return this.urlForFindQuery(id, typeKey); case 'findMany': return this.urlForFindMany(id, typeKey, snapshot); case 'findHasMany': return this.urlForFindHasMany(id, typeKey); case 'findBelongsTo': return this.urlForFindBelongsTo(id, typeKey); case 'createRecord': return this.urlForCreateRecord(typeKey, snapshot); case 'updateRecord': return this.urlForUpdateRecord(id, typeKey, snapshot); case 'deleteRecord': return this.urlForDeleteRecord(id, typeKey, snapshot); default: return this._buildURL(typeKey, id); } }, /** @method _buildURL @private @param {String} typeKey @param {String} id @return {String} url */ _buildURL: function(typeKey, id) { var url = []; var host = ember$data$lib$adapters$build$url$mixin$$get(this, 'host'); var prefix = this.urlPrefix(); var path; if (typeKey) { path = this.pathForType(typeKey); if (path) { url.push(path); } } if (id) { url.push(encodeURIComponent(id)); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url && url.charAt(0) !== '/') { url = '/' + url; } return url; }, /** * @method urlForFind * @param {String} id * @param {String} typeKey * @param {DS.Snapshot} snapshot * @return {String} url */ urlForFind: function(id, typeKey, snapshot) { return this._buildURL(typeKey, id); }, /** * @method urlForFindAll * @param {String} typeKey * @return {String} url */ urlForFindAll: function(typeKey) { return this._buildURL(typeKey); }, /** * @method urlForFindQuery * @param {Object} query * @param {String} typeKey * @return {String} url */ urlForFindQuery: function(query, typeKey) { return this._buildURL(typeKey); }, /** * @method urlForFindMany * @param {Array} ids * @param {String} type * @param {Array} snapshots * @return {String} url */ urlForFindMany: function(ids, typeKey, snapshots) { return this._buildURL(typeKey); }, /** * @method urlForFindHasMany * @param {String} id * @param {String} typeKey * @return {String} url */ urlForFindHasMany: function(id, typeKey) { return this._buildURL(typeKey, id); }, /** * @method urlForFindBelongTo * @param {String} id * @param {String} typeKey * @return {String} url */ urlForFindBelongsTo: function(id, typeKey) { return this._buildURL(typeKey, id); }, /** * @method urlForCreateRecord * @param {String} typeKey * @param {DS.Snapshot} snapshot * @return {String} url */ urlForCreateRecord: function(typeKey, snapshot) { return this._buildURL(typeKey); }, /** * @method urlForUpdateRecord * @param {String} id * @param {String} typeKey * @param {DS.Snapshot} snapshot * @return {String} url */ urlForUpdateRecord: function(id, typeKey, snapshot) { return this._buildURL(typeKey, id); }, /** * @method urlForDeleteRecord * @param {String} id * @param {String} typeKey * @param {DS.Snapshot} snapshot * @return {String} url */ urlForDeleteRecord: function(id, typeKey, snapshot) { return this._buildURL(typeKey, id); }, /** @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(typeKey) { var decamelized = Ember.String.decamelize(typeKey); return Ember.String.pluralize(decamelized); } }); ``` @method pathForType @param {String} typeKey @return {String} path **/ pathForType: function(typeKey) { var camelized = Ember.String.camelize(typeKey); 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, 'find'), '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, url; if (sinceToken) { query = { since: sinceToken }; } url = this.buildURL(type.typeKey, null, null, 'findAll'); return this.ajax(url, '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) { var url = this.buildURL(type.typeKey, query, null, 'findQuery'); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, '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) { var url = this.buildURL(type.typeKey, ids, snapshots, 'findMany'); return this.ajax(url, '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. @method findHasMany @param {DS.Store} store @param {DS.Snapshot} snapshot @param {String} url @return {Promise} promise */ findHasMany: function(store, snapshot, url, relationship) { var id = snapshot.id; var type = snapshot.typeKey; url = this.urlPrefix(url, this.buildURL(type, id, null, 'findHasMany')); return this.ajax(url, '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; url = this.urlPrefix(url, this.buildURL(type, id, null, 'findBelongsTo')); return this.ajax(url, '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); var url = this.buildURL(type.typeKey, null, snapshot, 'createRecord'); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return this.ajax(url, "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; var url = this.buildURL(type.typeKey, id, snapshot, 'updateRecord'); return this.ajax(url, "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, 'deleteRecord'), "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$model$errors$invalid$$default) { 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 = 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 = !word || 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} typeKey @return String */ pathForType: function(typeKey) { var decamelized = activemodel$adapter$lib$system$active$model$adapter$$decamelize(typeKey); 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) { var response = Ember.$.parseJSON(jqXHR.responseText); var errors = response.errors ? response.errors : response; return new ember$data$lib$system$model$errors$invalid$$default(errors); } 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} typeClass @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} typeClass @param {Object} hash @return {Object} */ normalize: function(typeClass, 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 { "firstName": "Harry", "lastName": "Houdini", "career": "magician" } ``` Note that the `admin` is now not included in the payload. @property attrs @type {Object} */ mergedProperties: ['attrs'], /** 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} typeClass @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function(typeClass, data) { typeClass.eachTransformedAttribute(function applyTransform(key, typeClass) { if (!data.hasOwnProperty(key)) { return; } var transform = this.transformFor(typeClass); 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(typeClass, hash) { var fields = Ember.get(typeClass, '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} typeClass @param {Object} hash @return {Object} */ normalize: function(typeClass, hash) { if (!hash) { return hash; } this.normalizeId(hash); this.normalizeAttributes(typeClass, hash); this.normalizeRelationships(typeClass, hash); this.normalizeUsingDeclaredMapping(typeClass, hash); this.applyTransforms(typeClass, 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(typeClass, hash) { var payloadKey; if (this.keyForAttribute) { typeClass.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key, 'deserialize'); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(typeClass, hash) { var payloadKey; if (this.keyForRelationship) { typeClass.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind, 'deserialize'); if (key === payloadKey) { return; } if (!hash.hasOwnProperty(payloadKey)) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(typeClass, 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(typeClass, hash) { this.normalizeId(hash); this.normalizeAttributes(typeClass, hash); this.normalizeRelationships(typeClass, hash); this.normalizeUsingDeclaredMapping(typeClass, 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} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function(hash, typeClass, 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, 'serialize'); } 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", "serialize") : 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", "serialize"); } //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", "serialize"); } 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, "serialize") : 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 typeClass = store.modelFor(message.modelName); var serializer = store.serializerFor(typeClass.typeKey); var record = serializer.extract(store, typeClass, data, data.id, 'single'); store.push(message.modelName, record); }); ``` @method extract @param {DS.Store} store @param {subclass of DS.Model} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function(store, typeClass, payload, id, requestType) { this.extractMeta(store, typeClass, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, typeClass, 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} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindAll: function(store, typeClass, payload, id, requestType) { return this.extractArray(store, typeClass, 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, typeClass, payload, id, requestType) { return this.extractArray(store, typeClass, 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} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindMany: function(store, typeClass, payload, id, requestType) { return this.extractArray(store, typeClass, 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} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractFindHasMany: function(store, typeClass, payload, id, requestType) { return this.extractArray(store, typeClass, 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} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractCreateRecord: function(store, typeClass, payload, id, requestType) { return this.extractSave(store, typeClass, 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} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractUpdateRecord: function(store, typeClass, payload, id, requestType) { return this.extractSave(store, typeClass, 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} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractDeleteRecord: function(store, typeClass, payload, id, requestType) { return this.extractSave(store, typeClass, 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} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractFind: function(store, typeClass, payload, id, requestType) { return this.extractSingle(store, typeClass, 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} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractFindBelongsTo: function(store, typeClass, payload, id, requestType) { return this.extractSingle(store, typeClass, 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, typeClass, payload, id, requestType) { return this.extractSingle(store, typeClass, 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, typeClass, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, typeClass, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extractSingle: function(store, typeClass, payload, id, requestType) { var normalizedPayload = this.normalizePayload(payload); return this.normalize(typeClass, normalizedPayload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractArray: function(store, typeClass, payload) { return payload.map(function(json) { return this.extractSingle(store, typeClass, json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {subclass of DS.Model} typeClass @param {Object} payload @param {String or Number} id @param {String} requestType @return {Array} array An array of deserialized objects */ extractArray: function(store, typeClass, 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(typeClass, 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, typeClass, payload) { if (payload && payload._pagination) { store.setMetadataFor(typeClass, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {subclass of DS.Model} typeClass @param {Object} payload */ extractMeta: function(store, typeClass, payload) { if (payload && payload.meta) { store.setMetadataFor(typeClass, 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, typeClass, payload, id) { if (payload && typeof payload === 'object' && payload._problems) { payload = payload._problems; this.normalizeErrors(typeClass, payload); } return payload; } }); ``` @method extractErrors @param {DS.Store} store @param {subclass of DS.Model} typeClass @param {Object} payload @param {String or Number} id @return {Object} json The deserialized errors */ extractErrors: function(store, typeClass, payload, id) { if (payload && typeof payload === 'object' && payload.errors) { payload = payload.errors; this.normalizeErrors(typeClass, 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, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @param {String} method @return {String} normalized key */ keyForAttribute: function(key, method) { return key; }, /** `keyForRelationship` can be used to define a custom key when serializing and deserializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship, method) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} relationship typeClass @param {String} method @return {String} normalized key */ keyForRelationship: function(key, typeClass, method) { 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); 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, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, the kind of relationship (`hasMany` or `belongsTo`) as the second parameter, and the method (`serialize` or `deserialize`) as the third 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} typeClass @param {Object} hash @param {String} prop @return {Object} */ normalize: function(typeClass, hash, prop) { this.normalizeId(hash); this.normalizeAttributes(typeClass, hash); this.normalizeRelationships(typeClass, hash); this.normalizeUsingDeclaredMapping(typeClass, hash); if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](hash); } this.applyTransforms(typeClass, 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, typeClass, payload, id) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, typeClass, 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} primaryTypeClasss @param {Object} payload @param {String} recordId @return {Object} the primary response to the original request */ extractSingle: function(store, primaryTypeClass, rawPayload, recordId) { var payload = this.normalizePayload(rawPayload); var primaryTypeClassName = primaryTypeClass.typeKey; var primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop); if (!store.modelFactoryFor(typeName)) { continue; } var type = store.modelFor(typeName); var isPrimary = type.typeKey === primaryTypeClassName; var value = payload[prop]; if (value === null) { continue; } // legacy support for singular resources if (isPrimary && Ember.typeOf(value) !== "array" ) { primaryRecord = this.normalize(primaryTypeClass, 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: posts }; 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} primaryTypeClass @param {Object} payload @return {Array} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryTypeClass, rawPayload) { var payload = this.normalizePayload(rawPayload); var primaryTypeClassName = primaryTypeClass.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)) { continue; } var type = store.modelFor(typeName); var typeSerializer = store.serializerFor(type); var isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeClassName)); /*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 typeKey = this.typeForRoot(prop); if (!store.modelFactoryFor(typeKey, prop)) { continue; } var type = store.modelFor(typeKey); 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(typeKey, 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} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function(hash, typeClass, snapshot, options) { hash[typeClass.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, "serialize") : key; if (Ember.isNone(belongsTo)) { json[key + "Type"] = null; } else { json[key + "Type"] = Ember.String.camelize(belongsTo.typeKey); } } }); 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$$classify = Ember.String.classify; 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} relationshipTypeKey @param {String} kind @return String */ keyForRelationship: function(relationshipTypeKey, kind) { var key = activemodel$adapter$lib$system$active$model$serializer$$decamelize(relationshipTypeKey); 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} typeClass @param {DS.Snapshot} snapshot @param {Object} options */ serializeIntoHash: function(data, typeClass, snapshot, options) { var root = activemodel$adapter$lib$system$active$model$serializer$$underscore(activemodel$adapter$lib$system$active$model$serializer$$decamelize(typeClass.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$$classify(belongsTo.typeKey).replace(/(\/)([a-z])/g, function(match, separator, chr) { return match.toUpperCase(); }).replace('/', '::'); } }, // 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} typeClass @param {Object} hash @param {String} prop @return Object */ normalize: function(typeClass, hash, prop) { this.normalizeLinks(hash); return this._super(typeClass, 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"} } ``` @param {Subclass of DS.Model} typeClass @method normalizeRelationships @private */ normalizeRelationships: function(typeClass, hash) { if (this.keyForRelationship) { typeClass.eachRelationship(function(key, relationship) { var payloadKey, payload; if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key, "deserialize"); 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, "deserialize"); if (!hash.hasOwnProperty(payloadKey)) { return; } payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } }, typeForRoot: function(key) { return activemodel$adapter$lib$system$active$model$serializer$$camelize(ember$inflector$lib$lib$system$string$$singularize(key)).replace(/(^|\:)([A-Z])/g, function(match, separator, chr) { return match.toLowerCase(); }).replace('::', '/'); } }); 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() { }; 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.17' }); 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 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, typeClass, id, record) { var snapshot = record._createSnapshot(); var promise = adapter.find(store, typeClass, id, snapshot); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, typeClass); var label = "DS: Handle Adapter#find of " + typeClass + " 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) { return store._adapterRun(function() { var payload = serializer.extract(store, typeClass, adapterPayload, id, 'find'); return store.push(typeClass, payload); }); }, function(error) { record.notFound(); if (ember$data$lib$system$store$finders$$get(record, 'isEmpty')) { store.unloadRecord(record); } throw error; }, "DS: Extract payload of '" + typeClass + "'"); } function ember$data$lib$system$store$finders$$_findMany(adapter, store, typeClass, ids, records) { var snapshots = Ember.A(records).invoke('_createSnapshot'); var promise = adapter.findMany(store, typeClass, ids, snapshots); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, typeClass); var label = "DS: Handle Adapter#findMany of " + typeClass; 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, typeClass, adapterPayload, null, 'findMany'); return store.pushMany(typeClass, payload); }); }, null, "DS: Extract payload of " + typeClass); } 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'); 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, typeClass, sinceToken) { var promise = adapter.findAll(store, typeClass, sinceToken); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, typeClass); var label = "DS: Handle Adapter#findAll of " + typeClass; 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, typeClass, adapterPayload, null, 'findAll'); store.pushMany(typeClass, payload); }); store.didUpdateAll(typeClass); return store.all(typeClass); }, null, "DS: Extract payload of findAll " + typeClass); } function ember$data$lib$system$store$finders$$_findQuery(adapter, store, typeClass, query, recordArray) { var promise = adapter.findQuery(store, typeClass, query, recordArray); var serializer = ember$data$lib$system$store$serializers$$serializerForAdapter(store, adapter, typeClass); var label = "DS: Handle Adapter#findQuery of " + typeClass; 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, typeClass, adapterPayload, null, 'findQuery'); }); recordArray.load(payload); return recordArray; }, null, "DS: Extract payload of findQuery " + typeClass); } 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) { 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 */ 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 typeClass = record.constructor; var recordArrays = this.filteredRecordArrays.get(typeClass); 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, typeClass, record); } }, this); }, //Need to update live arrays on loading recordWasLoaded: function(record) { var typeClass = record.constructor; var recordArrays = this.filteredRecordArrays.get(typeClass); 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, typeClass, record); }, this); }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {subclass of DS.Model} typeClass @param {Number|String} clientId */ updateRecordArray: function(array, filter, typeClass, 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} typeKey @param {Function} filter */ updateFilter: function(array, typeKey, filter) { var typeMap = this.store.typeMapFor(typeKey); 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, typeKey, record); } } }, /** Create a `DS.RecordArray` for a type and register it for updates. @method createRecordArray @param {Class} typeClass @return {DS.RecordArray} */ createRecordArray: function(typeClass) { var array = ember$data$lib$system$record$arrays$record$array$$default.create({ type: typeClass, content: Ember.A(), store: this.store, isLoaded: true, manager: this }); this.registerFilteredRecordArray(array, typeClass); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {subclass of DS.Model} typeClass @param {Function} filter @param {Object} query (optional @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function(typeClass, filter, query) { var array = ember$data$lib$system$record$arrays$filtered$record$array$$default.create({ query: query, type: typeClass, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, typeClass, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {subclass of DS.Model} typeClass @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function(typeClass, query) { var array = ember$data$lib$system$record$arrays$adapter$populated$record$array$$default.create({ type: typeClass, 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 {subclass of DS.Model} typeClass @param {Function} filter */ registerFilteredRecordArray: function(array, typeClass, filter) { var recordArrays = this.filteredRecordArrays.get(typeClass); recordArrays.push(array); this.updateFilter(array, typeClass, 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) { }, // 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$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 model.errors.messages as |message|}} <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; this.hasData = false; }; 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(); this.setHasData(true); }, 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(); } this.setHasData(true); }, 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) { 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); self.setHasData(true); }, notifyRecordRelationshipAdded: Ember.K, notifyRecordRelationshipRemoved: Ember.K, setHasData: function(value) { this.hasData = value; } }; 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) { return this.currentState[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; record = store.createRecord(type, hash); this.pushObject(record); return record; }, /** @method addRecord @param {DS.Model} record @deprecated Use `addObject()` instead */ addRecord: function(record) { this.addObject(record); }, /** @method removeRecord @param {DS.Model} record @deprecated Use `removeObject()` instead */ removeRecord: function(record) { 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; 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 { //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); } this.setHasData(true); }; 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); } this.setHasData(true); }; 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; 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'); 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 { 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; 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' // store.push('comment', { id: 1, body: 'Lorem ipsum' }); commentSnapshot.belongsTo('post'); // => undefined ``` Calling `belongsTo` will return a new Snapshot as long as there's any known data for the relationship available, such as an ID. If the relationship is known but unset, `belongsTo` will return `null`. If the contents of the relationship is unknown `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|null|undefined} A snapshot or ID of a known relationship or null if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ belongsTo: function(keyName, options) { var id = options && options.id; var relationship, inverseRecord, hasData; var result; 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."); } hasData = ember$data$lib$system$snapshot$$get(relationship, 'hasData'); inverseRecord = ember$data$lib$system$snapshot$$get(relationship, 'inverseRecord'); if (hasData) { if (inverseRecord) { if (id) { result = ember$data$lib$system$snapshot$$get(inverseRecord, 'id'); } else { result = inverseRecord._createSnapshot(); } } else { result = null; } } if (id) { this._belongsToIds[keyName] = result; } else { 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'] // store.push('post', { id: 1, title: 'Hello World' }); postSnapshot.hasMany('comments'); // => undefined ``` Note: Relationships are loaded lazily and cached upon first access. @method hasMany @param {String} keyName @param {Object} [options] @return {Array|undefined} An array of snapshots or IDs of a known relationship or an empty array if the relationship is known but unset. undefined will be returned if the contents of the relationship is unknown. */ hasMany: function(keyName, options) { var ids = options && options.ids; var relationship, members, hasData; var results; 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."); } hasData = ember$data$lib$system$snapshot$$get(relationship, 'hasData'); members = ember$data$lib$system$snapshot$$get(relationship, 'members'); if (hasData) { results = []; members.forEach(function(member) { if (ids) { results.push(ember$data$lib$system$snapshot$$get(member, 'id')); } else { results.push(member._createSnapshot()); } }); } if (ids) { this._hasManyIds[keyName] = results; } else { 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) { 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() { 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 = [ 'currentState', 'data', 'store' ]; var ember$data$lib$system$model$model$$retrieveFromCurrentState = Ember.computed('currentState', function(key) { 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 model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <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 model.errors.messages as |message|}} <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, /** Fired when the record is rolled back. @event rolledBack */ rolledBack: 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) { 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) { 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$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('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }, "DS: Model#reload complete, update flags")['finally'](function () { record.set('isReloading', false); 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; }, attr: function() { }, belongsTo: function() { }, hasMany: function() { } }); 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; var ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter; try { Ember.computed({ get: function() { }, set: function() { } }); ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter = true; } catch(e) { ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter = false; } var ember$data$lib$utils$supports$computed$getter$setter$$default = ember$data$lib$utils$supports$computed$getter$setter$$supportsComputedGetterSetter; var ember$data$lib$utils$computed$polyfill$$computed = Ember.computed; var ember$data$lib$utils$computed$polyfill$$default = function() { var polyfillArguments = []; var config = arguments[arguments.length - 1]; if (typeof config === 'function' || ember$data$lib$utils$supports$computed$getter$setter$$default) { return ember$data$lib$utils$computed$polyfill$$computed.apply(null, arguments); } for (var i = 0, l = arguments.length - 1; i < l; i++) { polyfillArguments.push(arguments[i]); } var func; if (config.set) { func = function(key, value) { if (arguments.length > 1) { return config.set.call(this, key, value); } else { return config.get.call(this, key); } }; } else { func = function(key) { return config.get.call(this, key); }; } polyfillArguments.push(func); return ember$data$lib$utils$computed$polyfill$$computed.apply(null, polyfillArguments); }; /** @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) { 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$data$lib$utils$computed$polyfill$$default({ get: function(key) { 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); } }, set: function(key, value) { 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; } }).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'); 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} typeKey @param {Object} properties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function(typeKey, inputProperties) { var typeClass = this.modelFor(typeKey); 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(typeClass, properties); } // Coerce ID to a string properties.id = ember$data$lib$system$store$$coerceId(properties.id); var record = this.buildRecord(typeClass, 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); record.eachRelationship(function(key, descriptor) { record._relationships[key].setHasData(true); }); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} typeKey @param {Object} properties from the new record @return {String} if the adapter can generate one, an ID */ _generateId: function(typeKey, properties) { var adapter = this.adapterFor(typeKey); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this, typeKey, 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} typeKey @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(typeKey, id, preload) { if (arguments.length === 1) { return this.findAll(typeKey); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(typeKey, id); } return this.findById(typeKey, 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} typeKey @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(typeKey, id, preload) { if (this.hasRecordForId(typeKey, id)) { return this.getById(typeKey, id).reload(); } else { return this.find(typeKey, 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} typeKey @return {Promise} promise */ fetchAll: function(typeKey) { var typeClass = this.modelFor(typeKey); return this._fetchAll(typeClass, this.all(typeKey)); }, /** @method fetch @param {String} typeKey @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(typeKey, id, preload) { return this.fetchById(typeKey, id, preload); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String} typeKey @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(typeKey, id, preload) { var typeClass = this.modelFor(typeKey); var record = this.recordForId(typeClass, 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} typeKey @param {Array} ids @return {Promise} promise */ findByIds: function(typeKey, 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(typeKey, id); })).then(Ember.A, null, "DS: Store#findByIds of " + typeKey + " 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 typeClass = record.constructor; var id = ember$data$lib$system$store$$get(record, 'id'); var adapter = this.adapterFor(typeClass); var promise = ember$data$lib$system$store$finders$$_find(adapter, this, typeClass, 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 typeClass = record.constructor; if (ember$data$lib$system$store$$isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } var resolver = Ember.RSVP.defer('Fetching ' + typeClass + 'with id: ' + record.get('id')); var recordResolverPair = { record: record, resolver: resolver }; var promise = resolver.promise; record.loadingData(promise); if (!this._pendingFetch.get(typeClass)) { this._pendingFetch.set(typeClass, [recordResolverPair]); } else { this._pendingFetch.get(typeClass).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, typeClass) { var store = this; var adapter = store.adapterFor(typeClass); 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) { } 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, typeClass, 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 { } }); } 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'); 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(typeKey, inputId) { var typeClass = this.modelFor(typeKey); var id = ember$data$lib$system$store$$coerceId(inputId); var record = this.typeMapFor(typeClass).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} typeKey @param {String|Integer} id @return {DS.Model} record */ recordForId: function(typeKey, inputId) { var typeClass = this.modelFor(typeKey); var id = ember$data$lib$system$store$$coerceId(inputId); var idToRecord = this.typeMapFor(typeClass).idToRecord; var record = idToRecord[id]; if (!record || !idToRecord[id]) { record = this.buildRecord(typeClass, 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 {Promise} promise */ 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); 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); 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); 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} typeKey @return {DS.AdapterPopulatedRecordArray} */ findAll: function(typeKey) { return this.fetchAll(typeKey); }, /** @method _fetchAll @private @param {DS.Model} typeClass @param {DS.RecordArray} array @return {Promise} promise */ _fetchAll: function(typeClass, array) { var adapter = this.adapterFor(typeClass); var sinceToken = this.typeMapFor(typeClass).metadata.since; ember$data$lib$system$store$$set(array, 'isUpdating', true); return ember$data$lib$system$promise$proxies$$promiseArray(ember$data$lib$system$store$finders$$_findAll(adapter, this, typeClass, sinceToken)); }, /** @method didUpdateAll @param {DS.Model} typeClass */ didUpdateAll: function(typeClass) { var findAllCache = this.typeMapFor(typeClass).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} typeKey @return {DS.RecordArray} */ all: function(typeKey) { var typeClass = this.modelFor(typeKey); var typeMap = this.typeMapFor(typeClass); var findAllCache = typeMap.findAllCache; if (findAllCache) { this.recordArrayManager.updateFilter(findAllCache, typeClass); return findAllCache; } var array = this.recordArrayManager.createRecordArray(typeClass); typeMap.findAllCache = array; return array; }, /** This method unloads all records in the store. Optionally you can pass a type which unload all records for a given type. ```javascript store.unloadAll(); store.unloadAll('post'); ``` @method unloadAll @param {String} optional typeKey */ unloadAll: function(typeKey) { if (arguments.length === 0) { var typeMaps = this.typeMaps; var keys = Ember.keys(typeMaps); var types = ember$data$lib$system$store$$map(keys, byType); ember$data$lib$system$store$$forEach(types, this.unloadAll, this); } else { var typeClass = this.modelFor(typeKey); var typeMap = this.typeMapFor(typeClass); 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; typeMap.metadata = Ember.create(null); } function byType(entry) { return typeMaps[entry]['type']; } }, /** 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 typeClass = this.modelFor(typeName); return this.typeMapFor(typeClass).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 typeClass = this.modelFor(typeName); Ember.merge(this.typeMapFor(typeClass).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); 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} typeClass @return {Object} typeMap */ typeMapFor: function(typeClass) { var typeMaps = ember$data$lib$system$store$$get(this, 'typeMaps'); var guid = Ember.guidFor(typeClass); var typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: Ember.create(null), records: [], metadata: Ember.create(null), type: typeClass }; 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) { 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) { } // 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); } 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) { 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) { 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; // 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) { 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() { this.recordArrayManager.destroy(); this.unloadAll(); 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; } 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 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; } 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; 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); } store.didSaveRecord(record, payload); }); return record; }, function(reason) { if (reason instanceof ember$data$lib$system$model$errors$invalid$$default) { 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$model$errors$invalid$$default(errors); } else { store.recordWasError(record, reason); } throw reason; }, label); } function ember$data$lib$system$store$$setupRelationships(store, record, data) { var typeClass = record.constructor; typeClass.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 (value !== undefined) { if (kind === 'belongsTo') { relationship.setCanonicalRecord(value); } else if (kind === 'hasMany') { 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) { 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(typeClass) { return typeClass !== ember$data$lib$system$model$$default && ember$data$lib$system$model$$default.detect(typeClass); }, columnsForType: function(typeClass) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; ember$data$lib$system$debug$debug$adapter$$get(typeClass, '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(typeKey) { return this.get('store').all(typeKey); }, 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 for deserialization. If a model is declared embedded for deserialization (`embedded: 'always'`, `deserialize: 'record'` or `deserialize: 'records'`), 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} typeClass @param {Object} hash to be normalized @param {String} key the hash has been referenced by @return {Object} the normalized hash **/ normalize: function(typeClass, hash, prop) { var normalizedHash = this._super(typeClass, hash, prop); return ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedRecords(this, this.store, typeClass, normalizedHash); }, keyForRelationship: function(key, typeClass, method) { if ((method === 'serialize' && this.hasSerializeRecordsOption(key)) || (method === 'deserialize' && this.hasDeserializeRecordsOption(key))) { return this.keyForAttribute(key, method); } else { return this._super(key, typeClass, method) || 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, 'serialize'); if (!embeddedSnapshot) { json[key] = null; } else { json[key] = embeddedSnapshot.id; } } else if (includeRecords) { key = this.keyForAttribute(attr, 'serialize'); 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, 'serialize'); json[key] = snapshot.hasMany(attr, { ids: true }); } else if (includeRecords) { key = this.keyForAttribute(attr, 'serialize'); 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, 'deserialize'); 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, typeClass, partial) { typeClass.eachRelationship(function(key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { var embeddedTypeClass = 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, embeddedTypeClass, 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, embeddedTypeClass, partial); } } } }); return partial; } // handles embedding for `hasMany` relationship function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedHasMany(store, key, embeddedTypeClass, hash) { if (!hash[key]) { return hash; } var ids = []; var embeddedSerializer = store.serializerFor(embeddedTypeClass.typeKey); ember$data$lib$serializers$embedded$records$mixin$$forEach(hash[key], function(data) { var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null); store.push(embeddedTypeClass, 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 embeddedTypeClass = store.modelFor(typeKey); var primaryKey = ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'primaryKey'); var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null); store.push(embeddedTypeClass, embeddedRecord); ids.push({ id: embeddedRecord[primaryKey], type: typeKey }); }); hash[key] = ids; return hash; } function ember$data$lib$serializers$embedded$records$mixin$$extractEmbeddedBelongsTo(store, key, embeddedTypeClass, hash) { if (!hash[key]) { return hash; } var embeddedSerializer = store.serializerFor(embeddedTypeClass.typeKey); var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, hash[key], null); store.push(embeddedTypeClass, 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 embeddedTypeClass = store.modelFor(typeKey); var primaryKey = ember$data$lib$serializers$embedded$records$mixin$$get(embeddedSerializer, 'primaryKey'); var embeddedRecord = embeddedSerializer.normalize(embeddedTypeClass, data, null); store.push(embeddedTypeClass, 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; } options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo', key: null }; return ember$data$lib$utils$computed$polyfill$$default({ get: function(key) { return this._relationships[key].getRecord(); }, set: function(key, value) { 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; } 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, typeClass; typeKey = meta.type || meta.key; if (typeof typeKey === 'string') { if (meta.kind === 'hasMany') { typeKey = ember$inflector$lib$lib$system$string$$singularize(typeKey); } typeClass = store.modelFor(typeKey); } else { typeClass = meta.type; } return typeClass; } 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 typeKey; 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; typeKey = ember$data$lib$system$relationship$meta$$typeForRelationshipMeta(this.store, meta); if (!types.contains(typeKey)) { types.push(typeKey); } } }); 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; //If inverse is specified manually, return the inverse if (options.inverse) { inverseName = options.inverse; inverse = Ember.get(inverseType, 'relationshipsByName').get(inverseName); 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; }); if (filteredRelationships.length === 1 ) { possibleRelationships = filteredRelationships; } 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$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$model$errors$invalid$$default; 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);
sites/all/modules/jquery_update/replace/jquery/1.11/jquery.js
TechBK/noname
/*! * jQuery JavaScript Library v1.11.2 * 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-12-17T15:27Z */ (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 support = {}; var version = "1.11.2", // 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, IE<9 // 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: 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 // adding 1 corrects loss of precision from parseFloat (#15100) return !jQuery.isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 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; }, // Support: Android<4.1, IE<9 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 ) { 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 v2.2.0-pre * http://sizzlejs.com/ * * Copyright 2008, 2014 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2014-12-16 */ (function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // General-purpose constants 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 as it's faster than native // http://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // 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 rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + 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 ); }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }; // 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 || []; nodeType = context.nodeType; if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } if ( !seed && documentIsHTML ) { // Try to shortcut find operations when possible (e.g., not under DocumentFragment) if ( nodeType !== 11 && (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 ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType !== 1 && 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 !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, parent, doc = node ? node.ownerDocument || node : preferredDoc; // 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; parent = doc.defaultView; // 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", unloadHandler, false ); } else if ( parent.attachEvent ) { parent.attachEvent( "onunload", unloadHandler ); } } /* Support tests ---------------------------------------------------------------------- */ documentIsHTML = !isXML( doc ); /* 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; }); // Support: IE<9 support.getElementsByClassName = rnative.test( doc.getElementsByClassName ); // 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 !== "undefined" && 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 !== "undefined" && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( 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 docElem.appendChild( div ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\f]' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( div.querySelectorAll("[msallowcapture^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.2+, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.7+ if ( !div.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push("~="); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibing-combinator selector` fails if ( !div.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push(".#.+[+~]"); } }); 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( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return 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 !== "undefined" && 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.replace( rwhitespace, " " ) + " " ).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( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[0] = null; return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( 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( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( 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-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( 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.triggerHandler ) { jQuery( document ).triggerHandler( "ready" ); jQuery( document ).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; // Execute ASAP in case we need to set body.style.zoom jQuery(function() { // Minified: var a,b,c,d var val, div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Return for frameset docs that don't have a body return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; 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 = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1"; support.inlineBlockNeedsLayout = val = div.offsetWidth === 3; if ( val ) { // 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 ); }); (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-- ) { // 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 ] ); } } } 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() { // Minified: var a,b,c var input = document.createElement( "input" ), div = document.createElement( "div" ), fragment = document.createDocumentFragment(); // Setup div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // 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; } } })(); (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|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 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 ) { // 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 = 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, 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 ) { 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() { 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 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; } }; }); // 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 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 ].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 shrinkWrapBlocksVal; support.shrinkWrapBlocks = function() { if ( shrinkWrapBlocksVal != null ) { return shrinkWrapBlocksVal; } // Will be changed later if needed. shrinkWrapBlocksVal = false; // Minified: var b,c,d var div, body, container; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); // Support: IE6 // Check if elements with layout shrink-wrap their children if ( typeof div.style.zoom !== strundefined ) { // Reset CSS: box-sizing; display; margin; border 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:1px;width:1px;zoom:1"; div.appendChild( document.createElement( "div" ) ).style.width = "5px"; shrinkWrapBlocksVal = div.offsetWidth !== 3; } body.removeChild( container ); 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 ) { // Support: IE<=11+, Firefox<=30+ (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" if ( elem.ownerDocument.defaultView.opener ) { return elem.ownerDocument.defaultView.getComputedStyle( elem, null ); } return window.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() { // Minified: var b,c,d,e,f,g, h,i var div, style, a, pixelPositionVal, boxSizingReliableVal, reliableHiddenOffsetsVal, reliableMarginRightVal; // Setup div = document.createElement( "div" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; a = div.getElementsByTagName( "a" )[ 0 ]; style = a && a.style; // Finish early in limited (non-browser) environments if ( !style ) { return; } style.cssText = "float:left;opacity:.5"; // Support: IE<9 // Make sure that element opacity exists (as opposed to filter) support.opacity = style.opacity === "0.5"; // Verify style float existence // (IE uses styleFloat instead of cssFloat) support.cssFloat = !!style.cssFloat; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Support: Firefox<29, Android 2.3 // Vendor-prefix box-sizing support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" || style.WebkitBoxSizing === ""; jQuery.extend(support, { reliableHiddenOffsets: function() { if ( reliableHiddenOffsetsVal == null ) { computeStyleTests(); } return reliableHiddenOffsetsVal; }, boxSizingReliable: function() { if ( boxSizingReliableVal == null ) { computeStyleTests(); } return boxSizingReliableVal; }, pixelPosition: function() { if ( pixelPositionVal == null ) { computeStyleTests(); } return pixelPositionVal; }, // Support: Android 2.3 reliableMarginRight: function() { if ( reliableMarginRightVal == null ) { computeStyleTests(); } return reliableMarginRightVal; } }); function computeStyleTests() { // Minified: var b,c,d,j var div, body, container, contents; body = document.getElementsByTagName( "body" )[ 0 ]; if ( !body || !body.style ) { // Test fired too early or in an unsupported environment, exit. return; } // Setup div = document.createElement( "div" ); container = document.createElement( "div" ); container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px"; body.appendChild( container ).appendChild( div ); 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"; // Support: IE<9 // Assume reasonable values in the absence of getComputedStyle pixelPositionVal = boxSizingReliableVal = false; reliableMarginRightVal = true; // Check for getComputedStyle so that this code is not run in IE<9. if ( window.getComputedStyle ) { pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; boxSizingReliableVal = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // 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 contents = div.appendChild( document.createElement( "div" ) ); // Reset CSS: box-sizing; display; margin; border; padding contents.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"; contents.style.marginRight = contents.style.width = "0"; div.style.width = "1px"; reliableMarginRightVal = !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight ); div.removeChild( contents ); } // 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>"; contents = div.getElementsByTagName( "td" ); contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; if ( reliableHiddenOffsetsVal ) { contents[ 0 ].style.display = ""; contents[ 1 ].style.display = "none"; reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0; } body.removeChild( container ); } })(); // 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 { 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, "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": 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 { 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 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, 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, checkDisplay, 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" ); // Test default display if display is currently "none" checkDisplay = display === "none" ? jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display; if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "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 ); // 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 = 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; } } } // 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 || 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() { // Minified: var a,b,c,d,e var input, div, select, a, opt; // Setup div = document.createElement( "div" ); 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"; })(); 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 ]; // 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 // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on 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 }); }; }); 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) // See https://support.microsoft.com/kb/2856746 for more info if ( window.attachEvent ) { window.attachEvent( "onunload", 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 = jQuery.trim( 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.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. // 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; }));
src/svg-icons/device/signal-cellular-connected-no-internet-3-bar.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceSignalCellularConnectedNoInternet3Bar = (props) => ( <SvgIcon {...props}> <path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M17 22V7L2 22h15zm3-12v8h2v-8h-2zm0 12h2v-2h-2v2z"/> </SvgIcon> ); DeviceSignalCellularConnectedNoInternet3Bar = pure(DeviceSignalCellularConnectedNoInternet3Bar); DeviceSignalCellularConnectedNoInternet3Bar.displayName = 'DeviceSignalCellularConnectedNoInternet3Bar'; export default DeviceSignalCellularConnectedNoInternet3Bar;
packages/material-ui-icons/src/AppsRounded.js
kybarg/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M4 8h4V4H4v4zm6 12h4v-4h-4v4zm-6 0h4v-4H4v4zm0-6h4v-4H4v4zm6 0h4v-4h-4v4zm6-10v4h4V4h-4zm-6 4h4V4h-4v4zm6 6h4v-4h-4v4zm0 6h4v-4h-4v4z" /> , 'AppsRounded');
src/ButtonToolbar.js
westonplatter/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; const ButtonToolbar = React.createClass({ mixins: [BootstrapMixin], getDefaultProps() { return { bsClass: 'button-toolbar' }; }, render() { let classes = this.getBsClassSet(); return ( <div {...this.props} role="toolbar" className={classNames(this.props.className, classes)}> {this.props.children} </div> ); } }); export default ButtonToolbar;
github-battle-es6/app/components/App.js
josedab/react-exercises
import React from 'react'; import Popular from './Popular'; import {BrowserRouter as Router,Route, Switch} from 'react-router-dom'; import Nav from './Nav'; import Home from './Home'; import Battle from './Battle'; import Results from './Results'; class App extends React.Component { render() { return ( <Router> <div className='container'> <Nav /> <Switch> <Route exact path='/' component={Home}/> <Route exact path='/battle' component={Battle}/> <Route path='/battle/results' component={Results}/> <Route path='/popular' component={Popular}/> <Route render={ function(){ return <p>Not found</p> } }/> </Switch> </div> </Router> ) } } export default App;
App/db/entities/content/Event.js
nthbr/mamasound.fr
/* * Copyright (c) 2017. Caipi Labs. All rights reserved. * * This File is part of Caipi. You can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * This project is dual licensed under AGPL and Commercial Licence. * * @author : Nathanael Braun * @contact : [email protected] */ /** * @author Nathanael BRAUN * * Date: 24/11/2015 * Time: 19:18 */ import React from 'react'; import {types, validate} from 'App/db/field'; export default { label : "Événements", adminRoute : "Événements/Tous", disallowCreate : true, aliasField : "title", labelField : "title", previewField : "previewImage", wwwRoute : "Evenements", autoMount : ["category", "place"], searchableFields : ["title", "resume", "description"], // processResult : { // "get" : function ( record, cuser ) { // if ( !record._public ) // if ( !cuser || !cuser.isPublisher ) { // //console.log('hidden', record); // return null; // } // return record; // } // }, schema : { title : [validate.mandatory, validate.noHtml], // previewImage : [validate.isImage] }, fields : { "_id" : types.indexes, "_public" : types.boolean("Publier :", false), "title" : types.labels(), "previewImage" : types.media({allowedTypes : "Image"}, "Preview :"), "artists" : types.collection(["Artist"], {}, "Groupes / artistes :"), "resume" : types.labels('Resumé'), // TODO refactor as "summary" "description" : types.descriptions('Description'), "price" : types.labels('Prix'), "startTM" : types.date("Début"), "endTM" : types.date("Fin"), "schedule" : types.datesList("Occurences"), "fbLink" : types.labels("Event facebook"), "category" : types.picker(["EventCategory"], {storeTypedItem : true}, "Style d'événement"), "place" : types.picker(["Place"], {storeTypedItem : true}, "Lieu"), "linkedMedia" : types.collection(["Image","Video","Audio"], { storeTypedItem: true, allowedUploadTypes:["Image","Video"], allowUpload: true }, "Média lié :"), } };
packages/cf-component-pagination/test/Pagination.js
mdno/mdno.github.io
import React from 'react'; import { Pagination, PaginationRoot } from '../../cf-component-pagination/src/index'; import { felaSnapshot } from 'cf-style-provider'; test('should render', () => { const snapshot = felaSnapshot( <Pagination PaginationRoot={PaginationRoot}>Pagination</Pagination> ); expect(snapshot.component).toMatchSnapshot(); expect(snapshot.styles).toMatchSnapshot(); }); test('should render with info', () => { const snapshot = felaSnapshot( <Pagination info="Pagination Info" PaginationRoot={PaginationRoot}> Pagination </Pagination> ); expect(snapshot.component).toMatchSnapshot(); expect(snapshot.styles).toMatchSnapshot(); });
src/app/BeerSaved.js
lolamastro/beerswap
import React, {Component} from 'react'; import Paper from 'material-ui/Paper'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import {muiTheme} from './ColorScheme'; import RaisedButton from 'material-ui/RaisedButton'; const styles = { container: { textAlign: 'center', paddingTop: 20, }, paper: { height: 200, width: 340, margin: 20, padding: 50, textAlign: 'center', display: 'inline-block' } }; class BeerSaved extends Component { constructor(props, context) { super(props, context); this.handleViewSwap = this.handleViewSwap.bind(this); let swapId = this.props.params['swapId']; this.state = { swapId: swapId }; } componentDidMount() { let me = this; let swapId = this.state.swapId; setTimeout(goToBeerList, 4000); function goToBeerList() { me.props.router.push('/beers/' + swapId); } } handleViewSwap = () => { let swapId = this.state.swapId; this.props.router.push('/beers/' + swapId); } render() { return ( <MuiThemeProvider muiTheme={muiTheme}> <div style={styles.container}> <img src="images/logo.png" className="logo-sm" /> <br/> <Paper style={styles.paper} zDepth={2}> <h1>Your beer was saved.</h1> <p className="instructions">We'll send you a reminder email before the swap.</p> <ViewSwapButton handleViewSwap={this.handleViewSwap}></ViewSwapButton> </Paper> </div> </MuiThemeProvider> ); } } class ViewSwapButton extends React.Component { render() { return ( <RaisedButton style={styles.button} label="View Beers" secondary={true} onTouchTap={this.props.handleViewSwap} /> ); } } export default BeerSaved;
src/components/icons/PhoneIcon.js
austinknight/ui-components
import React from 'react'; const PhoneIcon = props => ( <svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 100 100"> {props.title && <title>{props.title}</title>} <path d="M52.2,18.9l0.7,0.5l8,5.7l0.8,0.5l-0.4,0.8l-5.7,10.2c-0.3,0.7-0.8,1.2-1.4,1.5c-0.8,0.5-1.8,0.9-3,1.1 c-0.6,0.1-1.1,0.2-1.6,0.2c-2.9,5.4-2.9,15.6,0.1,21c0.5,0,1.1,0.1,1.5,0.2c1.2,0.2,2.2,0.6,3.1,1.2c0.6,0.4,1.1,0.9,1.4,1.5 l5.7,10.3l0.4,0.8L61,74.9l-8,5.7l-0.7,0.5l-0.6-0.5c-17.6-15.3-17.6-45.8,0-61.1L52.2,18.9 M52,15.8L50.6,17L50,17.5 c-8.9,7.8-14,19.6-14,32.4c0,12.9,5.1,24.7,14.2,32.6l0.6,0.5l1.4,1.3l1.5-1.1l0.7-0.5l8-5.7l0.8-0.5l1.7-1.3l-1.1-1.9l-0.4-0.8 l-5.7-10.2c-0.5-0.9-1.2-1.6-2.1-2.3c-1.2-0.8-2.4-1.3-4.1-1.5c-0.2-0.1-0.3-0.1-0.4-0.1c-1.9-4.5-1.9-12-0.1-16.5 c0.1-0.1,0.3-0.1,0.4-0.1c1.5-0.3,2.8-0.8,3.9-1.5c1-0.7,1.7-1.4,2.2-2.4l5.7-10.2l0.4-0.8l1.1-1.9L63,23.7L62.3,23l-8-5.7l-0.7-0.5 L52,15.8L52,15.8z"/> </svg> ); export default PhoneIcon;
www/src/pages/plugins.js
TaitoUnited/taito-cli
import React from 'react'; import { graphql } from 'gatsby'; import { flattenListData } from '../utils'; import Page from '../components/Page'; import SEO from '../components/SEO'; import GitHubEditLink from '../components/GitHubEditLink'; import Spacing from '../components/Spacing'; export default ({ data }) => { const [pageData] = flattenListData(data, 'md'); return ( <Page> <SEO /> <div dangerouslySetInnerHTML={{ __html: pageData.html }} /> <Spacing dir="y" amount={20} /> <GitHubEditLink /> </Page> ); }; export const query = graphql` query { md: allMarkdownRemark(filter: { fields: { slug: { eq: "/plugins/" } } }) { edges { node { id html } } } } `;
ajax/libs/vega/3.0.0-beta.6/vega.js
maruilian11/cdnjs
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.vega = global.vega || {}))); }(this, (function (exports) { 'use strict'; var version = "3.0.0-beta.6"; function bin$1(_) { // determine range var maxb = _.maxbins || 20, base = _.base || 10, logb = Math.log(base), div = _.divide || [5, 2], min = _.extent[0], max = _.extent[1], span = max - min, step, level, minstep, precision, v, i, n, eps; if (_.step) { // if step size is explicitly given, use that step = _.step; } else if (_.steps) { // if provided, limit choice to acceptable step sizes v = span / maxb; for (i=0, n=_.steps.length; i < n && _.steps[i] < v; ++i); step = _.steps[Math.max(0, i-1)]; } else { // else use span to determine step size level = Math.ceil(Math.log(maxb) / logb); minstep = _.minstep || 0; step = Math.max( minstep, Math.pow(base, Math.round(Math.log(span) / logb) - level) ); // increase step size if too many bins while (Math.ceil(span/step) > maxb) { step *= base; } // decrease step size if allowed for (i=0, n=div.length; i<n; ++i) { v = step / div[i]; if (v >= minstep && span / v <= maxb) step = v; } } // update precision, min and max v = Math.log(step); precision = v >= 0 ? 0 : ~~(-v / logb) + 1; eps = Math.pow(base, -precision - 1); if (_.nice || _.nice === undefined) { min = Math.min(min, Math.floor(min / step + eps) * step); max = Math.ceil(max / step) * step; } return { start: min, stop: max, step: step }; } function numbers(array, f) { var numbers = [], n = array.length, i = -1, a; if (f == null) { while (++i < n) if (!isNaN(a = number(array[i]))) numbers.push(a); } else { while (++i < n) if (!isNaN(a = number(f(array[i], i, array)))) numbers.push(a); } return numbers; } function number(x) { return x === null ? NaN : +x; } function ascending(a, b) { return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; } function bisector(compare) { if (compare.length === 1) compare = ascendingComparator(compare); return { left: function(a, x, lo, hi) { if (lo == null) lo = 0; if (hi == null) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid; } return lo; }, right: function(a, x, lo, hi) { if (lo == null) lo = 0; if (hi == null) hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1; } return lo; } }; } function ascendingComparator(f) { return function(d, x) { return ascending(f(d), x); }; } var ascendingBisect = bisector(ascending); var bisectRight = ascendingBisect.right; var bisectLeft = ascendingBisect.left; function number$1(x) { return x === null ? NaN : +x; } function variance(array, f) { var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0; if (f == null) { while (++i < n) { if (!isNaN(a = number$1(array[i]))) { d = a - m; m += d / ++j; s += d * (a - m); } } } else { while (++i < n) { if (!isNaN(a = number$1(f(array[i], i, array)))) { d = a - m; m += d / ++j; s += d * (a - m); } } } if (j > 1) return s / (j - 1); } function extent(array, f) { var i = -1, n = array.length, a, b, c; if (f == null) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = c = b; break; } while (++i < n) if ((b = array[i]) != null) { if (a > b) a = b; if (c < b) c = b; } } else { while (++i < n) if ((b = f(array[i], i, array)) != null && b >= b) { a = c = b; break; } while (++i < n) if ((b = f(array[i], i, array)) != null) { if (a > b) a = b; if (c < b) c = b; } } return [a, c]; } function range(start, stop, step) { start = +start, stop = +stop, step = (n = arguments.length) < 2 ? (stop = start, start = 0, 1) : n < 3 ? 1 : +step; var i = -1, n = Math.max(0, Math.ceil((stop - start) / step)) | 0, range = new Array(n); while (++i < n) { range[i] = start + i * step; } return range; } var e10 = Math.sqrt(50); var e5 = Math.sqrt(10); var e2 = Math.sqrt(2); function ticks(start, stop, count) { var step = tickStep(start, stop, count); return range( Math.ceil(start / step) * step, Math.floor(stop / step) * step + step / 2, // inclusive step ); } function tickStep(start, stop, count) { var step0 = Math.abs(stop - start) / Math.max(0, count), step1 = Math.pow(10, Math.floor(Math.log(step0) / Math.LN10)), error = step0 / step1; if (error >= e10) step1 *= 10; else if (error >= e5) step1 *= 5; else if (error >= e2) step1 *= 2; return stop < start ? -step1 : step1; } function threshold(array, p, f) { if (f == null) f = number$1; if (!(n = array.length)) return; if ((p = +p) <= 0 || n < 2) return +f(array[0], 0, array); if (p >= 1) return +f(array[n - 1], n - 1, array); var n, h = (n - 1) * p, i = Math.floor(h), a = +f(array[i], i, array), b = +f(array[i + 1], i + 1, array); return a + (b - a) * (h - i); } function max(array, f) { var i = -1, n = array.length, a, b; if (f == null) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = b; break; } while (++i < n) if ((b = array[i]) != null && b > a) a = b; } else { while (++i < n) if ((b = f(array[i], i, array)) != null && b >= b) { a = b; break; } while (++i < n) if ((b = f(array[i], i, array)) != null && b > a) a = b; } return a; } function mean(array, f) { var s = 0, n = array.length, a, i = -1, j = n; if (f == null) { while (++i < n) if (!isNaN(a = number$1(array[i]))) s += a; else --j; } else { while (++i < n) if (!isNaN(a = number$1(f(array[i], i, array)))) s += a; else --j; } if (j) return s / j; } function median(array, f) { var numbers = [], n = array.length, a, i = -1; if (f == null) { while (++i < n) if (!isNaN(a = number$1(array[i]))) numbers.push(a); } else { while (++i < n) if (!isNaN(a = number$1(f(array[i], i, array)))) numbers.push(a); } return threshold(numbers.sort(ascending), 0.5); } function merge(arrays) { var n = arrays.length, m, i = -1, j = 0, merged, array; while (++i < n) j += arrays[i].length; merged = new Array(j); while (--n >= 0) { array = arrays[n]; m = array.length; while (--m >= 0) { merged[--j] = array[m]; } } return merged; } function min(array, f) { var i = -1, n = array.length, a, b; if (f == null) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = b; break; } while (++i < n) if ((b = array[i]) != null && a > b) a = b; } else { while (++i < n) if ((b = f(array[i], i, array)) != null && b >= b) { a = b; break; } while (++i < n) if ((b = f(array[i], i, array)) != null && a > b) a = b; } return a; } function permute(array, indexes) { var i = indexes.length, permutes = new Array(i); while (i--) permutes[i] = array[indexes[i]]; return permutes; } function sum(array, f) { var s = 0, n = array.length, a, i = -1; if (f == null) { while (++i < n) if (a = +array[i]) s += a; // Note: zero and null are equivalent. } else { while (++i < n) if (a = +f(array[i], i, array)) s += a; } return s; } function bootstrapCI(array, samples, alpha, f) { var values = numbers(array, f), n = values.length, m = samples, a, i, j, mu; for (j=0, mu=Array(m); j<m; ++j) { for (a=0, i=0; i<n; ++i) { a += values[~~(Math.random() * n)]; } mu[i] = a / n; } return [ threshold(mu.sort(ascending), alpha/2), threshold(mu, 1-(alpha/2)) ]; } function integer(min, max) { if (max == null) { max = min; min = 0; } var dist = {}, a, b, d; dist.min = function(_) { return arguments.length ? (a = _ || 0, d = b - a, dist) : a; }; dist.max = function(_) { return arguments.length ? (b = _ || 0, d = b - a, dist) : b; }; dist.sample = function() { return a + Math.floor(d * Math.random()); }; dist.pdf = function(x) { return (x === Math.floor(x) && x >= a && x < b) ? 1 / d : 0; }; dist.cdf = function(x) { var v = Math.floor(x); return v < a ? 0 : v >= b ? 1 : (v - a + 1) / d; }; dist.icdf = function(p) { return (p >= 0 && p <= 1) ? a - 1 + Math.floor(p * d) : NaN; }; return dist.min(min).max(max); } function randomNormal(mean, stdev) { var mu, sigma, next = NaN, dist = {}; dist.mean = function(_) { return arguments.length ? (mu = _ || 0, next = NaN, dist) : mu; }; dist.stdev = function(_) { return arguments.length ? (sigma = (_==null ? 1 : _), next = NaN, dist) : sigma; }; dist.sample = function() { var x = 0, y = 0, rds, c; if (next === next) { return x = next, next = NaN, x; } do { x = Math.random() * 2 - 1; y = Math.random() * 2 - 1; rds = x * x + y * y; } while (rds === 0 || rds > 1); c = Math.sqrt(-2 * Math.log(rds) / rds); // Box-Muller transform next = mu + y * c * sigma; return mu + x * c * sigma; }; dist.pdf = function(x) { var exp = Math.exp(Math.pow(x-mu, 2) / (-2 * Math.pow(sigma, 2))); return (1 / (sigma * Math.sqrt(2*Math.PI))) * exp; }; // Approximation from West (2009) // Better Approximations to Cumulative Normal Functions dist.cdf = function(x) { var cd, z = (x - mu) / sigma, Z = Math.abs(z); if (Z > 37) { cd = 0; } else { var sum, exp = Math.exp(-Z*Z/2); if (Z < 7.07106781186547) { sum = 3.52624965998911e-02 * Z + 0.700383064443688; sum = sum * Z + 6.37396220353165; sum = sum * Z + 33.912866078383; sum = sum * Z + 112.079291497871; sum = sum * Z + 221.213596169931; sum = sum * Z + 220.206867912376; cd = exp * sum; sum = 8.83883476483184e-02 * Z + 1.75566716318264; sum = sum * Z + 16.064177579207; sum = sum * Z + 86.7807322029461; sum = sum * Z + 296.564248779674; sum = sum * Z + 637.333633378831; sum = sum * Z + 793.826512519948; sum = sum * Z + 440.413735824752; cd = cd / sum; } else { sum = Z + 0.65; sum = Z + 4 / sum; sum = Z + 3 / sum; sum = Z + 2 / sum; sum = Z + 1 / sum; cd = exp / sum / 2.506628274631; } } return z > 0 ? 1 - cd : cd; }; // Approximation of Probit function using inverse error function. dist.icdf = function(p) { if (p <= 0 || p >= 1) return NaN; var x = 2*p - 1, v = (8 * (Math.PI - 3)) / (3 * Math.PI * (4-Math.PI)), a = (2 / (Math.PI*v)) + (Math.log(1 - Math.pow(x,2)) / 2), b = Math.log(1 - (x*x)) / v, s = (x > 0 ? 1 : -1) * Math.sqrt(Math.sqrt((a*a) - b) - a); return mu + sigma * Math.SQRT2 * s; }; return dist.mean(mean).stdev(stdev); } function quartiles(array, f) { var values = numbers(array, f); return [ threshold(values.sort(ascending), 0.25), threshold(values, 0.50), threshold(values, 0.75) ]; } // TODO: support for additional kernels? function randomKDE(support, bandwidth) { var kernel = randomNormal(), dist = {}, n = 0; dist.data = function(_) { return arguments.length ? (support = _, (n = _?_.length:0), dist.bandwidth(bandwidth)) : support; }; dist.bandwidth = function(_) { if (!arguments.length) return bandwidth; bandwidth = _; if (!bandwidth && support) bandwidth = estimateBandwidth(support); return dist; }; dist.sample = function() { return support[~~(Math.random() * n)] + bandwidth * kernel.sample(); }; dist.pdf = function(x) { for (var y=0, i=0; i<n; ++i) { y += kernel.pdf((x - support[i]) / bandwidth); } return y / bandwidth / n; }; dist.cdf = function(x) { for (var y=0, i=0; i<n; ++i) { y += kernel.cdf((x - support[i]) / bandwidth); } return y / n; }; dist.icdf = function() { throw Error('KDE icdf not supported.'); }; return dist.data(support); } // Scott, D. W. (1992) Multivariate Density Estimation: // Theory, Practice, and Visualization. Wiley. function estimateBandwidth(array) { var n = array.length, q = quartiles(array), h = (q[2] - q[0]) / 1.34; return 1.06 * Math.min(Math.sqrt(variance(array)), h) * Math.pow(n, -0.2); } function randomMixture(dists, weights) { var dist = {}, m = 0, w; function normalize(x) { var w = [], sum = 0, i; for (i=0; i<m; ++i) { sum += (w[i] = (x[i]==null ? 1 : +x[i])); } for (i=0; i<m; ++i) { w[i] /= sum; } return w; } dist.weights = function(_) { if (arguments.length) { w = normalize(weights = (_ || [])); return dist; } return weights; }; dist.distributions = function(_) { if (arguments.length) { if (_) { m = _.length; dists = _; } else { m = 0; dists = []; } return dist.weights(weights); } return dists; }; dist.sample = function() { var r = Math.random(), d = dists[m-1], v = w[0], i = 0; // first select distribution for (; i<m-1; v += w[++i]) { if (r < v) { d = dists[i]; break; } } // then sample from it return d.sample(); }; dist.pdf = function(x) { for (var p=0, i=0; i<m; ++i) { p += w[i] * dists[i].pdf(x); } return p; }; dist.cdf = function(x) { for (var p=0, i=0; i<m; ++i) { p += w[i] * dists[i].cdf(x); } return p; }; dist.icdf = function() { throw Error('Mixture icdf not supported.'); }; return dist.distributions(dists).weights(weights); } function randomUniform(min, max) { if (max == null) { max = (min == null ? 1 : min); min = 0; } var dist = {}, a, b, d; dist.min = function(_) { return arguments.length ? (a = _ || 0, d = b - a, dist) : a; }; dist.max = function(_) { return arguments.length ? (b = _ || 0, d = b - a, dist) : b; }; dist.sample = function() { return a + d * Math.random(); }; dist.pdf = function(x) { return (x >= a && x <= b) ? 1 / d : 0; }; dist.cdf = function(x) { return x < a ? 0 : x > b ? 1 : (x - a) / d; }; dist.icdf = function(p) { return (p >= 0 && p <= 1) ? a + p * d : NaN; }; return dist.min(min).max(max); } function accessor(fn, fields, name) { return ( fn.fields = fields || [], fn.fname = name, fn ); } function accessorName(fn) { return fn == null ? null : fn.fname; } function accessorFields(fn) { return fn == null ? null : fn.fields; } function splitAccessPath(p) { return String(p) .match(/\[(.*?)\]|[^.\[]+/g) .map(path_trim); } function path_trim(d) { return d[0] !== '[' ? d : d[1] !== "'" && d[1] !== '"' ? d.slice(1, -1) : d.slice(2, -2).replace(/\\(["'])/g, '$1'); } var isArray = Array.isArray; function isObject(_) { return _ === Object(_); } function isString(_) { return typeof _ === 'string'; } function $(x) { return isArray(x) ? '[' + x.map($) + ']' : isObject(x) || isString(x) ? // Output valid JSON and JS source strings. // See http://timelessrepo.com/json-isnt-a-javascript-subset JSON.stringify(x).replace('\u2028','\\u2028').replace('\u2029', '\\u2029') : x; } function field(field, name) { var path = splitAccessPath(field).map($), fn = Function('_', 'return _[' + path.join('][') + '];'); return accessor(fn, [field], name || field); } var empty = []; var id = field('id'); var identity$1 = accessor(function(_) { return _; }, empty, 'identity'); var zero = accessor(function() { return 0; }, empty, 'zero'); var one = accessor(function() { return 1; }, empty, 'one'); var truthy = accessor(function() { return true; }, empty, 'true'); var falsy = accessor(function() { return false; }, empty, 'false'); function log(method, level, input) { var args = [level].concat([].slice.call(input)); console[method].apply(console, args); // eslint-disable-line no-console } var None = 0; var Warn = 1; var Info = 2; var Debug = 3; function logger(_) { var level = _ || None; return { level: function(_) { return arguments.length ? (level = +_, this) : level; }, warn: function() { if (level >= Warn) log('warn', 'WARN', arguments); return this; }, info: function() { if (level >= Info) log('log', 'INFO', arguments); return this; }, debug: function() { if (level >= Debug) log('log', 'DEBUG', arguments); return this; } } } function array$1(_) { return _ != null ? (isArray(_) ? _ : [_]) : []; } function compare(fields, orders) { if (fields == null) return null; fields = array$1(fields); var cmp = fields.map(function(f) { return splitAccessPath(f).map($).join(']['); }), ord = array$1(orders), n = cmp.length - 1, code = 'var u,v;return ', i, f, u, v, d, lt, gt; for (i=0; i<=n; ++i) { f = cmp[i]; u = '(u=a['+f+'])'; v = '(v=b['+f+'])'; d = '((v=v instanceof Date?+v:v),(u=u instanceof Date?+u:u))'; lt = ord[i] !== 'descending' ? (gt=1, -1) : (gt=-1, 1); code += '(' + u+'<'+v+'||u==null)&&v!=null?' + lt + ':(u>v||v==null)&&u!=null?' + gt + ':'+d+'!==u&&v===v?' + lt + ':v!==v&&u===u?' + gt + (i < n ? ':' : ':0'); } return accessor(Function('a', 'b', code + ';'), fields); } function isFunction(_) { return typeof _ === 'function'; } function constant$1(_) { return isFunction(_) ? _ : function() { return _; }; } function error(message) { throw Error(message); } function extend(_) { for (var x, k, i=1, len=arguments.length; i<len; ++i) { x = arguments[i]; for (k in x) { _[k] = x[k]; } } return _; } function extentIndex(array, f) { var i = -1, n = array.length, a, b, c, u, v; if (f == null) { while (++i < n) if ((b = array[i]) != null && b >= b) { a = c = b; break; } u = v = i; while (++i < n) if ((b = array[i]) != null) { if (a > b) a = b, u = i; if (c < b) c = b, v = i; } } else { while (++i < n) if ((b = f(array[i], i, array)) != null && b >= b) { a = c = b; break; } u = v = i; while (++i < n) if ((b = f(array[i], i, array)) != null) { if (a > b) a = b, u = i; if (c < b) c = b, v = i; } } return [u, v]; } function inherits(child, parent) { var proto = (child.prototype = Object.create(parent.prototype)); proto.constructor = child; return proto; } function isNumber(_) { return typeof _ === 'number'; } function key(fields) { fields = fields ? array$1(fields) : fields; var fn = !(fields && fields.length) ? function() { return ''; } : Function('_', 'return \'\'+' + fields.map(function(f) { return '_[' + splitAccessPath(f).map($).join('][') + ']'; }).join('+\'|\'+') + ';'); return accessor(fn, fields, 'key'); } function merge$1(compare, array0, array1, output) { var n0 = array0.length, n1 = array1.length; if (!n1) return array0; if (!n0) return array1; var merged = output || new array0.constructor(n0 + n1), i0 = 0, i1 = 0, i = 0; for (; i0<n0 && i1<n1; ++i) { merged[i] = compare(array0[i0], array1[i1]) > 0 ? array1[i1++] : array0[i0++]; } for (; i0<n0; ++i0, ++i) { merged[i] = array0[i0]; } for (; i1<n1; ++i1, ++i) { merged[i] = array1[i1]; } return merged; } function repeat(str, reps) { var s = ''; while (--reps >= 0) s += str; return s; } function pad(str, length, padchar, align) { var c = padchar || ' ', n = length - str.length; return n <= 0 ? str : align === 'left' ? repeat(c, n) + str : align === 'center' ? repeat(c, ~~(n/2)) + str + repeat(c, Math.ceil(n/2)) : str + repeat(c, n); } function peek(array) { return array[array.length - 1]; } function toSet(_) { for (var s={}, i=0, n=_.length; i<n; ++i) s[_[i]] = 1; return s; } function truncate(str, length, align, ellipsis) { var e = ellipsis != null ? ellipsis : '\u2026', n = str.length, l = Math.max(0, length - e.length); return n <= length ? str : align === 'left' ? e + str.slice(n - l) : align === 'center' ? str.slice(0, Math.ceil(l/2)) + e + str.slice(n - ~~(l/2)) : str.slice(0, l) + e; } function visitArray(array, filter, visitor) { if (array) { var i = 0, n = array.length, t; if (filter) { for (; i<n; ++i) { if (t = filter(array[i])) visitor(t, i, array); } } else { array.forEach(visitor); } } } var prefix = "$"; function Map() {} Map.prototype = map$1.prototype = { constructor: Map, has: function(key) { return (prefix + key) in this; }, get: function(key) { return this[prefix + key]; }, set: function(key, value) { this[prefix + key] = value; return this; }, remove: function(key) { var property = prefix + key; return property in this && delete this[property]; }, clear: function() { for (var property in this) if (property[0] === prefix) delete this[property]; }, keys: function() { var keys = []; for (var property in this) if (property[0] === prefix) keys.push(property.slice(1)); return keys; }, values: function() { var values = []; for (var property in this) if (property[0] === prefix) values.push(this[property]); return values; }, entries: function() { var entries = []; for (var property in this) if (property[0] === prefix) entries.push({key: property.slice(1), value: this[property]}); return entries; }, size: function() { var size = 0; for (var property in this) if (property[0] === prefix) ++size; return size; }, empty: function() { for (var property in this) if (property[0] === prefix) return false; return true; }, each: function(f) { for (var property in this) if (property[0] === prefix) f(this[property], property.slice(1), this); } }; function map$1(object, f) { var map = new Map; // Copy constructor. if (object instanceof Map) object.each(function(value, key) { map.set(key, value); }); // Index array by numeric index or specified key function. else if (Array.isArray(object)) { var i = -1, n = object.length, o; if (f == null) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f(o = object[i], i, object), o); } // Convert object to map. else if (object) for (var key in object) map.set(key, object[key]); return map; } function nest() { var keys = [], sortKeys = [], sortValues, rollup, nest; function apply(array, depth, createResult, setResult) { if (depth >= keys.length) return rollup != null ? rollup(array) : (sortValues != null ? array.sort(sortValues) : array); var i = -1, n = array.length, key = keys[depth++], keyValue, value, valuesByKey = map$1(), values, result = createResult(); while (++i < n) { if (values = valuesByKey.get(keyValue = key(value = array[i]) + "")) { values.push(value); } else { valuesByKey.set(keyValue, [value]); } } valuesByKey.each(function(values, key) { setResult(result, key, apply(values, depth, createResult, setResult)); }); return result; } function entries(map, depth) { if (++depth > keys.length) return map; var array, sortKey = sortKeys[depth - 1]; if (rollup != null && depth >= keys.length) array = map.entries(); else array = [], map.each(function(v, k) { array.push({key: k, values: entries(v, depth)}); }); return sortKey != null ? array.sort(function(a, b) { return sortKey(a.key, b.key); }) : array; } return nest = { object: function(array) { return apply(array, 0, createObject, setObject); }, map: function(array) { return apply(array, 0, createMap, setMap); }, entries: function(array) { return entries(apply(array, 0, createMap, setMap), 0); }, key: function(d) { keys.push(d); return nest; }, sortKeys: function(order) { sortKeys[keys.length - 1] = order; return nest; }, sortValues: function(order) { sortValues = order; return nest; }, rollup: function(f) { rollup = f; return nest; } }; } function createObject() { return {}; } function setObject(object, key, value) { object[key] = value; } function createMap() { return map$1(); } function setMap(map, key, value) { map.set(key, value); } var proto = map$1.prototype; var noop = {value: function() {}}; function dispatch() { for (var i = 0, n = arguments.length, _ = {}, t; i < n; ++i) { if (!(t = arguments[i] + "") || (t in _)) throw new Error("illegal type: " + t); _[t] = []; } return new Dispatch(_); } function Dispatch(_) { this._ = _; } function parseTypenames(typenames, types) { return typenames.trim().split(/^|\s+/).map(function(t) { var name = "", i = t.indexOf("."); if (i >= 0) name = t.slice(i + 1), t = t.slice(0, i); if (t && !types.hasOwnProperty(t)) throw new Error("unknown type: " + t); return {type: t, name: name}; }); } Dispatch.prototype = dispatch.prototype = { constructor: Dispatch, on: function(typename, callback) { var _ = this._, T = parseTypenames(typename + "", _), t, i = -1, n = T.length; // If no callback was specified, return the callback of the given type and name. if (arguments.length < 2) { while (++i < n) if ((t = (typename = T[i]).type) && (t = get(_[t], typename.name))) return t; return; } // If a type was specified, set the callback for the given type and name. // Otherwise, if a null callback was specified, remove callbacks of the given name. if (callback != null && typeof callback !== "function") throw new Error("invalid callback: " + callback); while (++i < n) { if (t = (typename = T[i]).type) _[t] = set$1(_[t], typename.name, callback); else if (callback == null) for (t in _) _[t] = set$1(_[t], typename.name, null); } return this; }, copy: function() { var copy = {}, _ = this._; for (var t in _) copy[t] = _[t].slice(); return new Dispatch(copy); }, call: function(type, that) { if ((n = arguments.length - 2) > 0) for (var args = new Array(n), i = 0, n, t; i < n; ++i) args[i] = arguments[i + 2]; if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type); for (t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args); }, apply: function(type, that, args) { if (!this._.hasOwnProperty(type)) throw new Error("unknown type: " + type); for (var t = this._[type], i = 0, n = t.length; i < n; ++i) t[i].value.apply(that, args); } }; function get(type, name) { for (var i = 0, n = type.length, c; i < n; ++i) { if ((c = type[i]).name === name) { return c.value; } } } function set$1(type, name, callback) { for (var i = 0, n = type.length; i < n; ++i) { if (type[i].name === name) { type[i] = noop, type = type.slice(0, i).concat(type.slice(i + 1)); break; } } if (callback != null) type.push({name: name, value: callback}); return type; } function request(url, callback) { var request, event = dispatch("beforesend", "progress", "load", "error"), mimeType, headers = map$1(), xhr = new XMLHttpRequest, user = null, password = null, response, responseType, timeout = 0; // If IE does not support CORS, use XDomainRequest. if (typeof XDomainRequest !== "undefined" && !("withCredentials" in xhr) && /^(http(s)?:)?\/\//.test(url)) xhr = new XDomainRequest; "onload" in xhr ? xhr.onload = xhr.onerror = xhr.ontimeout = respond : xhr.onreadystatechange = function(o) { xhr.readyState > 3 && respond(o); }; function respond(o) { var status = xhr.status, result; if (!status && hasResponse(xhr) || status >= 200 && status < 300 || status === 304) { if (response) { try { result = response.call(request, xhr); } catch (e) { event.call("error", request, e); return; } } else { result = xhr; } event.call("load", request, result); } else { event.call("error", request, o); } } xhr.onprogress = function(e) { event.call("progress", request, e); }; request = { header: function(name, value) { name = (name + "").toLowerCase(); if (arguments.length < 2) return headers.get(name); if (value == null) headers.remove(name); else headers.set(name, value + ""); return request; }, // If mimeType is non-null and no Accept header is set, a default is used. mimeType: function(value) { if (!arguments.length) return mimeType; mimeType = value == null ? null : value + ""; return request; }, // Specifies what type the response value should take; // for instance, arraybuffer, blob, document, or text. responseType: function(value) { if (!arguments.length) return responseType; responseType = value; return request; }, timeout: function(value) { if (!arguments.length) return timeout; timeout = +value; return request; }, user: function(value) { return arguments.length < 1 ? user : (user = value == null ? null : value + "", request); }, password: function(value) { return arguments.length < 1 ? password : (password = value == null ? null : value + "", request); }, // Specify how to convert the response content to a specific type; // changes the callback value on "load" events. response: function(value) { response = value; return request; }, // Alias for send("GET", …). get: function(data, callback) { return request.send("GET", data, callback); }, // Alias for send("POST", …). post: function(data, callback) { return request.send("POST", data, callback); }, // If callback is non-null, it will be used for error and load events. send: function(method, data, callback) { xhr.open(method, url, true, user, password); if (mimeType != null && !headers.has("accept")) headers.set("accept", mimeType + ",*/*"); if (xhr.setRequestHeader) headers.each(function(value, name) { xhr.setRequestHeader(name, value); }); if (mimeType != null && xhr.overrideMimeType) xhr.overrideMimeType(mimeType); if (responseType != null) xhr.responseType = responseType; if (timeout > 0) xhr.timeout = timeout; if (callback == null && typeof data === "function") callback = data, data = null; if (callback != null && callback.length === 1) callback = fixCallback(callback); if (callback != null) request.on("error", callback).on("load", function(xhr) { callback(null, xhr); }); event.call("beforesend", request, xhr); xhr.send(data == null ? null : data); return request; }, abort: function() { xhr.abort(); return request; }, on: function() { var value = event.on.apply(event, arguments); return value === event ? request : value; } }; if (callback != null) { if (typeof callback !== "function") throw new Error("invalid callback: " + callback); return request.get(callback); } return request; } function fixCallback(callback) { return function(error, xhr) { callback(error == null ? xhr : null); }; } function hasResponse(xhr) { var type = xhr.responseType; return type && type !== "text" ? xhr.response // null on error : xhr.responseText; // "" on error } function objectConverter(columns) { return new Function("d", "return {" + columns.map(function(name, i) { return JSON.stringify(name) + ": d[" + i + "]"; }).join(",") + "}"); } function customConverter(columns, f) { var object = objectConverter(columns); return function(row, i) { return f(object(row), i, columns); }; } // Compute unique columns in order of discovery. function inferColumns(rows) { var columnSet = Object.create(null), columns = []; rows.forEach(function(row) { for (var column in row) { if (!(column in columnSet)) { columns.push(columnSet[column] = column); } } }); return columns; } function dsvFormat(delimiter) { var reFormat = new RegExp("[\"" + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); function parse(text, f) { var convert, columns, rows = parseRows(text, function(row, i) { if (convert) return convert(row, i - 1); columns = row, convert = f ? customConverter(row, f) : objectConverter(row); }); rows.columns = columns; return rows; } function parseRows(text, f) { var EOL = {}, // sentinel value for end-of-line EOF = {}, // sentinel value for end-of-file rows = [], // output rows N = text.length, I = 0, // current character index n = 0, // the current line number t, // the current token eol; // is the current token followed by EOL? function token() { if (I >= N) return EOF; // special case: end of file if (eol) return eol = false, EOL; // special case: end of line // special case: quotes var j = I, c; if (text.charCodeAt(j) === 34) { var i = j; while (i++ < N) { if (text.charCodeAt(i) === 34) { if (text.charCodeAt(i + 1) !== 34) break; ++i; } } I = i + 2; c = text.charCodeAt(i + 1); if (c === 13) { eol = true; if (text.charCodeAt(i + 2) === 10) ++I; } else if (c === 10) { eol = true; } return text.slice(j + 1, i).replace(/""/g, "\""); } // common case: find next delimiter or newline while (I < N) { var k = 1; c = text.charCodeAt(I++); if (c === 10) eol = true; // \n else if (c === 13) { eol = true; if (text.charCodeAt(I) === 10) ++I, ++k; } // \r|\r\n else if (c !== delimiterCode) continue; return text.slice(j, I - k); } // special case: last token before EOF return text.slice(j); } while ((t = token()) !== EOF) { var a = []; while (t !== EOL && t !== EOF) { a.push(t); t = token(); } if (f && (a = f(a, n++)) == null) continue; rows.push(a); } return rows; } function format(rows, columns) { if (columns == null) columns = inferColumns(rows); return [columns.map(formatValue).join(delimiter)].concat(rows.map(function(row) { return columns.map(function(column) { return formatValue(row[column]); }).join(delimiter); })).join("\n"); } function formatRows(rows) { return rows.map(formatRow).join("\n"); } function formatRow(row) { return row.map(formatValue).join(delimiter); } function formatValue(text) { return text == null ? "" : reFormat.test(text += "") ? "\"" + text.replace(/\"/g, "\"\"") + "\"" : text; } return { parse: parse, parseRows: parseRows, format: format, formatRows: formatRows }; } var csv$1 = dsvFormat(","); var tsv = dsvFormat("\t"); // Matches absolute URLs with optional protocol // https://... file://... //... var protocol_re = /^([A-Za-z]+:)?\/\//; // Special treatment in node.js for the file: protocol var fileProtocol = 'file://'; // Request options to check for d3-request var requestOptions = [ 'mimeType', 'responseType', 'user', 'password' ]; /** * Creates a new loader instance that provides methods for requesting files * from either the network or disk, and for sanitizing request URIs. * @param {object} [options] - Optional default loading options to use. * @return {object} - A new loader instance. */ function loader(options) { return { options: options || {}, sanitize: sanitize, load: load, file: file, http: http }; } function marshall(loader, options) { return extend({}, loader.options, options); } /** * Load an external resource, typically either from the web or from the local * filesystem. This function uses {@link sanitize} to first sanitize the uri, * then calls either {@link http} (for web requests) or {@link file} (for * filesystem loading). * @param {string} uri - The resource indicator (e.g., URL or filename). * @param {object} [options] - Optional loading options. These options will * override any existing default options. * @return {Promise} - A promise that resolves to the loaded content. */ function load(uri, options) { var loader = this; return loader.sanitize(uri, options) .then(function(url) { return (startsWith(url, fileProtocol)) ? loader.file(url.slice(fileProtocol.length)) : loader.http(url, options); }); } /** * URI sanitizer function. * @param {string} uri - The uri (url or filename) to sanity check. * @param {object} options - An options hash. * @return {Promise} - A promise that resolves to the final URL to * load, or rejects if the input uri is invalid. */ function sanitize(uri, options) { options = marshall(this, options); return new Promise(function(accept, reject) { var isFile, hasProtocol, loadFile, base; if (uri == null || typeof uri !== 'string') { reject('Sanitize failure, invalid URI: ' + $(uri)); return; } // if relative url (no protocol/host), prepend baseURL if ((base = options.baseURL) && !hasProtocol) { // Ensure that there is a slash between the baseURL (e.g. hostname) and url if (!startsWith(uri, '/') && base[base.length-1] !== '/') { uri = '/' + uri; } uri = base + uri; } isFile = startsWith(uri, fileProtocol); hasProtocol = protocol_re.test(uri); // should we load from file system? loadFile = isFile || options.mode === 'file' || options.mode !== 'http' && !hasProtocol && fs(); if (loadFile) { // prepend file protocol, if not already present uri = (isFile ? '' : fileProtocol) + uri; } else if (startsWith(uri, '//')) { // if relative protocol (starts with '//'), prepend default protocol uri = (options.defaultProtocol || 'http') + ':' + uri; } accept(uri); }); } /** * HTTP request loader. * @param {string} url - The url to request. * @param {object} options - An options hash. * @return {Promise} - A promise that resolves to the file contents. */ function http(url, options) { options = marshall(this, options); return new Promise(function(accept, reject) { var req = request(url), name; for (name in options.headers) { req.header(name, options.headers[name]); } requestOptions.forEach(function(name) { if (options[name]) req[name](options[name]); }); req.on('error', function(error) { reject(error || 'Error loading URL: ' + url); }) .on('load', function(result) { var text = result && result.responseText; (!result || result.status === 0) ? reject(text || 'Error') : accept(text); }) .get(); }); } /** * File system loader. * @param {string} filename - The file system path to load. * @return {Promise} - A promise that resolves to the file contents. */ function file(filename) { return new Promise(function(accept, reject) { var f = fs(); f ? f.readFile(filename, function(error, data) { if (error) reject(error); else accept(data); }) : reject('No file system access for ' + filename); }); } function fs() { return typeof require === 'function' && require('fs'); } function startsWith(string, query) { return string == null ? false : string.lastIndexOf(query, 0) === 0; } var typeParsers = { boolean: toBoolean, integer: toNumber, number: toNumber, date: toDate, string: toString }; var typeTests = [ isBoolean, isInteger, isNumber$1, isDate ]; var typeList = [ 'boolean', 'integer', 'number', 'date' ]; function inferType(values, field) { var tests = typeTests.slice(), value, i, n, j; for (i=0, n=values.length; i<n; ++i) { value = field ? values[i][field] : values[i]; for (j=0; j<tests.length; ++j) { if (isValid(value) && !tests[j](value)) { tests.splice(j, 1); --j; } } if (tests.length === 0) return 'string'; } return typeList[typeTests.indexOf(tests[0])]; } function inferTypes(data, fields) { return fields.reduce(function(types, field) { return types[field] = inferType(data, field), types; }, {}); } // -- Type Coercion ---- function toNumber(_) { return _ == null || _ === '' ? null : +_; } function toBoolean(_) { return _ == null || _ === '' ? null : !_ || _ === 'false' ? false : !!_; } function toDate(_, parser) { return _ == null || _ === '' ? null : (parser ? parser(_) : Date.parse(_)); } function toString(_) { return _ == null || _ === '' ? null : _ + ''; } // -- Type Checks ---- function isValid(_) { return _ != null && _ === _; } function isBoolean(_) { return _ === 'true' || _ === 'false' || _ === true || _ === false; } function isDate(_) { return !isNaN(Date.parse(_)); } function isNumber$1(_) { return !isNaN(+_) && !(_ instanceof Date); } function isInteger(_) { return isNumber$1(_) && (_=+_) === ~~_; } function delimitedFormat(delimiter) { return function(data, format) { var delim = {delimiter: delimiter}; return dsv$1(data, format ? extend(format, delim) : delim); }; } function dsv$1(data, format) { if (format.header) { data = format.header .map($) .join(format.delimiter) + '\n' + data; } return dsvFormat(format.delimiter).parse(data+''); } function isBuffer(_) { return (typeof Buffer === 'function' && isFunction(Buffer.isBuffer)) ? Buffer.isBuffer(_) : false; } function json$1(data, format) { data = isObject(data) && !isBuffer(data) ? data : JSON.parse(data); return (format && format.property) ? field(format.property)(data) : data; } function noop$1() {} function transformAbsolute(transform) { if (!transform) return noop$1; var x0, y0, kx = transform.scale[0], ky = transform.scale[1], dx = transform.translate[0], dy = transform.translate[1]; return function(point, i) { if (!i) x0 = y0 = 0; point[0] = (x0 += point[0]) * kx + dx; point[1] = (y0 += point[1]) * ky + dy; }; } function reverse(array, n) { var t, j = array.length, i = j - n; while (i < --j) t = array[i], array[i++] = array[j], array[j] = t; } function feature(topology, o) { return o.type === "GeometryCollection" ? { type: "FeatureCollection", features: o.geometries.map(function(o) { return feature$1(topology, o); }) } : feature$1(topology, o); } function feature$1(topology, o) { var f = { type: "Feature", id: o.id, properties: o.properties || {}, geometry: object(topology, o) }; if (o.id == null) delete f.id; return f; } function object(topology, o) { var absolute = transformAbsolute(topology.transform), arcs = topology.arcs; function arc(i, points) { if (points.length) points.pop(); for (var a = arcs[i < 0 ? ~i : i], k = 0, n = a.length, p; k < n; ++k) { points.push(p = a[k].slice()); absolute(p, k); } if (i < 0) reverse(points, n); } function point(p) { p = p.slice(); absolute(p, 0); return p; } function line(arcs) { var points = []; for (var i = 0, n = arcs.length; i < n; ++i) arc(arcs[i], points); if (points.length < 2) points.push(points[0].slice()); return points; } function ring(arcs) { var points = line(arcs); while (points.length < 4) points.push(points[0].slice()); return points; } function polygon(arcs) { return arcs.map(ring); } function geometry(o) { var t = o.type; return t === "GeometryCollection" ? {type: t, geometries: o.geometries.map(geometry)} : t in geometryType ? {type: t, coordinates: geometryType[t](o)} : null; } var geometryType = { Point: function(o) { return point(o.coordinates); }, MultiPoint: function(o) { return o.coordinates.map(point); }, LineString: function(o) { return line(o.arcs); }, MultiLineString: function(o) { return o.arcs.map(line); }, Polygon: function(o) { return polygon(o.arcs); }, MultiPolygon: function(o) { return o.arcs.map(polygon); } }; return geometry(o); } function stitchArcs(topology, arcs) { var stitchedArcs = {}, fragmentByStart = {}, fragmentByEnd = {}, fragments = [], emptyIndex = -1; // Stitch empty arcs first, since they may be subsumed by other arcs. arcs.forEach(function(i, j) { var arc = topology.arcs[i < 0 ? ~i : i], t; if (arc.length < 3 && !arc[1][0] && !arc[1][1]) { t = arcs[++emptyIndex], arcs[emptyIndex] = i, arcs[j] = t; } }); arcs.forEach(function(i) { var e = ends(i), start = e[0], end = e[1], f, g; if (f = fragmentByEnd[start]) { delete fragmentByEnd[f.end]; f.push(i); f.end = end; if (g = fragmentByStart[end]) { delete fragmentByStart[g.start]; var fg = g === f ? f : f.concat(g); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else if (f = fragmentByStart[end]) { delete fragmentByStart[f.start]; f.unshift(i); f.start = start; if (g = fragmentByEnd[start]) { delete fragmentByEnd[g.end]; var gf = g === f ? f : g.concat(f); fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else { f = [i]; fragmentByStart[f.start = start] = fragmentByEnd[f.end = end] = f; } }); function ends(i) { var arc = topology.arcs[i < 0 ? ~i : i], p0 = arc[0], p1; if (topology.transform) p1 = [0, 0], arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); else p1 = arc[arc.length - 1]; return i < 0 ? [p1, p0] : [p0, p1]; } function flush(fragmentByEnd, fragmentByStart) { for (var k in fragmentByEnd) { var f = fragmentByEnd[k]; delete fragmentByStart[f.start]; delete f.start; delete f.end; f.forEach(function(i) { stitchedArcs[i < 0 ? ~i : i] = 1; }); fragments.push(f); } } flush(fragmentByEnd, fragmentByStart); flush(fragmentByStart, fragmentByEnd); arcs.forEach(function(i) { if (!stitchedArcs[i < 0 ? ~i : i]) fragments.push([i]); }); return fragments; } function mesh(topology) { return object(topology, meshArcs.apply(this, arguments)); } function meshArcs(topology, o, filter) { var arcs = []; function arc(i) { var j = i < 0 ? ~i : i; (geomsByArc[j] || (geomsByArc[j] = [])).push({i: i, g: geom}); } function line(arcs) { arcs.forEach(arc); } function polygon(arcs) { arcs.forEach(line); } function geometry(o) { if (o.type === "GeometryCollection") o.geometries.forEach(geometry); else if (o.type in geometryType) geom = o, geometryType[o.type](o.arcs); } if (arguments.length > 1) { var geomsByArc = [], geom; var geometryType = { LineString: line, MultiLineString: polygon, Polygon: polygon, MultiPolygon: function(arcs) { arcs.forEach(polygon); } }; geometry(o); geomsByArc.forEach(arguments.length < 3 ? function(geoms) { arcs.push(geoms[0].i); } : function(geoms) { if (filter(geoms[0].g, geoms[geoms.length - 1].g)) arcs.push(geoms[0].i); }); } else { for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i); } return {type: "MultiLineString", arcs: stitchArcs(topology, arcs)}; } function topojson(data, format) { var object, property; data = json$1(data, format); if (format && (property = format.feature)) { return (object = data.objects[property]) ? feature(data, object).features : error('Invalid TopoJSON object: ' + property); } else if (format && (property = format.mesh)) { return (object = data.objects[property]) ? [mesh(data, object)] : error('Invalid TopoJSON object: ' + property); } error('Missing TopoJSON feature or mesh parameter.'); } var formats = { dsv: dsv$1, csv: delimitedFormat(','), tsv: delimitedFormat('\t'), json: json$1, topojson: topojson }; function formats$1(name, format) { return arguments.length > 1 ? (formats[name] = format, this) : formats.hasOwnProperty(name) ? formats[name] : null; } var t0 = new Date; var t1 = new Date; function newInterval(floori, offseti, count, field) { function interval(date) { return floori(date = new Date(+date)), date; } interval.floor = interval; interval.ceil = function(date) { return floori(date = new Date(date - 1)), offseti(date, 1), floori(date), date; }; interval.round = function(date) { var d0 = interval(date), d1 = interval.ceil(date); return date - d0 < d1 - date ? d0 : d1; }; interval.offset = function(date, step) { return offseti(date = new Date(+date), step == null ? 1 : Math.floor(step)), date; }; interval.range = function(start, stop, step) { var range = []; start = interval.ceil(start); step = step == null ? 1 : Math.floor(step); if (!(start < stop) || !(step > 0)) return range; // also handles Invalid Date do range.push(new Date(+start)); while (offseti(start, step), floori(start), start < stop) return range; }; interval.filter = function(test) { return newInterval(function(date) { if (date >= date) while (floori(date), !test(date)) date.setTime(date - 1); }, function(date, step) { if (date >= date) while (--step >= 0) while (offseti(date, 1), !test(date)) {} // eslint-disable-line no-empty }); }; if (count) { interval.count = function(start, end) { t0.setTime(+start), t1.setTime(+end); floori(t0), floori(t1); return Math.floor(count(t0, t1)); }; interval.every = function(step) { step = Math.floor(step); return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval : interval.filter(field ? function(d) { return field(d) % step === 0; } : function(d) { return interval.count(0, d) % step === 0; }); }; } return interval; } var millisecond = newInterval(function() { // noop }, function(date, step) { date.setTime(+date + step); }, function(start, end) { return end - start; }); // An optimized implementation for this simple case. millisecond.every = function(k) { k = Math.floor(k); if (!isFinite(k) || !(k > 0)) return null; if (!(k > 1)) return millisecond; return newInterval(function(date) { date.setTime(Math.floor(date / k) * k); }, function(date, step) { date.setTime(+date + step * k); }, function(start, end) { return (end - start) / k; }); }; var durationSecond = 1e3; var durationMinute = 6e4; var durationHour = 36e5; var durationDay = 864e5; var durationWeek = 6048e5; var second = newInterval(function(date) { date.setTime(Math.floor(date / durationSecond) * durationSecond); }, function(date, step) { date.setTime(+date + step * durationSecond); }, function(start, end) { return (end - start) / durationSecond; }, function(date) { return date.getUTCSeconds(); }); var minute = newInterval(function(date) { date.setTime(Math.floor(date / durationMinute) * durationMinute); }, function(date, step) { date.setTime(+date + step * durationMinute); }, function(start, end) { return (end - start) / durationMinute; }, function(date) { return date.getMinutes(); }); var hour = newInterval(function(date) { var offset = date.getTimezoneOffset() * durationMinute % durationHour; if (offset < 0) offset += durationHour; date.setTime(Math.floor((+date - offset) / durationHour) * durationHour + offset); }, function(date, step) { date.setTime(+date + step * durationHour); }, function(start, end) { return (end - start) / durationHour; }, function(date) { return date.getHours(); }); var day = newInterval(function(date) { date.setHours(0, 0, 0, 0); }, function(date, step) { date.setDate(date.getDate() + step); }, function(start, end) { return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay; }, function(date) { return date.getDate() - 1; }); function weekday(i) { return newInterval(function(date) { date.setDate(date.getDate() - (date.getDay() + 7 - i) % 7); date.setHours(0, 0, 0, 0); }, function(date, step) { date.setDate(date.getDate() + step * 7); }, function(start, end) { return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek; }); } var timeWeek = weekday(0); var monday = weekday(1); var month = newInterval(function(date) { date.setDate(1); date.setHours(0, 0, 0, 0); }, function(date, step) { date.setMonth(date.getMonth() + step); }, function(start, end) { return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12; }, function(date) { return date.getMonth(); }); var year = newInterval(function(date) { date.setMonth(0, 1); date.setHours(0, 0, 0, 0); }, function(date, step) { date.setFullYear(date.getFullYear() + step); }, function(start, end) { return end.getFullYear() - start.getFullYear(); }, function(date) { return date.getFullYear(); }); // An optimized implementation for this simple case. year.every = function(k) { return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) { date.setFullYear(Math.floor(date.getFullYear() / k) * k); date.setMonth(0, 1); date.setHours(0, 0, 0, 0); }, function(date, step) { date.setFullYear(date.getFullYear() + step * k); }); }; var utcMinute = newInterval(function(date) { date.setUTCSeconds(0, 0); }, function(date, step) { date.setTime(+date + step * durationMinute); }, function(start, end) { return (end - start) / durationMinute; }, function(date) { return date.getUTCMinutes(); }); var utcHour = newInterval(function(date) { date.setUTCMinutes(0, 0, 0); }, function(date, step) { date.setTime(+date + step * durationHour); }, function(start, end) { return (end - start) / durationHour; }, function(date) { return date.getUTCHours(); }); var utcDay = newInterval(function(date) { date.setUTCHours(0, 0, 0, 0); }, function(date, step) { date.setUTCDate(date.getUTCDate() + step); }, function(start, end) { return (end - start) / durationDay; }, function(date) { return date.getUTCDate() - 1; }); function utcWeekday(i) { return newInterval(function(date) { date.setUTCDate(date.getUTCDate() - (date.getUTCDay() + 7 - i) % 7); date.setUTCHours(0, 0, 0, 0); }, function(date, step) { date.setUTCDate(date.getUTCDate() + step * 7); }, function(start, end) { return (end - start) / durationWeek; }); } var utcWeek = utcWeekday(0); var utcMonday = utcWeekday(1); var utcMonth = newInterval(function(date) { date.setUTCDate(1); date.setUTCHours(0, 0, 0, 0); }, function(date, step) { date.setUTCMonth(date.getUTCMonth() + step); }, function(start, end) { return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12; }, function(date) { return date.getUTCMonth(); }); var utcYear = newInterval(function(date) { date.setUTCMonth(0, 1); date.setUTCHours(0, 0, 0, 0); }, function(date, step) { date.setUTCFullYear(date.getUTCFullYear() + step); }, function(start, end) { return end.getUTCFullYear() - start.getUTCFullYear(); }, function(date) { return date.getUTCFullYear(); }); // An optimized implementation for this simple case. utcYear.every = function(k) { return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date) { date.setUTCFullYear(Math.floor(date.getUTCFullYear() / k) * k); date.setUTCMonth(0, 1); date.setUTCHours(0, 0, 0, 0); }, function(date, step) { date.setUTCFullYear(date.getUTCFullYear() + step * k); }); }; function localDate(d) { if (0 <= d.y && d.y < 100) { var date = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L); date.setFullYear(d.y); return date; } return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L); } function utcDate(d) { if (0 <= d.y && d.y < 100) { var date = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L)); date.setUTCFullYear(d.y); return date; } return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L)); } function newYear(y) { return {y: y, m: 0, d: 1, H: 0, M: 0, S: 0, L: 0}; } function formatLocale(locale) { var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_weekdays = locale.days, locale_shortWeekdays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths; var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths); var formats = { "a": formatShortWeekday, "A": formatWeekday, "b": formatShortMonth, "B": formatMonth, "c": null, "d": formatDayOfMonth, "e": formatDayOfMonth, "H": formatHour24, "I": formatHour12, "j": formatDayOfYear, "L": formatMilliseconds, "m": formatMonthNumber, "M": formatMinutes, "p": formatPeriod, "S": formatSeconds, "U": formatWeekNumberSunday, "w": formatWeekdayNumber, "W": formatWeekNumberMonday, "x": null, "X": null, "y": formatYear, "Y": formatFullYear, "Z": formatZone, "%": formatLiteralPercent }; var utcFormats = { "a": formatUTCShortWeekday, "A": formatUTCWeekday, "b": formatUTCShortMonth, "B": formatUTCMonth, "c": null, "d": formatUTCDayOfMonth, "e": formatUTCDayOfMonth, "H": formatUTCHour24, "I": formatUTCHour12, "j": formatUTCDayOfYear, "L": formatUTCMilliseconds, "m": formatUTCMonthNumber, "M": formatUTCMinutes, "p": formatUTCPeriod, "S": formatUTCSeconds, "U": formatUTCWeekNumberSunday, "w": formatUTCWeekdayNumber, "W": formatUTCWeekNumberMonday, "x": null, "X": null, "y": formatUTCYear, "Y": formatUTCFullYear, "Z": formatUTCZone, "%": formatLiteralPercent }; var parses = { "a": parseShortWeekday, "A": parseWeekday, "b": parseShortMonth, "B": parseMonth, "c": parseLocaleDateTime, "d": parseDayOfMonth, "e": parseDayOfMonth, "H": parseHour24, "I": parseHour24, "j": parseDayOfYear, "L": parseMilliseconds, "m": parseMonthNumber, "M": parseMinutes, "p": parsePeriod, "S": parseSeconds, "U": parseWeekNumberSunday, "w": parseWeekdayNumber, "W": parseWeekNumberMonday, "x": parseLocaleDate, "X": parseLocaleTime, "y": parseYear, "Y": parseFullYear, "Z": parseZone, "%": parseLiteralPercent }; // These recursive directive definitions must be deferred. formats.x = newFormat(locale_date, formats); formats.X = newFormat(locale_time, formats); formats.c = newFormat(locale_dateTime, formats); utcFormats.x = newFormat(locale_date, utcFormats); utcFormats.X = newFormat(locale_time, utcFormats); utcFormats.c = newFormat(locale_dateTime, utcFormats); function newFormat(specifier, formats) { return function(date) { var string = [], i = -1, j = 0, n = specifier.length, c, pad, format; if (!(date instanceof Date)) date = new Date(+date); while (++i < n) { if (specifier.charCodeAt(i) === 37) { string.push(specifier.slice(j, i)); if ((pad = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i); else pad = c === "e" ? " " : "0"; if (format = formats[c]) c = format(date, pad); string.push(c); j = i + 1; } } string.push(specifier.slice(j, i)); return string.join(""); }; } function newParse(specifier, newDate) { return function(string) { var d = newYear(1900), i = parseSpecifier(d, specifier, string += "", 0); if (i != string.length) return null; // The am-pm flag is 0 for AM, and 1 for PM. if ("p" in d) d.H = d.H % 12 + d.p * 12; // Convert day-of-week and week-of-year to day-of-year. if ("W" in d || "U" in d) { if (!("w" in d)) d.w = "W" in d ? 1 : 0; var day = "Z" in d ? utcDate(newYear(d.y)).getUTCDay() : newDate(newYear(d.y)).getDay(); d.m = 0; d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day + 5) % 7 : d.w + d.U * 7 - (day + 6) % 7; } // If a time zone is specified, all fields are interpreted as UTC and then // offset according to the specified time zone. if ("Z" in d) { d.H += d.Z / 100 | 0; d.M += d.Z % 100; return utcDate(d); } // Otherwise, all fields are in local time. return newDate(d); }; } function parseSpecifier(d, specifier, string, j) { var i = 0, n = specifier.length, m = string.length, c, parse; while (i < n) { if (j >= m) return -1; c = specifier.charCodeAt(i++); if (c === 37) { c = specifier.charAt(i++); parse = parses[c in pads ? specifier.charAt(i++) : c]; if (!parse || ((j = parse(d, string, j)) < 0)) return -1; } else if (c != string.charCodeAt(j++)) { return -1; } } return j; } function parsePeriod(d, string, i) { var n = periodRe.exec(string.slice(i)); return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1; } function parseShortWeekday(d, string, i) { var n = shortWeekdayRe.exec(string.slice(i)); return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1; } function parseWeekday(d, string, i) { var n = weekdayRe.exec(string.slice(i)); return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1; } function parseShortMonth(d, string, i) { var n = shortMonthRe.exec(string.slice(i)); return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1; } function parseMonth(d, string, i) { var n = monthRe.exec(string.slice(i)); return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1; } function parseLocaleDateTime(d, string, i) { return parseSpecifier(d, locale_dateTime, string, i); } function parseLocaleDate(d, string, i) { return parseSpecifier(d, locale_date, string, i); } function parseLocaleTime(d, string, i) { return parseSpecifier(d, locale_time, string, i); } function formatShortWeekday(d) { return locale_shortWeekdays[d.getDay()]; } function formatWeekday(d) { return locale_weekdays[d.getDay()]; } function formatShortMonth(d) { return locale_shortMonths[d.getMonth()]; } function formatMonth(d) { return locale_months[d.getMonth()]; } function formatPeriod(d) { return locale_periods[+(d.getHours() >= 12)]; } function formatUTCShortWeekday(d) { return locale_shortWeekdays[d.getUTCDay()]; } function formatUTCWeekday(d) { return locale_weekdays[d.getUTCDay()]; } function formatUTCShortMonth(d) { return locale_shortMonths[d.getUTCMonth()]; } function formatUTCMonth(d) { return locale_months[d.getUTCMonth()]; } function formatUTCPeriod(d) { return locale_periods[+(d.getUTCHours() >= 12)]; } return { format: function(specifier) { var f = newFormat(specifier += "", formats); f.toString = function() { return specifier; }; return f; }, parse: function(specifier) { var p = newParse(specifier += "", localDate); p.toString = function() { return specifier; }; return p; }, utcFormat: function(specifier) { var f = newFormat(specifier += "", utcFormats); f.toString = function() { return specifier; }; return f; }, utcParse: function(specifier) { var p = newParse(specifier, utcDate); p.toString = function() { return specifier; }; return p; } }; } var pads = {"-": "", "_": " ", "0": "0"}; var numberRe = /^\s*\d+/; var percentRe = /^%/; var requoteRe = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; function pad$1(value, fill, width) { var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length; return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string); } function requote(s) { return s.replace(requoteRe, "\\$&"); } function formatRe(names) { return new RegExp("^(?:" + names.map(requote).join("|") + ")", "i"); } function formatLookup(names) { var map = {}, i = -1, n = names.length; while (++i < n) map[names[i].toLowerCase()] = i; return map; } function parseWeekdayNumber(d, string, i) { var n = numberRe.exec(string.slice(i, i + 1)); return n ? (d.w = +n[0], i + n[0].length) : -1; } function parseWeekNumberSunday(d, string, i) { var n = numberRe.exec(string.slice(i)); return n ? (d.U = +n[0], i + n[0].length) : -1; } function parseWeekNumberMonday(d, string, i) { var n = numberRe.exec(string.slice(i)); return n ? (d.W = +n[0], i + n[0].length) : -1; } function parseFullYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 4)); return n ? (d.y = +n[0], i + n[0].length) : -1; } function parseYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2000), i + n[0].length) : -1; } function parseZone(d, string, i) { var n = /^(Z)|([+-]\d\d)(?:\:?(\d\d))?/.exec(string.slice(i, i + 6)); return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1; } function parseMonthNumber(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.m = n[0] - 1, i + n[0].length) : -1; } function parseDayOfMonth(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.d = +n[0], i + n[0].length) : -1; } function parseDayOfYear(d, string, i) { var n = numberRe.exec(string.slice(i, i + 3)); return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1; } function parseHour24(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.H = +n[0], i + n[0].length) : -1; } function parseMinutes(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.M = +n[0], i + n[0].length) : -1; } function parseSeconds(d, string, i) { var n = numberRe.exec(string.slice(i, i + 2)); return n ? (d.S = +n[0], i + n[0].length) : -1; } function parseMilliseconds(d, string, i) { var n = numberRe.exec(string.slice(i, i + 3)); return n ? (d.L = +n[0], i + n[0].length) : -1; } function parseLiteralPercent(d, string, i) { var n = percentRe.exec(string.slice(i, i + 1)); return n ? i + n[0].length : -1; } function formatDayOfMonth(d, p) { return pad$1(d.getDate(), p, 2); } function formatHour24(d, p) { return pad$1(d.getHours(), p, 2); } function formatHour12(d, p) { return pad$1(d.getHours() % 12 || 12, p, 2); } function formatDayOfYear(d, p) { return pad$1(1 + day.count(year(d), d), p, 3); } function formatMilliseconds(d, p) { return pad$1(d.getMilliseconds(), p, 3); } function formatMonthNumber(d, p) { return pad$1(d.getMonth() + 1, p, 2); } function formatMinutes(d, p) { return pad$1(d.getMinutes(), p, 2); } function formatSeconds(d, p) { return pad$1(d.getSeconds(), p, 2); } function formatWeekNumberSunday(d, p) { return pad$1(timeWeek.count(year(d), d), p, 2); } function formatWeekdayNumber(d) { return d.getDay(); } function formatWeekNumberMonday(d, p) { return pad$1(monday.count(year(d), d), p, 2); } function formatYear(d, p) { return pad$1(d.getFullYear() % 100, p, 2); } function formatFullYear(d, p) { return pad$1(d.getFullYear() % 10000, p, 4); } function formatZone(d) { var z = d.getTimezoneOffset(); return (z > 0 ? "-" : (z *= -1, "+")) + pad$1(z / 60 | 0, "0", 2) + pad$1(z % 60, "0", 2); } function formatUTCDayOfMonth(d, p) { return pad$1(d.getUTCDate(), p, 2); } function formatUTCHour24(d, p) { return pad$1(d.getUTCHours(), p, 2); } function formatUTCHour12(d, p) { return pad$1(d.getUTCHours() % 12 || 12, p, 2); } function formatUTCDayOfYear(d, p) { return pad$1(1 + utcDay.count(utcYear(d), d), p, 3); } function formatUTCMilliseconds(d, p) { return pad$1(d.getUTCMilliseconds(), p, 3); } function formatUTCMonthNumber(d, p) { return pad$1(d.getUTCMonth() + 1, p, 2); } function formatUTCMinutes(d, p) { return pad$1(d.getUTCMinutes(), p, 2); } function formatUTCSeconds(d, p) { return pad$1(d.getUTCSeconds(), p, 2); } function formatUTCWeekNumberSunday(d, p) { return pad$1(utcWeek.count(utcYear(d), d), p, 2); } function formatUTCWeekdayNumber(d) { return d.getUTCDay(); } function formatUTCWeekNumberMonday(d, p) { return pad$1(utcMonday.count(utcYear(d), d), p, 2); } function formatUTCYear(d, p) { return pad$1(d.getUTCFullYear() % 100, p, 2); } function formatUTCFullYear(d, p) { return pad$1(d.getUTCFullYear() % 10000, p, 4); } function formatUTCZone() { return "+0000"; } function formatLiteralPercent() { return "%"; } var locale; var timeFormat; var timeParse; var utcFormat; var utcParse; defaultLocale({ dateTime: "%x, %X", date: "%-m/%-d/%Y", time: "%-I:%M:%S %p", periods: ["AM", "PM"], days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], 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"] }); function defaultLocale(definition) { locale = formatLocale(definition); timeFormat = locale.format; timeParse = locale.parse; utcFormat = locale.utcFormat; utcParse = locale.utcParse; return locale; } var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ"; function formatIsoNative(date) { return date.toISOString(); } var formatIso = Date.prototype.toISOString ? formatIsoNative : utcFormat(isoSpecifier); function parseIsoNative(string) { var date = new Date(string); return isNaN(date) ? null : date; } var parseIso = +new Date("2000-01-01T00:00:00.000Z") ? parseIsoNative : utcParse(isoSpecifier); function read(data, schema, dateParse) { schema = schema || {}; var reader = formats$1(schema.type || 'json'); if (!reader) error('Unknown data format type: ' + schema.type); data = reader(data, schema); if (schema.parse) parse(data, schema.parse, dateParse); if (data.hasOwnProperty('columns')) delete data.columns; return data; } function parse(data, types, dateParse) { dateParse = dateParse || timeParse; var fields = data.columns || Object.keys(data[0]), parsers, datum, field, i, j, n, m; if (types === 'auto') types = inferTypes(data, fields); fields = Object.keys(types); parsers = fields.map(function(field) { var type = types[field], parts, pattern; if (type && type.indexOf('date:') === 0) { parts = type.split(/:(.+)?/, 2); // split on first : pattern = parts[1]; if ((pattern[0] === '\'' && pattern[pattern.length-1] === '\'') || (pattern[0] === '"' && pattern[pattern.length-1] === '"')) { pattern = pattern.slice(1, -1); } return dateParse(pattern); } if (!typeParsers[type]) { throw Error('Illegal format pattern: ' + field + ':' + type); } return typeParsers[type]; }); for (i=0, n=data.length, m=fields.length; i<n; ++i) { datum = data[i]; for (j=0; j<m; ++j) { field = fields[j]; datum[field] = parsers[j](datum[field]); } } } function UniqueList(idFunc) { var $ = idFunc || identity$1, list = [], ids = {}; list.add = function(_) { var id = $(_); if (!ids[id]) { ids[id] = 1; list.push(_); } return list; }; list.remove = function(_) { var id = $(_), idx; if (ids[id]) { ids[id] = 0; if ((idx = list.indexOf(_)) >= 0) { list.splice(idx, 1); } } return list; }; return list; } var TUPLE_ID = 1; /** * Returns the id of a tuple. * @param {Tuple} t - The input tuple. * @return the tuple id. */ function tupleid(t) { return t._id; } /** * Copy the values of one tuple to another (ignoring id and prev fields). * @param {Tuple} t - The tuple to copy from. * @param {Tuple} c - The tuple to write to. * @return The re-written tuple, same as the argument 'c'. */ function copy(t, c) { for (var k in t) { if (k !== '_id') c[k] = t[k]; } return c; } /** * Ingest an object or value as a data tuple. * If the input value is an object, an id field will be added to it. For * efficiency, the input object is modified directly. A copy is not made. * If the input value is a literal, it will be wrapped in a new object * instance, with the value accessible as the 'data' property. * @param datum - The value to ingest. * @return {Tuple} The ingested data tuple. */ function ingest(datum) { var tuple = (datum === Object(datum)) ? datum : {data: datum}; if (!tuple._id) tuple._id = ++TUPLE_ID; return tuple; } /** * Given a source tuple, return a derived copy. * @param {object} t - The source tuple. * @return {object} The derived tuple. */ function derive(t) { return ingest(copy(t, {})); } /** * Rederive a derived tuple by copying values from the source tuple. * @param {object} t - The source tuple. * @param {object} d - The derived tuple. * @return {object} The derived tuple. */ function rederive(t, d) { return copy(t, d); } /** * Replace an existing tuple with a new tuple. * The existing tuple will become the previous value of the new. * @param {object} t - The existing data tuple. * @param {object} d - The new tuple that replaces the old. * @return {object} The new tuple. */ function replace(t, d) { return d._id = t._id, d; } function isChangeSet(v) { return v && v.constructor === changeset; } function changeset() { var add = [], // insert tuples rem = [], // remove tuples mod = [], // modify tuples remp = [], // remove by predicate modp = []; // modify by predicate return { constructor: changeset, insert: function(t) { var d = array$1(t), i = 0, n = d.length; for (; i<n; ++i) add.push(d[i]); return this; }, remove: function(t) { var a = isFunction(t) ? remp : rem, d = array$1(t), i = 0, n = d.length; for (; i<n; ++i) a.push(d[i]); return this; }, modify: function(t, field, value) { var m = {field: field, value: constant$1(value)}; if (isFunction(t)) m.filter = t, modp.push(m); else m.tuple = t, mod.push(m); return this; }, encode: function(t, set) { mod.push({tuple: t, field: set}); return this; }, pulse: function(pulse, tuples) { var out, i, n, m, f, t, id; // add for (i=0, n=add.length; i<n; ++i) { pulse.add.push(ingest(add[i])); } // remove for (out={}, i=0, n=rem.length; i<n; ++i) { t = rem[i]; out[t._id] = t; } for (i=0, n=remp.length; i<n; ++i) { f = remp[i]; tuples.forEach(function(t) { if (f(t)) out[t._id] = t; }); } for (id in out) pulse.rem.push(out[id]); // modify function modify(t, f, v) { if (v) t[f] = v(t); else pulse.encode = f; out[t._id] = t; } for (out={}, i=0, n=mod.length; i<n; ++i) { m = mod[i]; modify(m.tuple, m.field, m.value); pulse.modifies(m.field); } for (i=0, n=modp.length; i<n; ++i) { m = modp[i]; f = m.filter; tuples.forEach(function(t) { if (f(t)) modify(t, m.field, m.value); }); pulse.modifies(m.field); } for (id in out) pulse.mod.push(out[id]); return pulse; } }; } var CACHE = '_:mod:_'; /** * Hash that tracks modifications to assigned values. * Callers *must* use the set method to update values. */ function Parameters() { Object.defineProperty(this, CACHE, {writable:true, value: {}}); } var prototype$2 = Parameters.prototype; function key$1(name, index) { return (index != null && index >= 0 ? index + ':' : '') + name; } /** * Set a parameter value. If the parameter value changes, the parameter * will be recorded as modified. * @param {string} name - The parameter name. * @param {number} index - The index into an array-value parameter. Ignored if * the argument is undefined, null or less than zero. * @param {*} value - The parameter value to set. * @param {boolean} [force=false] - If true, records the parameter as modified * even if the value is unchanged. * @return {Parameters} - This parameter object. */ prototype$2.set = function(name, index, value, force) { var o = this, v = o[name], mod = o[CACHE]; if (index != null && index >= 0) { if (v[index] !== value || force) { v[index] = value; mod[key$1(name, index)] = 1; mod[name] = 1; } } else if (v !== value || force) { o[name] = value; mod[name] = 1; if (isArray(value)) value.forEach(function(v, i) { mod[key$1(name, i)] = 1; }); } return o; }; /** * Tests if one or more parameters has been modified. If invoked with no * arguments, returns true if any parameter value has changed. If the first * argument is array, returns trues if any parameter name in the array has * changed. Otherwise, tests if the given name and optional array index has * changed. * @param {string} name - The parameter name to test. * @param {number} [index=undefined] - The parameter array index to test. * @return {boolean} - Returns true if a queried parameter was modified. */ prototype$2.modified = function(name, index) { var mod = this[CACHE], k; if (!arguments.length) { for (k in mod) { if (mod[k]) return true; } return false; } else if (isArray(name)) { for (k=0; k<name.length; ++k) { if (mod[name[k]]) return true; } return false; } return !!mod[key$1(name, index)]; }; /** * Clears the modification records. After calling this method, * all parameters are considered unmodified. */ prototype$2.clear = function() { return this[CACHE] = {}, this; }; var OP_ID = 0; var PULSE = 'pulse'; var NO_PARAMS = new Parameters(); // Boolean Flags var SKIP = 1; var MODIFIED = 2; /** * An Operator is a processing node in a dataflow graph. * Each operator stores a value and an optional value update function. * Operators can accept a hash of named parameters. Parameter values can * either be direct (JavaScript literals, arrays, objects) or indirect * (other operators whose values will be pulled dynamically). Operators * included as parameters will have this operator added as a dependency. * @constructor * @param {*} [init] - The initial value for this operator. * @param {function(object, Pulse)} [update] - An update function. Upon * evaluation of this operator, the update function will be invoked and the * return value will be used as the new value of this operator. * @param {object} [params] - The parameters for this operator. * @param {boolean} [react=true] - Flag indicating if this operator should * listen for changes to upstream operators included as parameters. * @see parameters */ function Operator(init, update, params, react) { this.id = ++OP_ID; this.value = init; this.stamp = -1; this.rank = -1; this.qrank = -1; this.flags = 0; if (update) { this._update = update; } if (params) this.parameters(params, react); } var prototype$1 = Operator.prototype; /** * Returns a list of target operators dependent on this operator. * If this list does not exist, it is created and then returned. * @return {UniqueList} */ prototype$1.targets = function() { return this._targets || (this._targets = UniqueList(id)); }; /** * Sets the value of this operator. * @param {*} value - the value to set. * @return {Number} Returns 1 if the operator value has changed * according to strict equality, returns 0 otherwise. */ prototype$1.set = function(value) { return this.value !== value ? (this.value = value, 1) : 0; }; function flag(bit) { return function(state) { var f = this.flags; if (arguments.length === 0) return !!(f & bit); this.flags = state ? (f | bit) : (f & ~bit); return this; }; } /** * Indicates that operator evaluation should be skipped on the next pulse. * This operator will still propagate incoming pulses, but its update function * will not be invoked. The skip flag is reset after every pulse, so calling * this method will affect processing of the next pulse only. */ prototype$1.skip = flag(SKIP); /** * Indicates that this operator's value has been modified on its most recent * pulse. Normally modification is checked via strict equality; however, in * some cases it is more efficient to update the internal state of an object. * In those cases, the modified flag can be used to trigger propagation. Once * set, the modification flag persists across pulses until unset. The flag can * be used with the last timestamp to test if a modification is recent. */ prototype$1.modified = flag(MODIFIED); /** * Sets the parameters for this operator. The parameter values are analyzed for * operator instances. If found, this operator will be added as a dependency * of the parameterizing operator. Operator values are dynamically marshalled * from each operator parameter prior to evaluation. If a parameter value is * an array, the array will also be searched for Operator instances. However, * the search does not recurse into sub-arrays or object properties. * @param {object} params - A hash of operator parameters. * @param {boolean} [react=true] - A flag indicating if this operator should * automatically update (react) when parameter values change. In other words, * this flag determines if the operator registers itself as a listener on * any upstream operators included in the parameters. * @return {Operator[]} - An array of upstream dependencies. */ prototype$1.parameters = function(params, react) { react = react !== false; var self = this, argval = (self._argval = self._argval || new Parameters()), argops = (self._argops = self._argops || []), deps = [], name, value, n, i; function add(name, index, value) { if (value instanceof Operator) { if (value !== self) { if (react) value.targets().add(self); deps.push(value); } argops.push({op:value, name:name, index:index}); } else { argval.set(name, index, value); } } for (name in params) { value = params[name]; if (name === PULSE) { array$1(value).forEach(function(op) { if (!(op instanceof Operator)) { error('Pulse parameters must be operator instances.'); } else if (op !== self) { op.targets().add(self); deps.push(op); } }); self.source = value; } else if (isArray(value)) { argval.set(name, -1, Array(n = value.length)); for (i=0; i<n; ++i) add(name, i, value[i]); } else { add(name, -1, value); } } this.marshall().clear(); // initialize values return deps; }; /** * Internal method for marshalling parameter values. * Visits each operator dependency to pull the latest value. * @return {Parameters} A Parameters object to pass to the update function. */ prototype$1.marshall = function(stamp) { var argval = this._argval || NO_PARAMS, argops = this._argops, item, i, n, op, mod; if (argops && (n = argops.length)) { for (i=0; i<n; ++i) { item = argops[i]; op = item.op; mod = op.modified() && op.stamp === stamp; argval.set(item.name, item.index, op.value, mod); } } return argval; }; /** * Delegate method to perform operator processing. * Subclasses can override this method to perform custom processing. * By default, it marshalls parameters and calls the update function * if that function is defined. If the update function does not * change the operator value then StopPropagation is returned. * If no update function is defined, this method does nothing. * @param {Pulse} pulse - the current dataflow pulse. * @return The output pulse or StopPropagation. A falsy return value * (including undefined) will let the input pulse pass through. */ prototype$1.evaluate = function(pulse) { if (this._update) { var params = this.marshall(pulse.stamp), v = this._update(params, pulse); params.clear(); if (v !== this.value) { this.value = v; } else if (!this.modified()) { return pulse.StopPropagation; } } }; /** * Run this operator for the current pulse. If this operator has already * been run at (or after) the pulse timestamp, returns StopPropagation. * Internally, this method calls {@link evaluate} to perform processing. * If {@link evaluate} returns a falsy value, the input pulse is returned. * This method should NOT be overridden, instead overrride {@link evaluate}. * @param {Pulse} pulse - the current dataflow pulse. * @return the output pulse for this operator (or StopPropagation) */ prototype$1.run = function(pulse) { if (pulse.stamp <= this.stamp) return pulse.StopPropagation; var rv = this.skip() ? (this.skip(false), 0) : this.evaluate(pulse); return this.stamp = pulse.stamp, this.pulse = rv || pulse; }; /** * Add an operator to the dataflow graph. This function accepts a * variety of input argument types. The basic signature supports an * initial value, update function and parameters. If the first parameter * is an Operator instance, it will be added directly. If it is a * constructor for an Operator subclass, a new instance will be instantiated. * Otherwise, if the first parameter is a function instance, it will be used * as the update function and a null initial value is assumed. * @param {*} init - One of: the operator to add, the initial value of * the operator, an operator class to instantiate, or an update function. * @param {function} [update] - The operator update function. * @param {object} [params] - The operator parameters. * @param {boolean} [react=true] - Flag indicating if this operator should * listen for changes to upstream operators included as parameters. * @return {Operator} - The added operator. */ function add(init, update, params, react) { var shift = 1, op = (init instanceof Operator) ? init : init && init.prototype instanceof Operator ? new init() : isFunction(init) ? new Operator(null, init) : (shift = 0, new Operator(init, update)); this.rank(op); if (shift) react = params, params = update; if (params) this.connect(op, op.parameters(params, react)); this.touch(op); return op; } /** * Connect a target operator as a dependent of source operators. * If necessary, this method will rerank the target operator and its * dependents to ensure propagation proceeds in a topologically sorted order. * @param {Operator} target - The target operator. * @param {Array<Operator>} - The source operators that should propagate * to the target operator. */ function connect(target, sources) { var targetRank = target.rank, i, n; for (i=0, n=sources.length; i<n; ++i) { if (targetRank < sources[i].rank) { this.rerank(target); return; } } } var STREAM_ID = 0; /** * Models an event stream. * @constructor * @param {function(Object, number): boolean} [filter] - Filter predicate. * Events pass through when truthy, events are suppressed when falsy. * @param {function(Object): *} [apply] - Applied to input events to produce * new event values. * @param {function(Object)} [receive] - Event callback function to invoke * upon receipt of a new event. Use to override standard event processing. */ function EventStream(filter, apply, receive) { this.id = ++STREAM_ID; this.value = null; if (receive) this.receive = receive; if (filter) this._filter = filter; if (apply) this._apply = apply; } /** * Creates a new event stream instance with the provided * (optional) filter, apply and receive functions. * @param {function(Object, number): boolean} [filter] - Filter predicate. * Events pass through when truthy, events are suppressed when falsy. * @param {function(Object): *} [apply] - Applied to input events to produce * new event values. * @see EventStream */ function stream(filter, apply, receive) { return new EventStream(filter, apply, receive); } var prototype$3 = EventStream.prototype; prototype$3._filter = truthy; prototype$3._apply = identity$1; prototype$3.targets = function() { return this._targets || (this._targets = UniqueList(id)); }; prototype$3.consume = function(_) { if (!arguments.length) return !!this._consume; return (this._consume = !!_, this); }; prototype$3.receive = function(evt) { if (this._filter(evt)) { var val = (this.value = this._apply(evt)), trg = this._targets, n = trg ? trg.length : 0, i = 0; for (; i<n; ++i) trg[i].receive(val); if (this._consume) { evt.preventDefault(); evt.stopPropagation(); } } }; prototype$3.filter = function(filter) { var s = stream(filter); return (this.targets().add(s), s); }; prototype$3.apply = function(apply) { var s = stream(null, apply); return (this.targets().add(s), s); }; prototype$3.merge = function() { var s = stream(); this.targets().add(s); for (var i=0, n=arguments.length; i<n; ++i) { arguments[i].targets().add(s); } return s; }; prototype$3.throttle = function(pause) { var t = -1; return this.filter(function() { var now = Date.now(); return (now - t) > pause ? (t = now, 1) : 0; }); }; prototype$3.debounce = function(delay) { var s = stream(), evt = null, tid = null; function callback() { var df = evt.dataflow; s.receive(evt); evt = null; tid = null; if (df && df.run) df.run(); } this.targets().add(stream(null, null, function(e) { evt = e; if (tid) clearTimeout(tid); tid = setTimeout(callback, delay); })); return s; }; prototype$3.between = function(a, b) { var active = false; a.targets().add(stream(null, null, function() { active = true; })); b.targets().add(stream(null, null, function() { active = false; })); return this.filter(function() { return active; }); }; /** * Create a new event stream from an event source. * @param {object} source - The event source to monitor. The input must * support the addEventListener method. * @param {string} type - The event type. * @param {function(object): boolean} [filter] - Event filter function. * @param {function(object): *} [apply] - Event application function. * If provided, this function will be invoked and the result will be * used as the downstream event value. * @return {EventStream} */ function events(source, type, filter, apply) { var df = this, s = stream(filter, apply), send = function(e) { e.dataflow = df; s.receive(e); df.run(); }, sources; if (typeof source === 'string' && typeof document !== 'undefined') { sources = document.querySelectorAll(source); } else { sources = array$1(source); } for (var i=0, n=sources.length; i<n; ++i) { sources[i].addEventListener(type, send); } return s; } var SKIP$1 = {skip: true}; /** * Perform operator updates in response to events. Applies an * update function to compute a new operator value. If the update function * returns a {@link ChangeSet}, the operator will be pulsed with those tuple * changes. Otherwise, the operator value will be updated to the return value. * @param {EventStream|Operator} source - The event source to react to. * This argument can be either an EventStream or an Operator. * @param {Operator|function(object):Operator} target - The operator to update. * This argument can either be an Operator instance or (if the source * argument is an EventStream), a function that accepts an event object as * input and returns an Operator to target. * @param {function(Parameters,Event): *} [update] - Optional update function * to compute the new operator value, or a literal value to set. Update * functions expect to receive a parameter object and event as arguments. * This function can either return a new operator value or (if the source * argument is an EventStream) a {@link ChangeSet} instance to pulse * the target operator with tuple changes. * @param {object} [params] - The update function parameters. * @param {object} [options] - Additional options hash. If not overridden, * updated operators will be skipped by default. * @param {boolean} [options.skip] - If true, the operator will * be skipped: it will not be evaluated, but its dependents will be. * @param {boolean} [options.force] - If true, the operator will * be re-evaluated even if its value has not changed. * @return {Dataflow} */ function on(source, target, update, params, options) { var fn = source instanceof Operator ? onOperator : onStream; return fn(this, source, target, update, params, options), this; } function onStream(df, stream, target, update, params, options) { var opt = extend({}, options, SKIP$1), func, op; if (!isFunction(target)) target = constant$1(target); if (update === undefined) { func = function(e) { df.touch(target(e)); }; } else if (isFunction(update)) { op = new Operator(null, update, params, false); func = function(e) { var t = target(e), v = (op.evaluate(e), op.value); isChangeSet(v) ? df.pulse(t, v, options) : df.update(t, v, opt); }; } else { func = function(e) { df.update(target(e), update, opt); }; } stream.apply(func); } function onOperator(df, source, target, update, params, options) { var func, op; if (update === undefined) { op = target; } else { func = isFunction(update) ? update : constant$1(update); update = !target ? func : function(_, pulse) { if (!target.skip()) return target.skip(true).value = func(_, pulse); }; op = new Operator(null, update, params, false); op.modified(options && options.force); op.skip(true); // skip first invocation op.rank = 0; if (target) { op.value = target.value; op.targets().add(target); } } source.targets().add(op); } /** * Assigns a rank to an operator. Ranks are assigned in increasing order * by incrementing an internal rank counter. * @param {Operator} op - The operator to assign a rank. */ function rank(op) { op.rank = ++this._rank; } /** * Re-ranks an operator and all downstream target dependencies. This * is necessary when upstream depencies of higher rank are added to * a target operator. * @param {Operator} op - The operator to re-rank. */ function rerank(op) { var queue = [op], cur, list, i; while (queue.length) { this.rank(cur = queue.pop()); if (list = cur._targets) { for (i=list.length; --i >= 0;) { queue.push(list[i]); } } } } /** * Sentinel value indicating pulse propagation should stop. */ var StopPropagation = {}; // Pulse visit type flags var ADD = (1 << 0); var REM = (1 << 1); var MOD = (1 << 2); var ADD_REM = ADD | REM; var ADD_MOD = ADD | MOD; var ALL = ADD | REM | MOD; var REFLOW = (1 << 3); var SOURCE = (1 << 4); var NO_SOURCE = (1 << 5); var NO_FIELDS = (1 << 6); /** * A Pulse enables inter-operator communication during a run of the * dataflow graph. In addition to the current timestamp, a pulse may also * contain a change-set of added, removed or modified data tuples, as well as * a pointer to a full backing data source. Tuple change sets may not * be fully materialized; for example, to prevent needless array creation * a change set may include larger arrays and corresponding filter functions. * The pulse provides a {@link visit} method to enable proper and efficient * iteration over requested data tuples. * * In addition, each pulse can track modification flags for data tuple fields. * Responsible transform operators should call the {@link modifies} method to * indicate changes to data fields. The {@link modified} method enables * querying of this modification state. * * @constructor * @param {Dataflow} dataflow - The backing dataflow instance. * @param {number} stamp - The current propagation timestamp. * @param {string} [encode] - An optional encoding set name, which is then * accessible as Pulse.encode. Operators can respond to (or ignore) this * setting as appropriate. This parameter can be used in conjunction with * the Encode transform in the vega-encode module. */ function Pulse(dataflow, stamp, encode) { this.dataflow = dataflow; this.stamp = stamp == null ? -1 : stamp; this.add = []; this.rem = []; this.mod = []; this.fields = null; this.encode = encode || null; } var prototype$4 = Pulse.prototype; /** * Sentinel value indicating pulse propagation should stop. */ prototype$4.StopPropagation = StopPropagation; /** * Boolean flag indicating ADD (added) tuples. */ prototype$4.ADD = ADD; /** * Boolean flag indicating REM (removed) tuples. */ prototype$4.REM = REM; /** * Boolean flag indicating MOD (modified) tuples. */ prototype$4.MOD = MOD; /** * Boolean flag indicating ADD (added) and REM (removed) tuples. */ prototype$4.ADD_REM = ADD_REM; /** * Boolean flag indicating ADD (added) and MOD (modified) tuples. */ prototype$4.ADD_MOD = ADD_MOD; /** * Boolean flag indicating ADD, REM and MOD tuples. */ prototype$4.ALL = ALL; /** * Boolean flag indicating all tuples in a data source * except for the ADD, REM and MOD tuples. */ prototype$4.REFLOW = REFLOW; /** * Boolean flag indicating a 'pass-through' to a * backing data source, ignoring ADD, REM and MOD tuples. */ prototype$4.SOURCE = SOURCE; /** * Boolean flag indicating that source data should be * suppressed when creating a forked pulse. */ prototype$4.NO_SOURCE = NO_SOURCE; /** * Boolean flag indicating that field modifications should be * suppressed when creating a forked pulse. */ prototype$4.NO_FIELDS = NO_FIELDS; /** * Creates a new pulse based on the values of this pulse. * The dataflow, time stamp and field modification values are copied over. * By default, new empty ADD, REM and MOD arrays are created. * @param {number} flags - Integer of boolean flags indicating which (if any) * tuple arrays should be copied to the new pulse. The supported flag values * are ADD, REM and MOD. Array references are copied directly: new array * instances are not created. * @return {Pulse} - The forked pulse instance. * @see init */ prototype$4.fork = function(flags) { return new Pulse(this.dataflow).init(this, flags); }; /** * Returns a pulse that adds all tuples from a backing source. This is * useful for cases where operators are added to a dataflow after an * upstream data pipeline has already been processed, ensuring that * new operators can observe all tuples within a stream. * @return {Pulse} - A pulse instance with all source tuples included * in the add array. If the current pulse already has all source * tuples in its add array, it is returned directly. If the current * pulse does not have a backing source, it is returned directly. */ prototype$4.addAll = function() { var p = this; return (!this.source || this.source.length === this.add.length) ? p : (p = new Pulse(this.dataflow).init(this), p.add = p.source, p); }; /** * Initialize this pulse based on the values of another pulse. This method * is used internally by {@link fork} to initialize a new forked tuple. * The dataflow, time stamp and field modification values are copied over. * By default, new empty ADD, REM and MOD arrays are created. * @param {Pulse} src - The source pulse to copy from. * @param {number} flags - Integer of boolean flags indicating which (if any) * tuple arrays should be copied to the new pulse. The supported flag values * are ADD, REM and MOD. Array references are copied directly: new array * instances are not created. By default, source data arrays are copied * to the new pulse. Use the NO_SOURCE flag to enforce a null source. * @return {Pulse} - Returns this Pulse instance. */ prototype$4.init = function(src, flags) { var p = this; p.stamp = src.stamp; p.encode = src.encode; if (src.fields && !(flags & NO_FIELDS)) p.fields = src.fields; p.add = (flags & ADD) ? (p.addF = src.addF, src.add) : (p.addF = null, []); p.rem = (flags & REM) ? (p.remF = src.remF, src.rem) : (p.remF = null, []); p.mod = (flags & MOD) ? (p.modF = src.modF, src.mod) : (p.modF = null, []); p.source = (flags & NO_SOURCE) ? (p.srcF = null, null) : (p.srcF = src.srcF, src.source); return p; }; /** * Schedules a function to run after pulse propagation completes. * @param {function} func - The function to run. */ prototype$4.runAfter = function(func) { this.dataflow.runAfter(func); }; /** * Indicates if tuples have been added, removed or modified. * @param {number} [flags] - The tuple types (ADD, REM or MOD) to query. * Defaults to ALL, returning true if any tuple type has changed. * @return {boolean} - Returns true if one or more queried tuple types have * changed, false otherwise. */ prototype$4.changed = function(flags) { var f = flags || ALL; return ((f & ADD) && this.add.length) || ((f & REM) && this.rem.length) || ((f & MOD) && this.mod.length); }; /** * Forces a "reflow" of tuple values, such that all tuples in the backing * source are added to the MOD set, unless already present in the ADD set. * @param {boolean} [fork=false] - If true, returns a forked copy of this * pulse, and invokes reflow on that derived pulse. * @return {Pulse} - The reflowed pulse instance. */ prototype$4.reflow = function(fork) { if (fork) return this.fork(ALL).reflow(); var len = this.add.length, src = this.source && this.source.length; if (src && src !== len) { this.mod = this.source; if (len) this.filter(MOD, filter(this, ADD)); } return this; }; /** * Marks one or more data field names as modified to assist dependency * tracking and incremental processing by transform operators. * @param {string|Array<string>} _ - The field(s) to mark as modified. * @return {Pulse} - This pulse instance. */ prototype$4.modifies = function(_) { var fields = array$1(_), hash = this.fields || (this.fields = {}); fields.forEach(function(f) { hash[f] = true; }); return this; }; /** * Checks if one or more data fields have been modified during this pulse * propagation timestamp. * @param {string|Array<string>} _ - The field(s) to check for modified. * @return {boolean} - Returns true if any of the provided fields has been * marked as modified, false otherwise. */ prototype$4.modified = function(_) { var fields = this.fields; return !(this.mod.length && fields) ? false : !arguments.length ? !!fields : isArray(_) ? _.some(function(f) { return fields[f]; }) : fields[_]; }; /** * Adds a filter function to one more tuple sets. Filters are applied to * backing tuple arrays, to determine the actual set of tuples considered * added, removed or modified. They can be used to delay materialization of * a tuple set in order to avoid expensive array copies. In addition, the * filter functions can serve as value transformers: unlike standard predicate * function (which return boolean values), Pulse filters should return the * actual tuple value to process. If a tuple set is already filtered, the * new filter value will be appended into a conjuntive ('and') query. * @param {number} flags - Flags indicating the tuple set(s) to filter. * @param {function(*):object} filter - Filter function that will be applied * to the tuple set array, and should return a data tuple if the value * should be included in the tuple set, and falsy (or null) otherwise. * @return {Pulse} - Returns this pulse instance. */ prototype$4.filter = function(flags, filter) { var p = this; if (flags & ADD) p.addF = addFilter(p.addF, filter); if (flags & REM) p.remF = addFilter(p.remF, filter); if (flags & MOD) p.modF = addFilter(p.modF, filter); if (flags & SOURCE) p.srcF = addFilter(p.srcF, filter); return p; }; function addFilter(a, b) { return a ? function(t,i) { return a(t,i) && b(t,i); } : b; } /** * Materialize one or more tuple sets in this pulse. If the tuple set(s) have * a registered filter function, it will be applied and the tuple set(s) will * be replaced with materialized tuple arrays. * @param {number} flags - Flags indicating the tuple set(s) to materialize. * @return {Pulse} - Returns this pulse instance. */ prototype$4.materialize = function(flags) { flags = flags || ALL; var p = this; if ((flags & ADD) && p.addF) { p.add = p.add.filter(p.addF); p.addF = null; } if ((flags & REM) && p.remF) { p.rem = p.rem.filter(p.remF); p.remF = null; } if ((flags & MOD) && p.modF) { p.mod = p.mod.filter(p.modF); p.modF = null; } if ((flags & SOURCE) && p.srcF) { p.source = p.source.filter(p.srcF); p.srcF = null; } return p; }; function filter(pulse, flags) { var map = {}; pulse.visit(flags, function(t) { map[t._id] = 1; }); return function(t) { return map[t._id] ? null : t; }; } /** * Visit one or more tuple sets in this pulse. * @param {number} flags - Flags indicating the tuple set(s) to visit. * Legal values are ADD, REM, MOD and SOURCE (if a backing data source * has been set). * @param {function(object):*} - Visitor function invoked per-tuple. * @return {Pulse} - Returns this pulse instance. */ prototype$4.visit = function(flags, visitor) { var v = visitor, src, sum; if (flags & SOURCE) { visitArray(this.source, this.srcF, v); return this; } if (flags & ADD) visitArray(this.add, this.addF, v); if (flags & REM) visitArray(this.rem, this.remF, v); if (flags & MOD) visitArray(this.mod, this.modF, v); if ((flags & REFLOW) && (src = this.source)) { sum = this.add.length + this.mod.length; if (sum === src) { // do nothing } else if (sum) { visitArray(src, filter(this, ADD_MOD), v); } else { // if no add/rem/mod tuples, visit source visitArray(src, this.srcF, v); } } return this; }; var NO_OPT = {skip: false, force: false}; /** * Touches an operator, scheduling it to be evaluated. If invoked outside of * a pulse propagation, the operator will be evaluated the next time this * dataflow is run. If invoked in the midst of pulse propagation, the operator * will be queued for evaluation if and only if the operator has not yet been * evaluated on the current propagation timestamp. * @param {Operator} op - The operator to touch. * @param {object} [options] - Additional options hash. * @param {boolean} [options.skip] - If true, the operator will * be skipped: it will not be evaluated, but its dependents will be. * @return {Dataflow} */ function touch(op, options) { var opt = options || NO_OPT; if (this._pulse) { this._enqueue(op); } else { this._touched.add(op); } if (opt.skip) op.skip(true); return this; } /** * Updates the value of the given operator. * @param {Operator} op - The operator to update. * @param {*} value - The value to set. * @param {object} [options] - Additional options hash. * @param {boolean} [options.force] - If true, the operator will * be re-evaluated even if its value has not changed. * @param {boolean} [options.skip] - If true, the operator will * be skipped: it will not be evaluated, but its dependents will be. * @return {Dataflow} */ function update(op, value, options) { var opt = options || NO_OPT; if (op.set(value) || opt.force) { this.touch(op, opt); } return this; } /** * Pulses an operator with a changeset of tuples. If invoked outside of * a pulse propagation, the pulse will be applied the next time this * dataflow is run. If invoked in the midst of pulse propagation, the pulse * will be added to the set of active pulses and will be applied if and * only if the target operator has not yet been evaluated on the current * propagation timestamp. * @param {Operator} op - The operator to pulse. * @param {ChangeSet} value - The tuple changeset to apply. * @param {object} [options] - Additional options hash. * @param {boolean} [options.skip] - If true, the operator will * be skipped: it will not be evaluated, but its dependents will be. * @return {Dataflow} */ function pulse(op, changeset, options) { var p = new Pulse(this, this._clock + (this._pulse ? 0 : 1)); p.target = op; this._pulses[op.id] = changeset.pulse(p, op.value); return this.touch(op, options || NO_OPT); } function ingest$1(target, data, format) { return this.pulse(target, this.changeset().insert(read(data, format))); } function loadPending(df) { var accept, reject, pending = new Promise(function(a, r) { accept = a; reject = r; }); pending.requests = 0; pending.done = function() { if (--pending.requests === 0) { df.runAfter(function() { df._pending = null; try { df.run(); accept(df); } catch (err) { reject(err); } }); } } return (df._pending = pending); } function request$1(target, url, format) { var df = this, pending = df._pending || loadPending(df); pending.requests += 1; df.loader() .load(url, {context:'dataflow'}) .then( function(data) { df.ingest(target, data, format); }, function(error) { df.warn('Loading failed: ' + url, error); pending.done(); }) .then(pending.done) .catch(function(error) { df.warn(error); }); } /** * Represents a set of multiple pulses. Used as input for operators * that accept multiple pulses at a time. Contained pulses are * accessible via the public "pulses" array property. This pulse doe * not carry added, removed or modified tuples directly. However, * the visit method can be used to traverse all such tuples contained * in sub-pulses with a timestamp matching this parent multi-pulse. * @constructor * @param {Dataflow} dataflow - The backing dataflow instance. * @param {number} stamp - The timestamp. * @param {Array<Pulse>} pulses - The sub-pulses for this multi-pulse. */ function MultiPulse(dataflow, stamp, pulses, encode) { var p = this, c = 0, pulse, hash, i, n, f; this.dataflow = dataflow; this.stamp = stamp; this.fields = null; this.encode = encode || null; this.pulses = pulses; for (i=0, n=pulses.length; i<n; ++i) { pulse = pulses[i]; if (pulse.stamp !== stamp) continue; if (pulse.fields) { hash = p.fields || (p.fields = {}); for (f in pulse.fields) { hash[f] = 1; } } if (pulse.changed(p.ADD)) c |= p.ADD; if (pulse.changed(p.REM)) c |= p.REM; if (pulse.changed(p.MOD)) c |= p.MOD; } this.changes = c; } var prototype$5 = inherits(MultiPulse, Pulse); /** * Creates a new pulse based on the values of this pulse. * The dataflow, time stamp and field modification values are copied over. * @return {Pulse} */ prototype$5.fork = function() { if (arguments.length && (arguments[0] & Pulse.prototype.ALL)) { error('MultiPulse fork does not support tuple change sets.'); } return new Pulse(this.dataflow).init(this, 0); }; prototype$5.changed = function(flags) { return this.changes & flags; }; prototype$5.modified = function(_) { var p = this, fields = p.fields; return !(fields && (p.changes & p.MOD)) ? 0 : isArray(_) ? _.some(function(f) { return fields[f]; }) : fields[_]; }; prototype$5.filter = function() { error('MultiPulse does not support filtering.'); }; prototype$5.materialize = function() { error('MultiPulse does not support materialization.'); }; prototype$5.visit = function(flags, visitor) { var pulses = this.pulses, i, n; for (i=0, n=pulses.length; i<n; ++i) { if (pulses[i].stamp === this.stamp) { pulses[i].visit(flags, visitor); } } return this; }; /** * Runs the dataflow. This method will increment the current timestamp * and process all updated, pulsed and touched operators. When run for * the first time, all registered operators will be processed. If there * are pending data loading operations, this method will return immediately * without evaluating the dataflow. Instead, the dataflow will be * asynchronously invoked when data loading completes. To track when dataflow * evaluation completes, use the {@link runAsync} method instead. * @param {string} [encode] - The name of an encoding set to invoke during * propagation. This value is added to generated Pulse instances; * operators can then respond to (or ignore) this setting as appropriate. * This parameter can be used in conjunction with the Encode transform in * the vega-encode module. */ function run(encode) { if (!this._touched.length) { return 0; // nothing to do! } if (this._pending) { this.info('Awaiting requests, delaying dataflow run.'); return 0; } var df = this, count = 0, level = df.logLevel(), op, next, dt; df._pulse = new Pulse(df, ++df._clock, encode); if (level >= Info) { dt = Date.now(); df.debug('-- START PROPAGATION (' + df._clock + ') -----'); } // initialize queue, reset touched operators df._touched.forEach(function(op) { df._enqueue(op, true); }); df._touched = UniqueList(id); try { while (df._heap.size() > 0) { op = df._heap.pop(); // re-queue if rank changes if (op.rank !== op.qrank) { df._enqueue(op, true); continue; } // otherwise, evaluate the operator next = op.run(df._getPulse(op, encode)); if (level >= Debug) { df.debug(op.id, next === StopPropagation ? 'STOP' : next, op); } // propagate the pulse if (next !== StopPropagation) { df._pulse = next; if (op._targets) op._targets.forEach(function(op) { df._enqueue(op); }); } // increment visit counter ++count; } } catch (err) { df.error(err); } // reset pulse map df._pulses = {}; df._pulse = null; if (level >= Info) { dt = Date.now() - dt; df.info('> Pulse ' + df._clock + ': ' + count + ' operators; ' + dt + 'ms'); } // invoke callbacks queued via runAfter if (df._postrun.length) { var postrun = df._postrun; df._postrun = []; postrun.forEach(function(f) { try { f(df); } catch (err) { df.error(err); } }); } return count; } /** * Runs the dataflow and returns a Promise that resolves when the * propagation cycle completes. The standard run method may exit early * if there are pending data loading operations. In contrast, this * method returns a Promise to allow callers to receive notification * when dataflow evaluation completes. * @return {Promise} - A promise that resolves to this dataflow. */ function runAsync() { return this._pending || Promise.resolve(this.run()); } /** * Schedules a callback function to be invoked after the current pulse * propagation completes. If no propagation is currently occurring, * the function is invoked immediately. * @param {function(Dataflow)} callback - The callback function to run. * The callback will be invoked with this Dataflow instance as its * sole argument. */ function runAfter(callback) { if (this._pulse) { // pulse propagation is currently running, queue to run after this._postrun.push(callback); } else { // pulse propagation already complete, invoke immediately try { callback(this); } catch (err) { this.error(err); } } } /** * Enqueue an operator into the priority queue for evaluation. The operator * will be enqueued if it has no registered pulse for the current cycle, or if * the force argument is true. Upon enqueue, this method also sets the * operator's qrank to the current rank value. * @param {Operator} op - The operator to enqueue. * @param {boolean} [force] - A flag indicating if the operator should be * forceably added to the queue, even if it has already been previously * enqueued during the current pulse propagation. This is useful when the * dataflow graph is dynamically modified and the operator rank changes. */ function enqueue(op, force) { var p = !this._pulses[op.id]; if (p) this._pulses[op.id] = this._pulse; if (p || force) { op.qrank = op.rank; this._heap.push(op); } } /** * Provide a correct pulse for evaluating an operator. If the operator has an * explicit source operator, we will try to pull the pulse(s) from it. * If there is an array of source operators, we build a multi-pulse. * Otherwise, we return a current pulse with correct source data. * If the pulse is the pulse map has an explicit target set, we use that. * Else if the pulse on the upstream source operator is current, we use that. * Else we use the pulse from the pulse map, but copy the source tuple array. * @param {Operator} op - The operator for which to get an input pulse. * @param {string} [encode] - An (optional) encoding set name with which to * annotate the returned pulse. See {@link run} for more information. */ function getPulse(op, encode) { var s = op.source, stamp = this._clock, p; if (s && isArray(s)) { p = s.map(function(_) { return _.pulse; }); return new MultiPulse(this, stamp, p, encode); } else { s = s && s.pulse; p = this._pulses[op.id]; if (s && s !== StopPropagation) { if (s.stamp === stamp && p.target !== op) p = s; else p.source = s.source; } return p; } } function Heap(comparator) { this.cmp = comparator; this.nodes = []; } var prototype$6 = Heap.prototype; prototype$6.size = function() { return this.nodes.length; }; prototype$6.clear = function() { return (this.nodes = [], this); }; prototype$6.peek = function() { return this.nodes[0]; }; prototype$6.push = function(x) { var array = this.nodes; array.push(x); return siftdown(array, 0, array.length-1, this.cmp); }; prototype$6.pop = function() { var array = this.nodes, last = array.pop(), item; if (array.length) { item = array[0]; array[0] = last; siftup(array, 0, this.cmp); } else { item = last; } return item; }; prototype$6.replace = function(item) { var array = this.nodes, retval = array[0]; array[0] = item; siftup(array, 0, this.cmp); return retval; }; prototype$6.pushpop = function(item) { var array = this.nodes, ref = array[0]; if (array.length && this.cmp(ref, item) < 0) { array[0] = item; item = ref; siftup(array, 0, this.cmp); } return item; }; function siftdown(array, start, idx, cmp) { var item, parent, pidx; item = array[idx]; while (idx > start) { pidx = (idx - 1) >> 1; parent = array[pidx]; if (cmp(item, parent) < 0) { array[idx] = parent; idx = pidx; continue; } break; } return (array[idx] = item); } function siftup(array, idx, cmp) { var start = idx, end = array.length, item = array[idx], cidx = 2 * idx + 1, ridx; while (cidx < end) { ridx = cidx + 1; if (ridx < end && cmp(array[cidx], array[ridx]) >= 0) { cidx = ridx; } array[idx] = array[cidx]; idx = cidx; cidx = 2 * idx + 1; } array[idx] = item; return siftdown(array, start, idx, cmp); } /** * A dataflow graph for reactive processing of data streams. * @constructor */ function Dataflow() { this._log = logger(); this._clock = 0; this._rank = 0; this._loader = loader(); this._touched = UniqueList(id); this._pulses = {}; this._pulse = null; this._heap = new Heap(function(a, b) { return a.qrank - b.qrank; }); this._postrun = []; } var prototype = Dataflow.prototype; /** * The current timestamp of this dataflow. This value reflects the * timestamp of the previous dataflow run. The dataflow is initialized * with a stamp value of 0. The initial run of the dataflow will have * a timestap of 1, and so on. This value will match the * {@link Pulse.stamp} property. * @return {number} - The current timestamp value. */ prototype.stamp = function() { return this._clock; }; /** * Gets or sets the loader instance to use for data file loading. A * loader object must provide a "load" method for loading files and a * "sanitize" method for checking URL/filename validity. Both methods * should accept a URI and options hash as arguments, and return a Promise * that resolves to the loaded file contents or sanitized URL string, * respectively. * @param {object} _ - The loader instance to use. * @return {object|Dataflow} - If no arguments are provided, returns * the current loader instance. Otherwise returns this Dataflow instance. */ prototype.loader = function(_) { return arguments.length ? (this._loader = _, this) : this._loader; }; // OPERATOR REGISTRATION prototype.add = add; prototype.connect = connect; prototype.rank = rank; prototype.rerank = rerank; // OPERATOR UPDATES prototype.pulse = pulse; prototype.touch = touch; prototype.update = update; prototype.changeset = changeset; // DATA LOADING prototype.ingest = ingest$1; prototype.request = request$1; // EVENT HANDLING prototype.events = events; prototype.on = on; // PULSE PROPAGATION prototype.run = run; prototype.runAsync = runAsync; prototype.runAfter = runAfter; prototype._enqueue = enqueue; prototype._getPulse = getPulse; // LOGGING AND ERROR HANDLING function logMethod(method) { return function() { return this._log[method].apply(this, arguments); }; } /** * Logs a warning message. By default, logged messages are written to console * output. The message will only be logged if the current log level is high * enough to permit warning messages. */ prototype.warn = logMethod('warn'); /** * Logs a information message. By default, logged messages are written to * console output. The message will only be logged if the current log level is * high enough to permit information messages. */ prototype.info = logMethod('info'); /** * Logs a debug message. By default, logged messages are written to console * output. The message will only be logged if the current log level is high * enough to permit debug messages. */ prototype.debug = logMethod('debug'); /** * Get or set the current log level. If an argument is provided, it * will be used as the new log level. * @param {number} [level] - Should be one of None, Warn, Info * @return {number} - The current log level. */ prototype.logLevel = logMethod('level'); /** * Handle an error. By default, this method re-throws the input error. * This method can be overridden for custom error handling. */ prototype.error = function(err) { throw err; }; /** * Abstract class for operators that process data tuples. * Subclasses must provide a {@link transform} method for operator processing. * @constructor * @param {*} [init] - The initial value for this operator. * @param {object} [params] - The parameters for this operator. * @param {Operator} [source] - The operator from which to receive pulses. */ function Transform(init, params) { Operator.call(this, init, null, params); } var prototype$7 = inherits(Transform, Operator); /** * Overrides {@link Operator.evaluate} for transform operators. * Marshalls parameter values and then invokes {@link transform}. * @param {Pulse} pulse - the current dataflow pulse. * @return {Pulse} The output pulse (or StopPropagation). A falsy return value (including undefined) will let the input pulse pass through. */ prototype$7.evaluate = function(pulse) { var params = this.marshall(pulse.stamp), out = this.transform(params, pulse); params.clear(); return out; }; /** * Process incoming pulses. * Subclasses should override this method to implement transforms. * @param {Parameters} _ - The operator parameter values. * @param {Pulse} pulse - The current dataflow pulse. * @return {Pulse} The output pulse (or StopPropagation). A falsy return * value (including undefined) will let the input pulse pass through. */ prototype$7.transform = function() {}; var transforms = {}; var definitions = {}; function register(def, constructor) { var type = def.type; definition(type, def); transform(type, constructor); } function definition(type, def) { type = type && type.toLowerCase(); return arguments.length > 1 ? (definitions[type] = def, this) : definitions.hasOwnProperty(type) ? definitions[type] : null; } function transform(type, constructor) { return arguments.length > 1 ? (transforms[type] = constructor, this) : transforms.hasOwnProperty(type) ? transforms[type] : null; } function TupleStore(key) { this._key = key || '_id'; this._add = []; this._rem = []; this._ext = null; this._get = null; this._q = null; } var prototype$9 = TupleStore.prototype; prototype$9.add = function(v) { this._add.push(v); }; prototype$9.rem = function(v) { this._rem.push(v); }; prototype$9.values = function() { this._get = null; if (this._rem.length === 0) return this._add; var a = this._add, r = this._rem, k = this._key, n = a.length, m = r.length, x = Array(n - m), map = {}, i, j, v; // use unique key field to clear removed values for (i=0; i<m; ++i) { map[r[i][k]] = 1; } for (i=0, j=0; i<n; ++i) { if (map[(v = a[i])[k]]) { map[v[k]] = 0; } else { x[j++] = v; } } this._rem = []; return (this._add = x); }; // memoized statistics methods prototype$9.extent = function(get) { if (this._get !== get || !this._ext) { var v = this.values(), i = extentIndex(v, get); this._ext = [v[i[0]], v[i[1]]]; this._get = get; } return this._ext; }; prototype$9.argmin = function(get) { return this.extent(get)[0] || {}; }; prototype$9.argmax = function(get) { return this.extent(get)[1] || {}; }; prototype$9.min = function(get) { var m = this.extent(get)[0]; return m != null ? get(m) : +Infinity; }; prototype$9.max = function(get) { var m = this.extent(get)[1]; return m != null ? get(m) : -Infinity; }; prototype$9.quartile = function(get) { if (this._get !== get || !this._q) { this._q = quartiles(this.values(), get); this._get = get; } return this._q; }; prototype$9.q1 = function(get) { return this.quartile(get)[0]; }; prototype$9.q2 = function(get) { return this.quartile(get)[1]; }; prototype$9.q3 = function(get) { return this.quartile(get)[2]; }; prototype$9.ci = function(get) { if (this._get !== get || !this._ci) { this._ci = bootstrapCI(this.values(), 1000, 0.05, get); this._get = get; } return this._ci; }; prototype$9.ci0 = function(get) { return this.ci(get)[0]; }; prototype$9.ci1 = function(get) { return this.ci(get)[1]; }; var Aggregates = { 'values': measure({ name: 'values', init: 'cell.store = true;', set: 'cell.data.values()', idx: -1 }), 'count': measure({ name: 'count', set: 'cell.num' }), 'missing': measure({ name: 'missing', set: 'this.missing' }), 'valid': measure({ name: 'valid', set: 'this.valid' }), 'distinct': measure({ name: 'distinct', init: 'this.dmap = {}; this.distinct = 0;', add: 'this.dmap[v] = 1 + (this.dmap[v] || (++this.distinct, 0));', rem: 'if (!(--this.dmap[v])) --this.distinct;', set: 'this.distinct' }), 'sum': measure({ name: 'sum', init: 'this.sum = 0;', add: 'this.sum += v;', rem: 'this.sum -= v;', set: 'this.sum' }), 'mean': measure({ name: 'mean', init: 'this.mean = 0;', add: 'var d = v - this.mean; this.mean += d / this.valid;', rem: 'var d = v - this.mean; this.mean -= this.valid ? d / this.valid : this.mean;', set: 'this.mean' }), 'average': measure({ name: 'average', set: 'this.mean', req: ['mean'], idx: 1 }), 'variance': measure({ name: 'variance', init: 'this.dev = 0;', add: 'this.dev += d * (v - this.mean);', rem: 'this.dev -= d * (v - this.mean);', set: 'this.valid > 1 ? this.dev / (this.valid-1) : 0', req: ['mean'], idx: 1 }), 'variancep': measure({ name: 'variancep', set: 'this.valid > 1 ? this.dev / this.valid : 0', req: ['variance'], idx: 2 }), 'stdev': measure({ name: 'stdev', set: 'this.valid > 1 ? Math.sqrt(this.dev / (this.valid-1)) : 0', req: ['variance'], idx: 2 }), 'stdevp': measure({ name: 'stdevp', set: 'this.valid > 1 ? Math.sqrt(this.dev / this.valid) : 0', req: ['variance'], idx: 2 }), 'stderr': measure({ name: 'stderr', set: 'this.valid > 1 ? Math.sqrt(this.dev / (this.valid * (this.valid-1))) : 0', req: ['variance'], idx: 2 }), 'ci0': measure({ name: 'ci0', set: 'cell.data.ci0(this.get)', req: ['values'], idx: 3 }), 'ci1': measure({ name: 'ci1', set: 'cell.data.ci1(this.get)', req: ['values'], idx: 3 }), 'median': measure({ name: 'median', set: 'cell.data.q2(this.get)', req: ['values'], idx: 3 }), 'q1': measure({ name: 'q1', set: 'cell.data.q1(this.get)', req: ['values'], idx: 3 }), 'q3': measure({ name: 'q3', set: 'cell.data.q3(this.get)', req: ['values'], idx: 3 }), 'argmin': measure({ name: 'argmin', add: 'if (v < this.min) this.argmin = t;', rem: 'if (v <= this.min) this.argmin = null;', set: 'this.argmin || cell.data.argmin(this.get)', req: ['min'], str: ['values'], idx: 3 }), 'argmax': measure({ name: 'argmax', add: 'if (v > this.max) this.argmax = t;', rem: 'if (v >= this.max) this.argmax = null;', set: 'this.argmax || cell.data.argmax(this.get)', req: ['max'], str: ['values'], idx: 3 }), 'min': measure({ name: 'min', init: 'this.min = null;', add: 'if (v < this.min || this.min === null) this.min = v;', rem: 'if (v <= this.min) this.min = NaN;', set: 'this.min = (isNaN(this.min) ? cell.data.min(this.get) : this.min)', str: ['values'], idx: 4 }), 'max': measure({ name: 'max', init: 'this.max = null;', add: 'if (v > this.max || this.max === null) this.max = v;', rem: 'if (v >= this.max) this.max = NaN;', set: 'this.max = (isNaN(this.max) ? cell.data.max(this.get) : this.max)', str: ['values'], idx: 4 }) }; function createMeasure(op, name) { return Aggregates[op](name); } function measure(base) { return function(out) { var m = extend({init:'', add:'', rem:'', idx:0}, base); m.out = out || base.name; return m; }; } function compareIndex(a, b) { return a.idx - b.idx; } function resolve(agg, stream) { function collect(m, a) { function helper(r) { if (!m[r]) collect(m, m[r] = Aggregates[r]()); } if (a.req) a.req.forEach(helper); if (stream && a.str) a.str.forEach(helper); return m; } var map = agg.reduce( collect, agg.reduce(function(m, a) { return (m[a.name] = a, m); }, {}) ); var values = [], key; for (key in map) values.push(map[key]); return values.sort(compareIndex); } function compileMeasures(agg, field) { var get = field || identity$1, all = resolve(agg, true), // assume streaming removes may occur ctr = 'this.cell = cell; this.tuple = t; this.valid = 0; this.missing = 0;', add = 'if(v==null){this.missing++; return;} if(v!==v) return; ++this.valid;', rem = 'if(v==null){this.missing--; return;} if(v!==v) return; --this.valid;', set = 'var t = this.tuple; var cell = this.cell;'; all.forEach(function(a) { if (a.idx < 0) { ctr = a.init + ctr; add = a.add + add; rem = a.rem + rem; } else { ctr += a.init; add += a.add; rem += a.rem; } }); agg.slice().sort(compareIndex).forEach(function(a) { set += 't[\'' + a.out + '\']=' + a.set + ';'; }); set += 'return t;'; ctr = Function('cell', 't', ctr); ctr.prototype.add = Function('v', 't', add); ctr.prototype.rem = Function('v', 't', rem); ctr.prototype.set = Function(set); ctr.prototype.get = get; ctr.fields = agg.map(function(_) { return _.out; }); return ctr; } /** * Group-by aggregation operator. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<function(object): *>} params.groupby - An array of accessors to groupby. * @param {Array<function(object): *>} params.fields - An array of accessors to aggregate. * @param {Array<string>} params.ops - An array of strings indicating aggregation operations. * @param {Array<string>} [params.as] - An array of output field names for aggregated values. * @param {boolean} [params.drop=true] - A flag indicating if empty cells should be removed. */ function Aggregate(params) { Transform.call(this, null, params); this._adds = []; // array of added output tuples this._mods = []; // array of modified output tuples this._alen = 0; // number of active added tuples this._mlen = 0; // number of active modified tuples this._drop = true; // should empty aggregation cells be removed this._dims = []; // group-by dimension accessors this._dnames = []; // group-by dimension names this._measures = []; // collection of aggregation monoids this._countOnly = false; // flag indicating only count aggregation this._counts = null; // collection of count fields this._prev = null; // previous aggregation cells this._inputs = null; // array of dependent input tuple field names this._outputs = null; // array of output tuple field names } var prototype$8 = inherits(Aggregate, Transform); prototype$8.transform = function(_, pulse) { var aggr = this, out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), mod; this.stamp = out.stamp; if (this.value && ((mod = _.modified()) || pulse.modified(this._inputs))) { this._prev = this.value; this.value = mod ? this.init(_) : {}; pulse.visit(pulse.SOURCE, function(t) { aggr.add(t); }); } else { this.value = this.value || this.init(_); pulse.visit(pulse.REM, function(t) { aggr.rem(t); }); pulse.visit(pulse.ADD, function(t) { aggr.add(t); }); } // Indicate output fields and return aggregate tuples. out.modifies(this._outputs); aggr._drop = _.drop !== false; return aggr.changes(out); }; prototype$8.init = function(_) { // initialize input and output fields var inputs = (this._inputs = []), outputs = (this._outputs = []), inputMap = {}; function inputVisit(get) { var fields = get.fields, i = 0, n = fields.length, f; for (; i<n; ++i) { if (!inputMap[f=fields[i]]) { inputMap[f] = 1; inputs.push(f); } } } // initialize group-by dimensions this._dims = array$1(_.groupby); this._dnames = this._dims.map(function(d) { var dname = accessorName(d) return (inputVisit(d), outputs.push(dname), dname); }); this.cellkey = _.key ? _.key : this._dims.length === 0 ? function() { return ''; } : this._dims.length === 1 ? this._dims[0] : cellkey; // initialize aggregate measures this._countOnly = true; this._counts = []; this._measures = []; var fields = _.fields || [null], ops = _.ops || ['count'], as = _.as || [], n = fields.length, map = {}, field, op, m, mname, outname, i; if (n !== ops.length) { error('Unmatched number of fields and aggregate ops.'); } for (i=0; i<n; ++i) { field = fields[i]; op = ops[i]; if (field == null && op !== 'count') { error('Null aggregate field specified.'); } mname = accessorName(field); outname = measureName(op, mname, as[i]); outputs.push(outname); if (op === 'count') { this._counts.push(outname); continue; } m = map[mname]; if (!m) { inputVisit(field); m = (map[mname] = []); m.field = field; this._measures.push(m); } if (op !== 'count') this._countOnly = false; m.push(createMeasure(op, outname)); } this._measures = this._measures.map(function(m) { return compileMeasures(m, m.field); }); return {}; // aggregation cells (this.value) }; function measureName(op, mname, as) { return as || (op + (!mname ? '' : '_' + mname)); } // -- Cell Management ----- function cellkey(x) { var d = this._dims, n = d.length, i, k = String(d[0](x)); for (i=1; i<n; ++i) { k += '|' + d[i](x); } return k; } prototype$8.cellkey = cellkey; prototype$8.cell = function(key, t) { var cell = this.value[key]; if (!cell) { cell = this.value[key] = this.newcell(key, t); this._adds[this._alen++] = cell; } else if (cell.num === 0 && this._drop && cell.stamp < this.stamp) { cell.stamp = this.stamp; this._adds[this._alen++] = cell; } else if (cell.stamp < this.stamp) { cell.stamp = this.stamp; this._mods[this._mlen++] = cell; } return cell; }; prototype$8.newcell = function(key, t) { var cell = { key: key, num: 0, agg: null, tuple: this.newtuple(t, this._prev && this._prev[key]), stamp: this.stamp, store: false }; if (!this._countOnly) { var measures = this._measures, n = measures.length, i; cell.agg = Array(n); for (i=0; i<n; ++i) { cell.agg[i] = new measures[i](cell, cell.tuple); } } if (cell.store) { cell.data = new TupleStore(); } return cell; }; prototype$8.newtuple = function(t, p) { var names = this._dnames, dims = this._dims, x = {}, i, n; for (i=0, n=dims.length; i<n; ++i) { x[names[i]] = dims[i](t); } return p ? replace(p.tuple, x) : ingest(x); }; // -- Process Tuples ----- prototype$8.add = function(t) { var key = this.cellkey(t), cell = this.cell(key, t), agg, i, n; cell.num += 1; if (this._countOnly) return; if (cell.store) cell.data.add(t); agg = cell.agg; for (i=0, n=agg.length; i<n; ++i) { agg[i].add(agg[i].get(t), t); } }; prototype$8.rem = function(t) { var key = this.cellkey(t), cell = this.cell(key, t), agg, i, n; cell.num -= 1; if (this._countOnly) return; if (cell.store) cell.data.rem(t); agg = cell.agg; for (i=0, n=agg.length; i<n; ++i) { agg[i].rem(agg[i].get(t), t); } }; prototype$8.celltuple = function(cell) { var tuple = cell.tuple, counts = this._counts, agg, i, n; // consolidate stored values if (cell.store) { cell.data.values(); } // update tuple properties for (i=0, n=counts.length; i<n; ++i) { tuple[counts[i]] = cell.num; } if (!this._countOnly) { agg = cell.agg; for (i=0, n=agg.length; i<n; ++i) { agg[i].set(); } } return tuple; }; prototype$8.changes = function(out) { var adds = this._adds, mods = this._mods, prev = this._prev, drop = this._drop, add = out.add, rem = out.rem, mod = out.mod, cell, key, i, n; if (prev) for (key in prev) { rem.push(prev[key].tuple); } for (i=0, n=this._alen; i<n; ++i) { add.push(this.celltuple(adds[i])); adds[i] = null; // for garbage collection } for (i=0, n=this._mlen; i<n; ++i) { cell = mods[i]; (cell.num === 0 && drop ? rem : mod).push(this.celltuple(cell)); mods[i] = null; // for garbage collection } this._alen = this._mlen = 0; // reset list of active cells this._prev = null; return out; }; /** * Generates a binning function for discretizing data. * @constructor * @param {object} params - The parameters for this operator. The * provided values should be valid options for the {@link bin} function. * @param {function(object): *} params.field - The data field to bin. */ function Bin(params) { Transform.call(this, null, params); } var prototype$10 = inherits(Bin, Transform); prototype$10.transform = function(_, pulse) { var bins = this._bins(_), step = bins.step, as = _.as || ['bin0', 'bin1'], b0 = as[0], b1 = as[1], flag = _.modified() ? (pulse = pulse.reflow(true), pulse.SOURCE) : pulse.modified(accessorFields(_.field)) ? pulse.ADD_MOD : pulse.ADD; pulse.visit(flag, function(t) { t[b1] = (t[b0] = bins(t)) + step; }); return pulse.modifies(as); }; prototype$10._bins = function(_) { if (this.value && !_.modified()) { return this.value; } var field = _.field, bins = bin$1(_), start = bins.start, step = bins.step; var f = function(t) { var v = field(t); return v == null ? null : start + step * Math.floor((+v - start) / step); }; f.step = step; return this.value = accessor( f, accessorFields(field), _.name || 'bin_' + accessorName(field) ); }; /** * Collects all data tuples that pass through this operator. * @constructor * @param {object} params - The parameters for this operator. * @param {function(*,*): number} [params.sort] - An optional * comparator function for additionally sorting the collected tuples. */ function Collect(params) { Transform.call(this, [], params); } var prototype$11 = inherits(Collect, Transform); prototype$11.transform = function(_, pulse) { var out = pulse.fork(pulse.ALL), add = pulse.changed(pulse.ADD), mod = pulse.changed(), sort = _.sort, data = this.value, push = function(t) { data.push(t); }, n = 0, map; if (out.rem.length) { // build id map and filter data array map = {}; out.visit(out.REM, function(t) { map[t._id] = 1; ++n; }); data = data.filter(function(t) { return !map[t._id]; }); } if (sort) { // if sort criteria change, re-sort the full data array if (_.modified('sort') || pulse.modified(sort.fields)) { data.sort(sort); mod = true; } // if added tuples, sort them in place and then merge if (add) { data = merge$1(sort, data, out.add.sort(sort)); } } else if (add) { // no sort, so simply add new tuples out.visit(out.ADD, push); } this.modified(mod); this.value = out.source = data; return out; }; /** * Generates a comparator function. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<string>} params.fields - The fields to compare. * @param {Array<string>} [params.orders] - The sort orders. * Each entry should be one of "ascending" (default) or "descending". */ function Compare(params) { Operator.call(this, null, update$1, params); } inherits(Compare, Operator); function update$1(_) { return (this.value && !_.modified()) ? this.value : compare(_.fields, _.orders); } /** * Count regexp-defined pattern occurrences in a text field. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - An accessor for the text field. * @param {string} [params.pattern] - RegExp string defining the text pattern. * @param {string} [params.case] - One of 'lower', 'upper' or null (mixed) case. * @param {string} [params.stopwords] - RegExp string of words to ignore. */ function CountPattern(params) { Transform.call(this, null, params); } function tokenize(text, tcase, match) { switch (tcase) { case 'upper': text = text.toUpperCase(); break; case 'lower': text = text.toLowerCase(); break; } return text.match(match); } var prototype$12 = inherits(CountPattern, Transform); prototype$12.transform = function(_, pulse) { function process(update) { return function(tuple) { var tokens = tokenize(get(tuple), _.case, match) || [], t; for (var i=0, n=tokens.length; i<n; ++i) { if (!stop.test(t = tokens[i])) update(t); } }; } var init = this._parameterCheck(_, pulse), counts = this._counts, match = this._match, stop = this._stop, get = _.field, as = _.as || ['text', 'count'], add = process(function(t) { counts[t] = 1 + (counts[t] || 0); }), rem = process(function(t) { counts[t] -= 1; }); if (init) { pulse.visit(pulse.SOURCE, add); } else { pulse.visit(pulse.ADD, add); pulse.visit(pulse.REM, rem); } return this._finish(pulse, as); // generate output tuples }; prototype$12._parameterCheck = function(_, pulse) { var init = false; if (_.modified('stopwords') || !this._stop) { this._stop = new RegExp('^' + (_.stopwords || '') + '$', 'i'); init = true; } if (_.modified('pattern') || !this._match) { this._match = new RegExp((_.pattern || '[\\w\']+'), 'g'); init = true; } if (_.modified('field') || pulse.modified(_.field.fields)) { init = true; } if (init) this._counts = {}; return init; } prototype$12._finish = function(pulse, as) { var counts = this._counts, tuples = this._tuples || (this._tuples = {}), text = as[0], count = as[1], out = pulse.fork(), w, t, c; for (w in counts) { t = tuples[w]; c = counts[w] || 0; if (!t && c) { tuples[w] = (t = ingest({})); t[text] = w; t[count] = c; out.add.push(t); } else if (c === 0) { if (t) out.rem.push(t); counts[w] = null; tuples[w] = null; } else if (t[count] !== c) { t[count] = c; out.mod.push(t); } } return out.modifies(as); }; /** * Perform a cross-product of a tuple stream with itself. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object):boolean} [params.filter] - An optional filter * function for selectively including tuples in the cross product. * @param {Array<string>} [params.as] - The names of the output fields. */ function Cross(params) { Transform.call(this, null, params); } var prototype$13 = inherits(Cross, Transform); prototype$13.transform = function(_, pulse) { var out = pulse.fork(pulse.NO_SOURCE), data = this.value, as = _.as || ['a', 'b'], a = as[0], b = as[1], reset = !data || pulse.changed(pulse.ADD_REM) || _.modified('as') || _.modified('filter'); if (reset) { if (data) out.rem = data; out.add = this.value = cross(pulse.source, a, b, _.filter || truthy); } else { out.mod = data; } return out.source = this.value, out.modifies(as); }; function cross(input, a, b, filter) { var data = [], t = {}, n = input.length, i = 0, j, left; for (; i<n; ++i) { t[a] = left = input[i]; for (j=0; j<n; ++j) { t[b] = input[j]; if (filter(t)) { data.push(ingest(t)); t = {}; t[a] = left; } } } return data; } var Distributions = { kde: randomKDE, mixture: randomMixture, normal: randomNormal, uniform: randomUniform }; var DISTRIBUTIONS = 'distributions'; var FUNCTION = 'function'; var FIELD = 'field'; /** * Parse a parameter object for a probability distribution. * @param {object} def - The distribution parameter object. * @param {function():Array<object>} - A method for requesting * source data. Used for distributions (such as KDE) that * require sample data points. This method will only be * invoked if the 'from' parameter for a target data source * is not provided. Typically this method returns backing * source data for a Pulse object. * @return {object} - The output distribution object. */ function parse$1(def, data) { var func = def[FUNCTION]; if (!Distributions.hasOwnProperty(func)) { error('Unknown distribution function: ' + func); } var d = Distributions[func](); for (var name in def) { // if data field, extract values if (name === FIELD) { d.data((def.from || data()).map(def[name])); } // if distribution mixture, recurse to parse each definition else if (name === DISTRIBUTIONS) { d[name](def[name].map(function(_) { return parse$1(_, data); })); } // otherwise, simply set the parameter else if (typeof d[name] === FUNCTION) { d[name](def[name]); } } return d; } /** * Grid sample points for a probability density. Given a distribution and * a sampling extent, will generate points suitable for plotting either * PDF (probability density function) or CDF (cumulative distribution * function) curves. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.distribution - The probability distribution. This * is an object parameter dependent on the distribution type. * @param {string} [params.method='pdf'] - The distribution method to sample. * One of 'pdf' or 'cdf'. * @param {Array<number>} [params.extent] - The [min, max] extent over which * to sample the distribution. This argument is required in most cases, but * can be omitted if the distribution (e.g., 'kde') supports a 'data' method * that returns numerical sample points from which the extent can be deduced. * @param {number} [params.steps=100] - The number of sampling steps. */ function Density(params) { Transform.call(this, null, params); } var prototype$14 = inherits(Density, Transform); prototype$14.transform = function(_, pulse) { var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); if (!this.value || pulse.changed() || _.modified()) { var dist = parse$1(_.distribution, source(pulse)), method = _.method || 'pdf'; if (method !== 'pdf' && method !== 'cdf') { error('Invalid density method: ' + method); } if (!_.extent && !dist.data) { error('Missing density extent parameter.'); } method = dist[method]; var as = _.as || ['value', 'density'], domain = _.extent || extent(dist.data()), step = (domain[1] - domain[0]) / (_.steps || 100), values = range(domain[0], domain[1] + step/2, step) .map(function(v) { var tuple = {}; tuple[as[0]] = v; tuple[as[1]] = method(v); return ingest(tuple); }); if (this.value) out.rem = this.value; this.value = out.add = out.source = values; } return out; }; function source(pulse) { return function() { return pulse.materialize(pulse.SOURCE).source; }; } /** * Computes extents (min/max) for a data field. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The field over which to compute extends. */ function Extent(params) { Transform.call(this, [+Infinity, -Infinity], params); } var prototype$15 = inherits(Extent, Transform); prototype$15.transform = function(_, pulse) { var extent = this.value, field = _.field, min = extent[0], max = extent[1], flag = pulse.ADD, mod; mod = pulse.changed() || pulse.modified(field.fields) || _.modified('field'); if (mod) { flag = pulse.SOURCE; min = +Infinity; max = -Infinity; } pulse.visit(flag, function(t) { var v = field(t); if (v < min) min = v; if (v > max) max = v; }); this.value = [min, max]; }; /** * Provides a bridge between a parent transform and a target subflow that * consumes only a subset of the tuples that pass through the parent. * @constructor * @param {Pulse} pulse - A pulse to use as the value of this operator. * @param {Transform} parent - The parent transform (typically a Facet instance). * @param {Transform} target - A transform that receives the subflow of tuples. */ function Subflow(pulse, parent) { Operator.call(this, pulse); this.parent = parent; } var prototype$17 = inherits(Subflow, Operator); prototype$17.connect = function(target) { this.targets().add(target); return (target.source = this); }; /** * Add an 'add' tuple to the subflow pulse. * @param {Tuple} t - The tuple being added. */ prototype$17.add = function(t) { this.value.add.push(t); }; /** * Add a 'rem' tuple to the subflow pulse. * @param {Tuple} t - The tuple being removed. */ prototype$17.rem = function(t) { this.value.rem.push(t); }; /** * Add a 'mod' tuple to the subflow pulse. * @param {Tuple} t - The tuple being modified. */ prototype$17.mod = function(t) { this.value.mod.push(t); }; /** * Re-initialize this operator's pulse value. * @param {Pulse} pulse - The pulse to copy from. * @see Pulse.init */ prototype$17.init = function(pulse) { this.value.init(pulse, pulse.NO_SOURCE); }; /** * Evaluate this operator. This method overrides the * default behavior to simply return the contained pulse value. * @return {Pulse} */ prototype$17.evaluate = function() { // assert: this.value.stamp === pulse.stamp return this.value; }; /** * Facets a dataflow into a set of subflows based on a key. * @constructor * @param {object} params - The parameters for this operator. * @param {function(Dataflow, string): Operator} params.subflow - A function * that generates a subflow of operators and returns its root operator. * @param {function(object): *} params.key - The key field to facet by. */ function Facet(params) { Transform.call(this, {}, params); this._keys = {}; // cache previously calculated key values this._count = 0; // count of subflows // keep track of active subflows, use as targets array for listeners // this allows us to limit propagation to only updated subflows var a = this._targets = []; a.active = 0; a.forEach = function(f) { for (var i=0, n=a.active; i<n; ++i) f(a[i], i, a); }; } var prototype$16 = inherits(Facet, Transform); prototype$16.activate = function(flow) { this._targets[this._targets.active++] = flow; }; prototype$16.subflow = function(key, flow, pulse, parent) { var flows = this.value, sf = flows.hasOwnProperty(key) && flows[key], df, p; if (!sf) { p = parent || (p = this._group[key]) && p.tuple; df = pulse.dataflow; sf = df.add(new Subflow(pulse.fork(pulse.NO_SOURCE), this)) .connect(flow(df, key, this._count++, p)); flows[key] = sf; this.activate(sf); } else if (sf.value.stamp < pulse.stamp) { sf.init(pulse); this.activate(sf); } return sf; }; prototype$16.transform = function(_, pulse) { var self = this, key = _.key, flow = _.subflow, cache = this._keys, rekey = _.modified('key'); function subflow(key) { return self.subflow(key, flow, pulse); } this._group = _.group || {}; this._targets.active = 0; // reset list of active subflows pulse.visit(pulse.ADD, function(t) { subflow(cache[t._id] = key(t)).add(t); }); pulse.visit(pulse.REM, function(t) { var k = cache[t._id]; cache[t._id] = null; subflow(k).rem(t); }); if (rekey || pulse.modified(key.fields)) { pulse.visit(pulse.MOD, function(t) { var k0 = cache[t._id], k1 = key(t); if (k0 === k1) { subflow(k1).mod(t); } else { cache[t._id] = k1; subflow(k0).rem(t); subflow(k1).add(t); } }); } else if (pulse.changed(pulse.MOD)) { pulse.visit(pulse.MOD, function(t) { subflow(cache[t._id]).mod(t); }); } if (rekey) { pulse.visit(pulse.REFLOW, function(t) { var k0 = cache[t._id], k1 = key(t); if (k0 !== k1) { cache[t._id] = k1; subflow(k0).rem(t); subflow(k1).add(t); } }); } return pulse; }; /** * Generates one or more field accessor functions. * If the 'name' parameter is an array, an array of field accessors * will be created and the 'as' parameter will be ignored. * @constructor * @param {object} params - The parameters for this operator. * @param {string} params.name - The field name(s) to access. * @param {string} params.as - The accessor function name. */ function Field(params) { Operator.call(this, null, update$2, params); } inherits(Field, Operator); function update$2(_) { return (this.value && !_.modified()) ? this.value : isArray(_.name) ? array$1(_.name).map(function(f) { return field(f); }) : field(_.name, _.as); } /** * Filters data tuples according to a predicate function. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.expr - The predicate expression function * that determines a tuple's filter status. Truthy values pass the filter. */ function Filter(params) { Transform.call(this, {}, params); } var prototype$18 = inherits(Filter, Transform); prototype$18.transform = function(_, pulse) { var test = _.expr, cache = this.value, // cache ids of filtered tuples output = pulse.fork(), add = output.add, rem = output.rem, mod = output.mod, isMod = true; pulse.visit(pulse.REM, function(x) { if (!cache[x._id]) rem.push(x); else cache[x._id] = 0; }); pulse.visit(pulse.ADD, function(x) { if (test(x, _)) add.push(x); else cache[x._id] = 1; }); function revisit(x) { var b = test(x, _), s = cache[x._id]; if (b && s) { cache[x._id] = 0; add.push(x); } else if (!b && !s) { cache[x._id] = 1; rem.push(x); } else if (isMod && b && !s) { mod.push(x); } } pulse.visit(pulse.MOD, revisit); if (_.modified()) { isMod = false; pulse.visit(pulse.REFLOW, revisit); } return output; }; /** * Folds one more tuple fields into multiple tuples in which the field * name and values are available under new 'key' and 'value' fields. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.fields - An array of field accessors * for the tuple fields that should be folded. */ function Fold(params) { Transform.call(this, {}, params); } var prototype$19 = inherits(Fold, Transform); function keyFunction(f) { return f.fields.join('|'); } prototype$19.transform = function(_, pulse) { var cache = this.value, reset = _.modified('fields'), fields = _.fields, as = _.as || ['key', 'value'], key = as[0], value = as[1], keys = fields.map(keyFunction), n = fields.length, stamp = pulse.stamp, out = pulse.fork(pulse.NO_SOURCE), i = 0, mask = 0, id; function add(t) { var f = (cache[t._id] = Array(n)); // create cache of folded tuples for (var i=0, ft; i<n; ++i) { // for each key, derive folds ft = (f[i] = derive(t)); ft[key] = keys[i]; ft[value] = fields[i](t); out.add.push(ft); } } function mod(t) { var f = cache[t._id]; // get cache of folded tuples for (var i=0, ft; i<n; ++i) { // for each key, rederive folds if (!(mask & (1 << i))) continue; // field is unchanged ft = rederive(t, f[i], stamp); ft[key] = keys[i]; ft[value] = fields[i](t); out.mod.push(ft); } } if (reset) { // on reset, remove all folded tuples and clear cache for (id in cache) out.rem.push.apply(out.rem, cache[id]); cache = this.value = {}; pulse.visit(pulse.SOURCE, add); } else { pulse.visit(pulse.ADD, add); for (; i<n; ++i) { if (pulse.modified(fields[i].fields)) mask |= (1 << i); } if (mask) pulse.visit(pulse.MOD, mod); pulse.visit(pulse.REM, function(t) { out.rem.push.apply(out.rem, cache[t._id]); cache[t._id] = null; }); } return out.modifies(as); }; /** * Invokes a function for each data tuple and saves the results as a new field. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.expr - The formula function to invoke for each tuple. * @param {string} params.as - The field name under which to save the result. */ function Formula(params) { Transform.call(this, null, params); } var prototype$20 = inherits(Formula, Transform); prototype$20.transform = function(_, pulse) { var func = _.expr, as = _.as, mod; function set(t) { t[as] = func(t, _); } if (_.modified()) { // parameters updated, need to reflow pulse = pulse.materialize().reflow(true).visit(pulse.SOURCE, set); } else { mod = pulse.modified(func.fields); pulse.visit(mod ? pulse.ADD_MOD : pulse.ADD, set); } return pulse.modifies(as); }; /** * Generates data tuples using a provided generator function. * @constructor * @param {object} params - The parameters for this operator. * @param {function(Parameters): object} params.generator - A tuple generator * function. This function is given the operator parameters as input. * Changes to any additional parameters will not trigger re-calculation * of previously generated tuples. Only future tuples are affected. * @param {number} params.size - The number of tuples to produce. */ function Generate(params) { Transform.call(this, [], params); } var prototype$21 = inherits(Generate, Transform); prototype$21.transform = function(_, pulse) { var data = this.value, out = pulse.fork(pulse.ALL), num = _.size - data.length, gen = _.generator, add, rem, t; if (num > 0) { // need more tuples, generate and add for (add=[]; --num >= 0;) { add.push(t = ingest(gen(_))); data.push(t); } out.add = out.add.length ? out.materialize(out.ADD).add.concat(add) : add; } else { // need fewer tuples, remove rem = data.slice(0, -num); out.rem = out.rem.length ? out.materialize(out.REM).rem.concat(rem) : rem; data = data.slice(-num); } out.source = this.value = data; return out; }; var Methods = { value: 'value', median: median, mean: mean, min: min, max: max }; var Empty = []; /** * Impute missing values. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to impute. * @param {Array<function(object): *>} [params.groupby] - An array of * accessors to determine series within which to perform imputation. * @param {Array<function(object): *>} [params.orderby] - An array of * accessors to determine the ordering within a series. * @param {string} [method='value'] - The imputation method to use. One of * 'value', 'mean', 'median', 'max', 'min'. * @param {*} [value=0] - The constant value to use for imputation * when using method 'value'. */ function Impute(params) { Transform.call(this, [], params); } var prototype$22 = inherits(Impute, Transform); function getValue(_) { var m = _.method || Methods.value, v; if (Methods[m] == null) { error('Unrecognized imputation method: ' + m); } else if (m === Methods.value) { v = _.value !== undefined ? _.value : 0; return function() { return v; }; } else { return Methods[m]; } } function getField(_) { var f = _.field; return function(t) { return t ? f(t) : NaN; }; } prototype$22.transform = function(_, pulse) { var out = pulse.fork(pulse.ALL), impute = getValue(_), field = getField(_), fName = accessorName(_.field), gNames = _.groupby.map(accessorName), oNames = _.orderby.map(accessorName), groups = partition(pulse.source, _.groupby, _.orderby), curr = [], prev = this.value, m = groups.domain.length, group, value, gVals, oVals, g, i, j, l, n, t; for (g=0, l=groups.length; g<l; ++g) { group = groups[g]; gVals = group.values; value = NaN; // add tuples for missing values for (j=0; j<m; ++j) { if (group[j] != null) continue; oVals = groups.domain[j]; t = {_impute: true}; for (i=0, n=gVals.length; i<n; ++i) t[gNames[i]] = gVals[i]; for (i=0, n=oVals.length; i<n; ++i) t[oNames[i]] = oVals[i]; t[fName] = isNaN(value) ? (value = impute(group, field)) : value; curr.push(ingest(t)); } } // update pulse with imputed tuples if (curr.length) out.add = out.materialize(out.ADD).add.concat(curr); if (prev.length) out.rem = out.materialize(out.REM).rem.concat(prev); this.value = curr; return out; }; function partition(data, groupby, orderby) { var get = function(f) { return f(t); }, groups = [], domain = [], oMap = {}, oVals, oKey, gMap = {}, gVals, gKey, group, i, j, n, t; for (i=0, n=data.length; i<n; ++i) { t = data[i]; oKey = (oVals = orderby.map(get)) + ''; j = oMap[oKey] || (oMap[oKey] = domain.push(oVals)); gKey = (gVals = groupby ? groupby.map(get) : Empty) + ''; if (!(group = gMap[gKey])) { group = (gMap[gKey] = []); groups.push(group); group.values = gVals; } group[j-1] = t; } return (groups.domain = domain, groups); } /** * Generates a key function. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<string>} params.fields - The field name(s) for the key function. */ function Key(params) { Operator.call(this, null, update$3, params); } inherits(Key, Operator); function update$3(_) { return (this.value && !_.modified()) ? this.value : key(_.fields); } /** * Extend tuples by joining them with values from a lookup table. * @constructor * @param {object} params - The parameters for this operator. * @param {Map} params.index - The lookup table map. * @param {Array<function(object): *} params.fields - The fields to lookup. * @param {Array<string>} params.as - Output field names for each lookup value. * @param {*} [params.default] - A default value to use if lookup fails. */ function Lookup(params) { Transform.call(this, {}, params); } var prototype$23 = inherits(Lookup, Transform); function get$1(index, key) { return index.hasOwnProperty(key) ? index[key] : null; } prototype$23.transform = function(_, pulse) { var out = pulse, as = _.as, keys = _.fields, index = _.index, defaultValue = _.default==null ? null : _.default, reset = _.modified(), flag = pulse.ADD, set, key, field, mods; if (keys.length === 1) { key = keys[0]; field = as[0]; set = function(t) { var v = get$1(index, key(t)); t[field] = v==null ? defaultValue : v; }; } else { set = function(t) { for (var i=0, n=keys.length, v; i<n; ++i) { v = get$1(index, keys[i](t)); t[as[i]] = v==null ? defaultValue : v; } }; } if (reset) { flag = pulse.SOURCE; out = pulse.reflow(true); } else { mods = keys.some(function(k) { return pulse.modified(k.fields); }); flag |= (mods ? pulse.MOD : 0); } pulse.visit(flag, set); return out.modifies(as); }; /** * Computes global min/max extents over a collection of extents. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<Array<number>>} params.extents - The input extents. */ function MultiExtent(params) { Operator.call(this, null, update$4, params); } inherits(MultiExtent, Operator); function update$4(_) { if (this.value && !_.modified()) { return this.value; } var min = +Infinity, max = -Infinity, ext = _.extents, i, n, e; for (i=0, n=ext.length; i<n; ++i) { e = ext[i]; if (e[0] < min) min = e[0]; if (e[1] > max) max = e[1]; } return [min, max]; } /** * Merge a collection of value arrays. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<Array<*>>} params.values - The input value arrrays. */ function MultiValues(params) { Operator.call(this, null, update$5, params); } inherits(MultiValues, Operator); function update$5(_) { return (this.value && !_.modified()) ? this.value : _.values.reduce(function(data, _) { return data.concat(_); }, []); } /** * Operator whose value is simply its parameter hash. This operator is * useful for enabling reactive updates to values of nested objects. * @constructor * @param {object} params - The parameters for this operator. */ function Params(params) { Transform.call(this, null, params); } inherits(Params, Transform); Params.prototype.transform = function(_, pulse) { this.modified(_.modified()); this.value = _; return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); // do not pass tuples }; /** * Partitions pre-faceted data into tuple subflows. * @constructor * @param {object} params - The parameters for this operator. * @param {function(Dataflow, string): Operator} params.subflow - A function * that generates a subflow of operators and returns its root operator. * @param {function(object): Array<object>} params.field - The field * accessor for an array of subflow tuple objects. */ function PreFacet(params) { Facet.call(this, params); } var prototype$24 = inherits(PreFacet, Facet); prototype$24.transform = function(_, pulse) { var self = this, flow = _.subflow, field = _.field; if (_.modified('field') || field && pulse.modified(field.fields)) { error('PreFacet does not support field modification.'); } this._targets.active = 0; // reset list of active subflows pulse.visit(pulse.ADD, function(t) { var sf = self.subflow(t._id, flow, pulse, t); field ? field(t).forEach(function(_) { sf.add(ingest(_)); }) : sf.add(t); }); pulse.visit(pulse.REM, function(t) { var sf = self.subflow(t._id, flow, pulse, t); field ? field(t).forEach(function(_) { sf.rem(_); }) : sf.rem(t); }); return pulse; }; /** * Generates data tuples for a specified range of numbers. * @constructor * @param {object} params - The parameters for this operator. * @param {number} params.start - The first number in the range. * @param {number} params.stop - The last number (exclusive) in the range. * @param {number} [params.step=1] - The step size between numbers in the range. */ function Range(params) { Transform.call(this, [], params); } var prototype$25 = inherits(Range, Transform); prototype$25.transform = function(_, pulse) { if (!_.modified()) return; var out = pulse.materialize().fork(pulse.MOD); out.rem = pulse.rem.concat(this.value); out.source = this.value = range(_.start, _.stop, _.step).map(ingest); out.add = pulse.add.concat(this.value); return out; }; /** * Compute rank order scores for tuples. The tuples are assumed to have been * sorted in the desired rank order by an upstream data source. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - An accessor for the field to rank. * @param {boolean} params.normalize - Boolean flag for normalizing rank values. * If true, the integer rank scores are normalized to range [0, 1]. */ function Rank(params) { Transform.call(this, null, params); } var prototype$26 = inherits(Rank, Transform); prototype$26.transform = function(_, pulse) { if (!pulse.source) { error('Rank transform requires an upstream data source.'); } var norm = _.normalize, field = _.field, as = _.as || 'rank', ranks = {}, n = -1, rank; if (field) { // If we have a field accessor, first compile distinct keys. pulse.visit(pulse.SOURCE, function(t) { var v = field(t); if (ranks[v] == null) ranks[v] = ++n; }); pulse.visit(pulse.SOURCE, norm && --n ? function(t) { t[as] = ranks[field(t)] / n; } : function(t) { t[as] = ranks[field(t)]; } ); } else { n += pulse.source.length; rank = -1; // Otherwise rank all the tuples together. pulse.visit(pulse.SOURCE, norm && n ? function(t) { t[as] = ++rank / n; } : function(t) { t[as] = ++rank; } ); } return pulse.reflow(_.modified()).modifies(as); }; /** * Relays a data stream between data processing pipelines. * If the derive parameter is set, this transform will create derived * copies of observed tuples. This provides derived data streams in which * modifications to the tuples do not pollute an upstream data source. * @param {object} params - The parameters for this operator. * @param {number} [params.derive=false] - Boolean flag indicating if * the transform should make derived copies of incoming tuples. * @constructor */ function Relay(params) { Transform.call(this, null, params); } var prototype$27 = inherits(Relay, Transform); prototype$27.transform = function(_, pulse) { var out, lut = this.value || (out = pulse = pulse.addAll(), this.value = {}); if (_.derive) { out = pulse.fork(); pulse.visit(pulse.ADD, function(t) { var dt = derive(t); lut[t._id] = dt; out.add.push(dt); }); pulse.visit(pulse.MOD, function(t) { out.mod.push(rederive(t, lut[t._id])); }); pulse.visit(pulse.REM, function(t) { out.rem.push(lut[t._id]); lut[t._id] = null; }); } return out; }; /** * Samples tuples passing through this operator. * Uses reservoir sampling to maintain a representative sample. * @constructor * @param {object} params - The parameters for this operator. * @param {number} [params.size=1000] - The maximum number of samples. */ function Sample(params) { Transform.call(this, [], params); this.count = 0; } var prototype$28 = inherits(Sample, Transform); prototype$28.transform = function(_, pulse) { var out = pulse.fork(), mod = _.modified('size'), num = _.size, res = this.value, cnt = this.count, cap = 0, map = res.reduce(function(m, t) { return (m[t._id] = 1, m); }, {}); // sample reservoir update function function update(t) { var p, idx; if (res.length < num) { res.push(t); } else { idx = ~~(cnt * Math.random()); if (idx < res.length && idx >= cap) { p = res[idx]; if (map[p._id]) out.rem.push(p); // eviction res[idx] = t; } } ++cnt; } if (pulse.rem.length) { // find all tuples that should be removed, add to output pulse.visit(pulse.REM, function(t) { if (map[t._id]) { map[t._id] = -1; out.rem.push(t); } --cnt; }); // filter removed tuples out of the sample reservoir res = res.filter(function(t) { return map[t._id] !== -1; }); } if ((pulse.rem.length || mod) && res.length < num && pulse.source) { // replenish sample if backing data source is available cap = cnt = res.length; pulse.visit(pulse.SOURCE, function(t) { // update, but skip previously sampled tuples if (!map[t._id]) update(t); }); cap = -1; } if (mod && res.length > num) { for (var i=0, n=res.length-num; i<n; ++i) { map[res[i]._id] = -1; out.rem.push(res[i]); } res = res.slice(n); } if (pulse.mod.length) { // propagate modified tuples in the sample reservoir pulse.visit(pulse.MOD, function(t) { if (map[t._id]) out.mod.push(t); }); } if (pulse.add.length) { // update sample reservoir pulse.visit(pulse.ADD, update); } if (pulse.add.length || cap < 0) { // output newly added tuples out.add = res.filter(function(t) { return !map[t._id]; }); } this.count = cnt; this.value = out.source = res; return out; }; /** * Propagates a new pulse without any tuples so long as the input * pulse contains some added, removed or modified tuples. * @constructor */ function Sieve(params) { Transform.call(this, null, params); this.modified(true); // always treat as modified } var prototype$29 = inherits(Sieve, Transform); prototype$29.transform = function(_, pulse) { this.value = pulse.source; return pulse.changed() ? pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS) : pulse.StopPropagation; }; /** * An index that maps from unique, string-coerced, field values to tuples. * Assumes that the field serves as a unique key with no duplicate values. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The field accessor to index. */ function TupleIndex(params) { Transform.call(this, {}, params); } var prototype$30 = inherits(TupleIndex, Transform); prototype$30.transform = function(_, pulse) { var field = _.field, index = this.value, mod = true; function set(t) { index[field(t)] = t; } if (_.modified('field') || pulse.modified(field.fields)) { this.value = index = {}; pulse.visit(pulse.SOURCE, set); } else if (pulse.changed()) { pulse.visit(pulse.REM, function(t) { index[field(t)] = undefined; }); pulse.visit(pulse.ADD, set); } else { mod = false; } this.modified(mod); return pulse.fork(); }; /** * Extracts an array of values. Assumes the source data has already been * reduced as needed (e.g., by an upstream Aggregate transform). * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The domain field to extract. * @param {function(*,*): number} [params.sort] - An optional * comparator function for sorting the values. The comparator will be * applied to backing tuples prior to value extraction. */ function Values(params) { Transform.call(this, null, params); } var prototype$31 = inherits(Values, Transform); prototype$31.transform = function(_, pulse) { var run = !this.value || _.modified('field') || _.modified('sort') || pulse.changed() || (_.sort && pulse.modified(_.sort.fields)); if (run) { this.value = (_.sort ? pulse.source.slice().sort(_.sort) : pulse.source).map(_.field); } }; var AggregateDefinition = { "type": "Aggregate", "metadata": {"generates": true, "changes": true}, "params": [ { "name": "groupby", "type": "field", "array": true }, { "name": "fields", "type": "field", "array": true }, { "name": "ops", "type": "enum", "array": true, "values": [ "count", "valid", "missing", "distinct", "sum", "mean", "average", "variance", "variancep", "stdev", "stdevp", "median", "q1", "q3", "modeskew", "min", "max", "argmin", "argmax" ] }, { "name": "as", "type": "string", "array": true }, { "name": "drop", "type": "boolean", "default": true }, { "name": "key", "type": "field" } ] }; var BinDefinition = { "type": "Bin", "metadata": {"modifies": true}, "params": [ { "name": "field", "type": "field", "required": true }, { "name": "maxbins", "type": "number", "default": 20 }, { "name": "base", "type": "number", "default": 10 }, { "name": "divide", "type": "number", "array": true, "default": [5, 2] }, { "name": "extent", "type": "number", "array": true, "length": 2, "required": true }, { "name": "step", "type": "number" }, { "name": "steps", "type": "number", "array": true }, { "name": "minstep", "type": "number", "default": 0 }, { "name": "nice", "type": "boolean", "default": true }, { "name": "name", "type": "string" }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["bin0", "bin1"] } ] }; var CollectDefinition = { "type": "Collect", "metadata": {"source": true}, "params": [ { "name": "sort", "type": "compare" } ] }; var CountPatternDefinition = { "type": "CountPattern", "metadata": {"generates": true, "changes": true}, "params": [ { "name": "field", "type": "field", "required": true }, { "name": "case", "type": "enum", "values": ["upper", "lower", "mixed"], "default": "mixed" }, { "name": "pattern", "type": "string", "default": "[\\w\"]+" }, { "name": "stopwords", "type": "string", "default": "" }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["text", "count"] } ] }; var CrossDefinition = { "type": "Cross", "metadata": {"source": true, "generates": true, "changes": true}, "params": [ { "name": "filter", "type": "expr" }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["a", "b"] } ] }; var distributions = [ { "key": {"function": "normal"}, "params": [ { "name": "mean", "type": "number", "default": 0 }, { "name": "stdev", "type": "number", "default": 1 } ] }, { "key": {"function": "uniform"}, "params": [ { "name": "min", "type": "number", "default": 0 }, { "name": "max", "type": "number", "default": 1 } ] }, { "key": {"function": "kde"}, "params": [ { "name": "field", "type": "field", "required": true }, { "name": "from", "type": "data" }, { "name": "bandwidth", "type": "number", "default": 0 } ] } ]; var mixture = { "key": {"function": "mixture"}, "params": [ { "name": "distributions", "type": "param", "array": true, "params": distributions }, { "name": "weights", "type": "number", "array": true } ] }; var DensityDefinition = { "type": "Density", "metadata": {"generates": true, "source": true}, "params": [ { "name": "extent", "type": "number", "array": true, "length": 2 }, { "name": "steps", "type": "number", "default": 100 }, { "name": "method", "type": "string", "default": "pdf", "values": ["pdf", "cdf"] }, { "name": "distribution", "type": "param", "params": distributions.concat(mixture) }, { "name": "as", "type": "string", "array": true } ] }; var ExtentDefinition = { "type": "Extent", "metadata": {}, "params": [ { "name": "field", "type": "field", "required": true } ] }; var FilterDefinition = { "type": "Filter", "metadata": {"changes": true}, "params": [ { "name": "expr", "type": "expr", "required": true } ] }; var FoldDefinition = { "type": "Fold", "metadata": {"generates": true, "changes": true}, "params": [ { "name": "fields", "type": "field", "array": true, "required": true }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["key", "value"] } ] }; var FormulaDefinition = { "type": "Formula", "metadata": {"modifies": true}, "params": [ { "name": "expr", "type": "expr", "required": true }, { "name": "as", "type": "string", "required": true } ] }; var ImputeDefinition = { "type": "Impute", "metadata": {"changes": true}, "params": [ { "name": "field", "type": "field", "required": true }, { "name": "groupby", "type": "field", "array": true }, { "name": "orderby", "type": "field", "array": true }, { "name": "method", "type": "enum", "default": "value", "values": ["value", "mean", "median", "max", "min"] }, { "name": "value", "default": 0 } ] }; var LookupDefinition = { "type": "Lookup", "metadata": {"modifies": true}, "params": [ { "name": "index", "type": "index", "params": [ {"name": "from", "type": "data", "required": true }, {"name": "key", "type": "field", "required": true } ] }, { "name": "fields", "type": "field", "array": true, "required": true }, { "name": "as", "type": "string", "array": true, "required": true }, { "name": "default", "default": null } ] }; var RangeDefinition = { "type": "Range", "metadata": {"generates": true, "source": true}, "params": [ { "name": "start", "type": "number", "required": true }, { "name": "stop", "type": "number", "required": true }, { "name": "step", "type": "number", "default": 1 } ], "output": ["value"] }; var RankDefinition = { "type": "Rank", "metadata": {"modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "normalize", "type": "boolean", "default": false }, { "name": "as", "type": "string", "default": "rank" } ] }; var SampleDefinition = { "type": "Sample", "metadata": {"source": true, "changes": true}, "params": [ { "name": "size", "type": "number", "default": 1000 } ] }; // Data Transforms register(AggregateDefinition, Aggregate); register(BinDefinition, Bin); register(CollectDefinition, Collect); register(CountPatternDefinition, CountPattern); register(CrossDefinition, Cross); register(DensityDefinition, Density); register(ExtentDefinition, Extent); register(FilterDefinition, Filter); register(FoldDefinition, Fold); register(FormulaDefinition, Formula); register(ImputeDefinition, Impute); register(LookupDefinition, Lookup); register(RangeDefinition, Range); register(RankDefinition, Rank); register(SampleDefinition, Sample); transform('Compare', Compare); transform('Facet', Facet); transform('Field', Field); transform('Generate', Generate); transform('Key', Key); transform('MultiExtent', MultiExtent); transform('MultiValues', MultiValues); transform('Params', Params); transform('PreFacet', PreFacet); transform('Relay', Relay); transform('Sieve', Sieve); transform('Subflow', Subflow); transform('TupleIndex', TupleIndex); transform('Values', Values); function Bounds(b) { this.clear(); if (b) this.union(b); } var prototype$32 = Bounds.prototype; prototype$32.clone = function() { return new Bounds(this); }; prototype$32.clear = function() { this.x1 = +Number.MAX_VALUE; this.y1 = +Number.MAX_VALUE; this.x2 = -Number.MAX_VALUE; this.y2 = -Number.MAX_VALUE; return this; }; prototype$32.set = function(x1, y1, x2, y2) { if (x2 < x1) { this.x2 = x1; this.x1 = x2; } else { this.x1 = x1; this.x2 = x2; } if (y2 < y1) { this.y2 = y1; this.y1 = y2; } else { this.y1 = y1; this.y2 = y2; } return this; }; prototype$32.add = function(x, y) { if (x < this.x1) this.x1 = x; if (y < this.y1) this.y1 = y; if (x > this.x2) this.x2 = x; if (y > this.y2) this.y2 = y; return this; }; prototype$32.expand = function(d) { this.x1 -= d; this.y1 -= d; this.x2 += d; this.y2 += d; return this; }; prototype$32.round = function() { this.x1 = Math.floor(this.x1); this.y1 = Math.floor(this.y1); this.x2 = Math.ceil(this.x2); this.y2 = Math.ceil(this.y2); return this; }; prototype$32.translate = function(dx, dy) { this.x1 += dx; this.x2 += dx; this.y1 += dy; this.y2 += dy; return this; }; prototype$32.rotate = function(angle, x, y) { var cos = Math.cos(angle), sin = Math.sin(angle), cx = x - x*cos + y*sin, cy = y - x*sin - y*cos, x1 = this.x1, x2 = this.x2, y1 = this.y1, y2 = this.y2; return this.clear() .add(cos*x1 - sin*y1 + cx, sin*x1 + cos*y1 + cy) .add(cos*x1 - sin*y2 + cx, sin*x1 + cos*y2 + cy) .add(cos*x2 - sin*y1 + cx, sin*x2 + cos*y1 + cy) .add(cos*x2 - sin*y2 + cx, sin*x2 + cos*y2 + cy); }; prototype$32.union = function(b) { if (b.x1 < this.x1) this.x1 = b.x1; if (b.y1 < this.y1) this.y1 = b.y1; if (b.x2 > this.x2) this.x2 = b.x2; if (b.y2 > this.y2) this.y2 = b.y2; return this; }; prototype$32.encloses = function(b) { return b && ( this.x1 <= b.x1 && this.x2 >= b.x2 && this.y1 <= b.y1 && this.y2 >= b.y2 ); }; prototype$32.alignsWith = function(b) { return b && ( this.x1 == b.x1 || this.x2 == b.x2 || this.y1 == b.y1 || this.y2 == b.y2 ); }; prototype$32.intersects = function(b) { return b && !( this.x2 < b.x1 || this.x1 > b.x2 || this.y2 < b.y1 || this.y1 > b.y2 ); }; prototype$32.contains = function(x, y) { return !( x < this.x1 || x > this.x2 || y < this.y1 || y > this.y2 ); }; prototype$32.width = function() { return this.x2 - this.x1; }; prototype$32.height = function() { return this.y2 - this.y1; }; var gradient_id = 0; function Gradient(p0, p1) { var stops = [], gradient; return gradient = { id: 'gradient_' + (gradient_id++), x1: p0 ? p0[0] : 0, y1: p0 ? p0[1] : 0, x2: p1 ? p1[0] : 1, y2: p1 ? p1[1] : 0, stops: stops, stop: function(offset, color) { stops.push({offset: offset, color: color}); return gradient; } }; } function Item(mark) { this.mark = mark; this.bounds = (this.bounds || new Bounds()); this.bounds_prev = (this.bounds_prev || new Bounds()); } function inherits$1(child, parent) { var proto = (child.prototype = Object.create(parent.prototype)); proto.constructor = child; return proto; } function GroupItem(mark) { Item.call(this, mark); this.items = (this.items || []); } inherits$1(GroupItem, Item); var Canvas; try { Canvas = require('canvas'); } catch (e) { Canvas = null; } function Canvas$1(w, h) { var canvas = null; if (typeof document !== 'undefined' && document.createElement) { canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; } else if (Canvas) { canvas = new Canvas(w, h); } return canvas; } var Image$1 = typeof Image !== 'undefined' ? Image : (Canvas && Canvas.Image || null); function ImageLoader(imageLoader) { this._pending = 0; this._loader = imageLoader || loader(); } var prototype$33 = ImageLoader.prototype; prototype$33.pending = function() { return this._pending; }; prototype$33.loadImage = function(uri) { var loader = this; loader._pending += 1; return loader._loader.sanitize(uri, {context:'image'}) .then(function(url) { if (!url || !Image$1) throw 'Image unsupported.'; var image = new Image$1(); image.onload = function() { loader._pending -= 1; image.loaded = true; }; image.onerror = function() { loader._pending -= 1; image.loaded = false; } image.src = url; return image; }) .catch(function() { loader._pending -= 1; return {loaded: false, width: 0, height: 0}; }); }; prototype$33.ready = function() { var loader = this; return new Promise(function(accept) { function poll(value) { if (!loader._pending) accept(value); else setTimeout(function() { poll(true); }, 10); } poll(false); }); }; var pi = Math.PI; var tau = 2 * pi; var epsilon = 1e-6; var tauEpsilon = tau - epsilon; function Path() { this._x0 = this._y0 = // start of current subpath this._x1 = this._y1 = null; // end of current subpath this._ = ""; } function path() { return new Path; } Path.prototype = path.prototype = { constructor: Path, moveTo: function(x, y) { this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y); }, closePath: function() { if (this._x1 !== null) { this._x1 = this._x0, this._y1 = this._y0; this._ += "Z"; } }, lineTo: function(x, y) { this._ += "L" + (this._x1 = +x) + "," + (this._y1 = +y); }, quadraticCurveTo: function(x1, y1, x, y) { this._ += "Q" + (+x1) + "," + (+y1) + "," + (this._x1 = +x) + "," + (this._y1 = +y); }, bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._ += "C" + (+x1) + "," + (+y1) + "," + (+x2) + "," + (+y2) + "," + (this._x1 = +x) + "," + (this._y1 = +y); }, arcTo: function(x1, y1, x2, y2, r) { x1 = +x1, y1 = +y1, x2 = +x2, y2 = +y2, r = +r; var x0 = this._x1, y0 = this._y1, x21 = x2 - x1, y21 = y2 - y1, x01 = x0 - x1, y01 = y0 - y1, l01_2 = x01 * x01 + y01 * y01; // Is the radius negative? Error. if (r < 0) throw new Error("negative radius: " + r); // Is this path empty? Move to (x1,y1). if (this._x1 === null) { this._ += "M" + (this._x1 = x1) + "," + (this._y1 = y1); } // Or, is (x1,y1) coincident with (x0,y0)? Do nothing. else if (!(l01_2 > epsilon)) {} // Or, are (x0,y0), (x1,y1) and (x2,y2) collinear? // Equivalently, is (x1,y1) coincident with (x2,y2)? // Or, is the radius zero? Line to (x1,y1). else if (!(Math.abs(y01 * x21 - y21 * x01) > epsilon) || !r) { this._ += "L" + (this._x1 = x1) + "," + (this._y1 = y1); } // Otherwise, draw an arc! else { var x20 = x2 - x0, y20 = y2 - y0, l21_2 = x21 * x21 + y21 * y21, l20_2 = x20 * x20 + y20 * y20, l21 = Math.sqrt(l21_2), l01 = Math.sqrt(l01_2), l = r * Math.tan((pi - Math.acos((l21_2 + l01_2 - l20_2) / (2 * l21 * l01))) / 2), t01 = l / l01, t21 = l / l21; // If the start tangent is not coincident with (x0,y0), line to. if (Math.abs(t01 - 1) > epsilon) { this._ += "L" + (x1 + t01 * x01) + "," + (y1 + t01 * y01); } this._ += "A" + r + "," + r + ",0,0," + (+(y01 * x20 > x01 * y20)) + "," + (this._x1 = x1 + t21 * x21) + "," + (this._y1 = y1 + t21 * y21); } }, arc: function(x, y, r, a0, a1, ccw) { x = +x, y = +y, r = +r; var dx = r * Math.cos(a0), dy = r * Math.sin(a0), x0 = x + dx, y0 = y + dy, cw = 1 ^ ccw, da = ccw ? a0 - a1 : a1 - a0; // Is the radius negative? Error. if (r < 0) throw new Error("negative radius: " + r); // Is this path empty? Move to (x0,y0). if (this._x1 === null) { this._ += "M" + x0 + "," + y0; } // Or, is (x0,y0) not coincident with the previous point? Line to (x0,y0). else if (Math.abs(this._x1 - x0) > epsilon || Math.abs(this._y1 - y0) > epsilon) { this._ += "L" + x0 + "," + y0; } // Is this arc empty? We’re done. if (!r) return; // Is this a complete circle? Draw two arcs to complete the circle. if (da > tauEpsilon) { this._ += "A" + r + "," + r + ",0,1," + cw + "," + (x - dx) + "," + (y - dy) + "A" + r + "," + r + ",0,1," + cw + "," + (this._x1 = x0) + "," + (this._y1 = y0); } // Otherwise, draw an arc! else { if (da < 0) da = da % tau + tau; this._ += "A" + r + "," + r + ",0," + (+(da >= pi)) + "," + cw + "," + (this._x1 = x + r * Math.cos(a1)) + "," + (this._y1 = y + r * Math.sin(a1)); } }, rect: function(x, y, w, h) { this._ += "M" + (this._x0 = this._x1 = +x) + "," + (this._y0 = this._y1 = +y) + "h" + (+w) + "v" + (+h) + "h" + (-w) + "Z"; }, toString: function() { return this._; } }; function constant$2(x) { return function constant() { return x; }; } var epsilon$1 = 1e-12; var pi$1 = Math.PI; var halfPi = pi$1 / 2; var tau$1 = 2 * pi$1; function arcInnerRadius(d) { return d.innerRadius; } function arcOuterRadius(d) { return d.outerRadius; } function arcStartAngle(d) { return d.startAngle; } function arcEndAngle(d) { return d.endAngle; } function arcPadAngle(d) { return d && d.padAngle; // Note: optional! } function asin(x) { return x >= 1 ? halfPi : x <= -1 ? -halfPi : Math.asin(x); } function intersect(x0, y0, x1, y1, x2, y2, x3, y3) { var x10 = x1 - x0, y10 = y1 - y0, x32 = x3 - x2, y32 = y3 - y2, t = (x32 * (y0 - y2) - y32 * (x0 - x2)) / (y32 * x10 - x32 * y10); return [x0 + t * x10, y0 + t * y10]; } // Compute perpendicular offset line of length rc. // http://mathworld.wolfram.com/Circle-LineIntersection.html function cornerTangents(x0, y0, x1, y1, r1, rc, cw) { var x01 = x0 - x1, y01 = y0 - y1, lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x11 = x0 + ox, y11 = y0 + oy, x10 = x1 + ox, y10 = y1 + oy, x00 = (x11 + x10) / 2, y00 = (y11 + y10) / 2, dx = x10 - x11, dy = y10 - y11, d2 = dx * dx + dy * dy, r = r1 - rc, D = x11 * y10 - x10 * y11, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x00, dy0 = cy0 - y00, dx1 = cx1 - x00, dy1 = cy1 - y00; // Pick the closer of the two intersection points. // TODO Is there a faster way to determine which intersection to use? if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; return { cx: cx0, cy: cy0, x01: -ox, y01: -oy, x11: cx0 * (r1 / r - 1), y11: cy0 * (r1 / r - 1) }; } function d3_arc() { var innerRadius = arcInnerRadius, outerRadius = arcOuterRadius, cornerRadius = constant$2(0), padRadius = null, startAngle = arcStartAngle, endAngle = arcEndAngle, padAngle = arcPadAngle, context = null; function arc() { var buffer, r, r0 = +innerRadius.apply(this, arguments), r1 = +outerRadius.apply(this, arguments), a0 = startAngle.apply(this, arguments) - halfPi, a1 = endAngle.apply(this, arguments) - halfPi, da = Math.abs(a1 - a0), cw = a1 > a0; if (!context) context = buffer = path(); // Ensure that the outer radius is always larger than the inner radius. if (r1 < r0) r = r1, r1 = r0, r0 = r; // Is it a point? if (!(r1 > epsilon$1)) context.moveTo(0, 0); // Or is it a circle or annulus? else if (da > tau$1 - epsilon$1) { context.moveTo(r1 * Math.cos(a0), r1 * Math.sin(a0)); context.arc(0, 0, r1, a0, a1, !cw); if (r0 > epsilon$1) { context.moveTo(r0 * Math.cos(a1), r0 * Math.sin(a1)); context.arc(0, 0, r0, a1, a0, cw); } } // Or is it a circular or annular sector? else { var a01 = a0, a11 = a1, a00 = a0, a10 = a1, da0 = da, da1 = da, ap = padAngle.apply(this, arguments) / 2, rp = (ap > epsilon$1) && (padRadius ? +padRadius.apply(this, arguments) : Math.sqrt(r0 * r0 + r1 * r1)), rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments)), rc0 = rc, rc1 = rc, t0, t1; // Apply padding? Note that since r1 ≥ r0, da1 ≥ da0. if (rp > epsilon$1) { var p0 = asin(rp / r0 * Math.sin(ap)), p1 = asin(rp / r1 * Math.sin(ap)); if ((da0 -= p0 * 2) > epsilon$1) p0 *= (cw ? 1 : -1), a00 += p0, a10 -= p0; else da0 = 0, a00 = a10 = (a0 + a1) / 2; if ((da1 -= p1 * 2) > epsilon$1) p1 *= (cw ? 1 : -1), a01 += p1, a11 -= p1; else da1 = 0, a01 = a11 = (a0 + a1) / 2; } var x01 = r1 * Math.cos(a01), y01 = r1 * Math.sin(a01), x10 = r0 * Math.cos(a10), y10 = r0 * Math.sin(a10); // Apply rounded corners? if (rc > epsilon$1) { var x11 = r1 * Math.cos(a11), y11 = r1 * Math.sin(a11), x00 = r0 * Math.cos(a00), y00 = r0 * Math.sin(a00); // Restrict the corner radius according to the sector angle. if (da < pi$1) { var oc = da0 > epsilon$1 ? intersect(x01, y01, x00, y00, x11, y11, x10, y10) : [x10, y10], ax = x01 - oc[0], ay = y01 - oc[1], bx = x11 - oc[0], by = y11 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); } } // Is the sector collapsed to a line? if (!(da1 > epsilon$1)) context.moveTo(x01, y01); // Does the sector’s outer ring have rounded corners? else if (rc1 > epsilon$1) { t0 = cornerTangents(x00, y00, x01, y01, r1, rc1, cw); t1 = cornerTangents(x11, y11, x10, y10, r1, rc1, cw); context.moveTo(t0.cx + t0.x01, t0.cy + t0.y01); // Have the corners merged? if (rc1 < rc) context.arc(t0.cx, t0.cy, rc1, Math.atan2(t0.y01, t0.x01), Math.atan2(t1.y01, t1.x01), !cw); // Otherwise, draw the two corners and the ring. else { context.arc(t0.cx, t0.cy, rc1, Math.atan2(t0.y01, t0.x01), Math.atan2(t0.y11, t0.x11), !cw); context.arc(0, 0, r1, Math.atan2(t0.cy + t0.y11, t0.cx + t0.x11), Math.atan2(t1.cy + t1.y11, t1.cx + t1.x11), !cw); context.arc(t1.cx, t1.cy, rc1, Math.atan2(t1.y11, t1.x11), Math.atan2(t1.y01, t1.x01), !cw); } } // Or is the outer ring just a circular arc? else context.moveTo(x01, y01), context.arc(0, 0, r1, a01, a11, !cw); // Is there no inner ring, and it’s a circular sector? // Or perhaps it’s an annular sector collapsed due to padding? if (!(r0 > epsilon$1) || !(da0 > epsilon$1)) context.lineTo(x10, y10); // Does the sector’s inner ring (or point) have rounded corners? else if (rc0 > epsilon$1) { t0 = cornerTangents(x10, y10, x11, y11, r0, -rc0, cw); t1 = cornerTangents(x01, y01, x00, y00, r0, -rc0, cw); context.lineTo(t0.cx + t0.x01, t0.cy + t0.y01); // Have the corners merged? if (rc0 < rc) context.arc(t0.cx, t0.cy, rc0, Math.atan2(t0.y01, t0.x01), Math.atan2(t1.y01, t1.x01), !cw); // Otherwise, draw the two corners and the ring. else { context.arc(t0.cx, t0.cy, rc0, Math.atan2(t0.y01, t0.x01), Math.atan2(t0.y11, t0.x11), !cw); context.arc(0, 0, r0, Math.atan2(t0.cy + t0.y11, t0.cx + t0.x11), Math.atan2(t1.cy + t1.y11, t1.cx + t1.x11), cw); context.arc(t1.cx, t1.cy, rc0, Math.atan2(t1.y11, t1.x11), Math.atan2(t1.y01, t1.x01), !cw); } } // Or is the inner ring just a circular arc? else context.arc(0, 0, r0, a10, a00, cw); } context.closePath(); if (buffer) return context = null, buffer + "" || null; } arc.centroid = function() { var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - pi$1 / 2; return [Math.cos(a) * r, Math.sin(a) * r]; }; arc.innerRadius = function(_) { return arguments.length ? (innerRadius = typeof _ === "function" ? _ : constant$2(+_), arc) : innerRadius; }; arc.outerRadius = function(_) { return arguments.length ? (outerRadius = typeof _ === "function" ? _ : constant$2(+_), arc) : outerRadius; }; arc.cornerRadius = function(_) { return arguments.length ? (cornerRadius = typeof _ === "function" ? _ : constant$2(+_), arc) : cornerRadius; }; arc.padRadius = function(_) { return arguments.length ? (padRadius = _ == null ? null : typeof _ === "function" ? _ : constant$2(+_), arc) : padRadius; }; arc.startAngle = function(_) { return arguments.length ? (startAngle = typeof _ === "function" ? _ : constant$2(+_), arc) : startAngle; }; arc.endAngle = function(_) { return arguments.length ? (endAngle = typeof _ === "function" ? _ : constant$2(+_), arc) : endAngle; }; arc.padAngle = function(_) { return arguments.length ? (padAngle = typeof _ === "function" ? _ : constant$2(+_), arc) : padAngle; }; arc.context = function(_) { return arguments.length ? ((context = _ == null ? null : _), arc) : context; }; return arc; } function Linear(context) { this._context = context; } Linear.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._point = 0; }, lineEnd: function() { if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath(); this._line = 1 - this._line; }, point: function(x, y) { x = +x, y = +y; switch (this._point) { case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break; case 1: this._point = 2; // proceed default: this._context.lineTo(x, y); break; } } }; function curveLinear(context) { return new Linear(context); } function x$1(p) { return p[0]; } function y$1(p) { return p[1]; } function line$1() { var x = x$1, y = y$1, defined = constant$2(true), context = null, curve = curveLinear, output = null; function line(data) { var i, n = data.length, d, defined0 = false, buffer; if (context == null) output = curve(buffer = path()); for (i = 0; i <= n; ++i) { if (!(i < n && defined(d = data[i], i, data)) === defined0) { if (defined0 = !defined0) output.lineStart(); else output.lineEnd(); } if (defined0) output.point(+x(d, i, data), +y(d, i, data)); } if (buffer) return output = null, buffer + "" || null; } line.x = function(_) { return arguments.length ? (x = typeof _ === "function" ? _ : constant$2(+_), line) : x; }; line.y = function(_) { return arguments.length ? (y = typeof _ === "function" ? _ : constant$2(+_), line) : y; }; line.defined = function(_) { return arguments.length ? (defined = typeof _ === "function" ? _ : constant$2(!!_), line) : defined; }; line.curve = function(_) { return arguments.length ? (curve = _, context != null && (output = curve(context)), line) : curve; }; line.context = function(_) { return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), line) : context; }; return line; } function area$1() { var x0 = x$1, x1 = null, y0 = constant$2(0), y1 = y$1, defined = constant$2(true), context = null, curve = curveLinear, output = null; function area(data) { var i, j, k, n = data.length, d, defined0 = false, buffer, x0z = new Array(n), y0z = new Array(n); if (context == null) output = curve(buffer = path()); for (i = 0; i <= n; ++i) { if (!(i < n && defined(d = data[i], i, data)) === defined0) { if (defined0 = !defined0) { j = i; output.areaStart(); output.lineStart(); } else { output.lineEnd(); output.lineStart(); for (k = i - 1; k >= j; --k) { output.point(x0z[k], y0z[k]); } output.lineEnd(); output.areaEnd(); } } if (defined0) { x0z[i] = +x0(d, i, data), y0z[i] = +y0(d, i, data); output.point(x1 ? +x1(d, i, data) : x0z[i], y1 ? +y1(d, i, data) : y0z[i]); } } if (buffer) return output = null, buffer + "" || null; } function arealine() { return line$1().defined(defined).curve(curve).context(context); } area.x = function(_) { return arguments.length ? (x0 = typeof _ === "function" ? _ : constant$2(+_), x1 = null, area) : x0; }; area.x0 = function(_) { return arguments.length ? (x0 = typeof _ === "function" ? _ : constant$2(+_), area) : x0; }; area.x1 = function(_) { return arguments.length ? (x1 = _ == null ? null : typeof _ === "function" ? _ : constant$2(+_), area) : x1; }; area.y = function(_) { return arguments.length ? (y0 = typeof _ === "function" ? _ : constant$2(+_), y1 = null, area) : y0; }; area.y0 = function(_) { return arguments.length ? (y0 = typeof _ === "function" ? _ : constant$2(+_), area) : y0; }; area.y1 = function(_) { return arguments.length ? (y1 = _ == null ? null : typeof _ === "function" ? _ : constant$2(+_), area) : y1; }; area.lineX0 = area.lineY0 = function() { return arealine().x(x0).y(y0); }; area.lineY1 = function() { return arealine().x(x0).y(y1); }; area.lineX1 = function() { return arealine().x(x1).y(y0); }; area.defined = function(_) { return arguments.length ? (defined = typeof _ === "function" ? _ : constant$2(!!_), area) : defined; }; area.curve = function(_) { return arguments.length ? (curve = _, context != null && (output = curve(context)), area) : curve; }; area.context = function(_) { return arguments.length ? (_ == null ? context = output = null : output = curve(context = _), area) : context; }; return area; } var circle = { draw: function(context, size) { var r = Math.sqrt(size / pi$1); context.moveTo(r, 0); context.arc(0, 0, r, 0, tau$1); } }; var kr = Math.sin(pi$1 / 10) / Math.sin(7 * pi$1 / 10); var kx = Math.sin(tau$1 / 10) * kr; var ky = -Math.cos(tau$1 / 10) * kr; function d3_symbol() { var type = constant$2(circle), size = constant$2(64), context = null; function symbol() { var buffer; if (!context) context = buffer = path(); type.apply(this, arguments).draw(context, +size.apply(this, arguments)); if (buffer) return context = null, buffer + "" || null; } symbol.type = function(_) { return arguments.length ? (type = typeof _ === "function" ? _ : constant$2(_), symbol) : type; }; symbol.size = function(_) { return arguments.length ? (size = typeof _ === "function" ? _ : constant$2(+_), symbol) : size; }; symbol.context = function(_) { return arguments.length ? (context = _ == null ? null : _, symbol) : context; }; return symbol; } function noop$2() {} function point(that, x, y) { that._context.bezierCurveTo( (2 * that._x0 + that._x1) / 3, (2 * that._y0 + that._y1) / 3, (that._x0 + 2 * that._x1) / 3, (that._y0 + 2 * that._y1) / 3, (that._x0 + 4 * that._x1 + x) / 6, (that._y0 + 4 * that._y1 + y) / 6 ); } function Basis(context) { this._context = context; } Basis.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._x0 = this._x1 = this._y0 = this._y1 = NaN; this._point = 0; }, lineEnd: function() { switch (this._point) { case 3: point(this, this._x1, this._y1); // proceed case 2: this._context.lineTo(this._x1, this._y1); break; } if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath(); this._line = 1 - this._line; }, point: function(x, y) { x = +x, y = +y; switch (this._point) { case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break; case 1: this._point = 2; break; case 2: this._point = 3; this._context.lineTo((5 * this._x0 + this._x1) / 6, (5 * this._y0 + this._y1) / 6); // proceed default: point(this, x, y); break; } this._x0 = this._x1, this._x1 = x; this._y0 = this._y1, this._y1 = y; } }; function curveBasis(context) { return new Basis(context); } function Bundle(context, beta) { this._basis = new Basis(context); this._beta = beta; } Bundle.prototype = { lineStart: function() { this._x = []; this._y = []; this._basis.lineStart(); }, lineEnd: function() { var x = this._x, y = this._y, j = x.length - 1; if (j > 0) { var x0 = x[0], y0 = y[0], dx = x[j] - x0, dy = y[j] - y0, i = -1, t; while (++i <= j) { t = i / j; this._basis.point( this._beta * x[i] + (1 - this._beta) * (x0 + t * dx), this._beta * y[i] + (1 - this._beta) * (y0 + t * dy) ); } } this._x = this._y = null; this._basis.lineEnd(); }, point: function(x, y) { this._x.push(+x); this._y.push(+y); } }; var curveBundle = (function custom(beta) { function bundle(context) { return beta === 1 ? new Basis(context) : new Bundle(context, beta); } bundle.beta = function(beta) { return custom(+beta); }; return bundle; })(0.85); function point$1(that, x, y) { that._context.bezierCurveTo( that._x1 + that._k * (that._x2 - that._x0), that._y1 + that._k * (that._y2 - that._y0), that._x2 + that._k * (that._x1 - x), that._y2 + that._k * (that._y1 - y), that._x2, that._y2 ); } function Cardinal(context, tension) { this._context = context; this._k = (1 - tension) / 6; } Cardinal.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN; this._point = 0; }, lineEnd: function() { switch (this._point) { case 2: this._context.lineTo(this._x2, this._y2); break; case 3: point$1(this, this._x1, this._y1); break; } if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath(); this._line = 1 - this._line; }, point: function(x, y) { x = +x, y = +y; switch (this._point) { case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break; case 1: this._point = 2; this._x1 = x, this._y1 = y; break; case 2: this._point = 3; // proceed default: point$1(this, x, y); break; } this._x0 = this._x1, this._x1 = this._x2, this._x2 = x; this._y0 = this._y1, this._y1 = this._y2, this._y2 = y; } }; var curveCardinal = (function custom(tension) { function cardinal(context) { return new Cardinal(context, tension); } cardinal.tension = function(tension) { return custom(+tension); }; return cardinal; })(0); function CardinalClosed(context, tension) { this._context = context; this._k = (1 - tension) / 6; } CardinalClosed.prototype = { areaStart: noop$2, areaEnd: noop$2, lineStart: function() { this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN; this._point = 0; }, lineEnd: function() { switch (this._point) { case 1: { this._context.moveTo(this._x3, this._y3); this._context.closePath(); break; } case 2: { this._context.lineTo(this._x3, this._y3); this._context.closePath(); break; } case 3: { this.point(this._x3, this._y3); this.point(this._x4, this._y4); this.point(this._x5, this._y5); break; } } }, point: function(x, y) { x = +x, y = +y; switch (this._point) { case 0: this._point = 1; this._x3 = x, this._y3 = y; break; case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break; case 2: this._point = 3; this._x5 = x, this._y5 = y; break; default: point$1(this, x, y); break; } this._x0 = this._x1, this._x1 = this._x2, this._x2 = x; this._y0 = this._y1, this._y1 = this._y2, this._y2 = y; } }; (function custom(tension) { function cardinal(context) { return new CardinalClosed(context, tension); } cardinal.tension = function(tension) { return custom(+tension); }; return cardinal; })(0); function CardinalOpen(context, tension) { this._context = context; this._k = (1 - tension) / 6; } CardinalOpen.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN; this._point = 0; }, lineEnd: function() { if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath(); this._line = 1 - this._line; }, point: function(x, y) { x = +x, y = +y; switch (this._point) { case 0: this._point = 1; break; case 1: this._point = 2; break; case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break; case 3: this._point = 4; // proceed default: point$1(this, x, y); break; } this._x0 = this._x1, this._x1 = this._x2, this._x2 = x; this._y0 = this._y1, this._y1 = this._y2, this._y2 = y; } }; (function custom(tension) { function cardinal(context) { return new CardinalOpen(context, tension); } cardinal.tension = function(tension) { return custom(+tension); }; return cardinal; })(0); function point$2(that, x, y) { var x1 = that._x1, y1 = that._y1, x2 = that._x2, y2 = that._y2; if (that._l01_a > epsilon$1) { var a = 2 * that._l01_2a + 3 * that._l01_a * that._l12_a + that._l12_2a, n = 3 * that._l01_a * (that._l01_a + that._l12_a); x1 = (x1 * a - that._x0 * that._l12_2a + that._x2 * that._l01_2a) / n; y1 = (y1 * a - that._y0 * that._l12_2a + that._y2 * that._l01_2a) / n; } if (that._l23_a > epsilon$1) { var b = 2 * that._l23_2a + 3 * that._l23_a * that._l12_a + that._l12_2a, m = 3 * that._l23_a * (that._l23_a + that._l12_a); x2 = (x2 * b + that._x1 * that._l23_2a - x * that._l12_2a) / m; y2 = (y2 * b + that._y1 * that._l23_2a - y * that._l12_2a) / m; } that._context.bezierCurveTo(x1, y1, x2, y2, that._x2, that._y2); } function CatmullRom(context, alpha) { this._context = context; this._alpha = alpha; } CatmullRom.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN; this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0; }, lineEnd: function() { switch (this._point) { case 2: this._context.lineTo(this._x2, this._y2); break; case 3: this.point(this._x2, this._y2); break; } if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath(); this._line = 1 - this._line; }, point: function(x, y) { x = +x, y = +y; if (this._point) { var x23 = this._x2 - x, y23 = this._y2 - y; this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha)); } switch (this._point) { case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break; case 1: this._point = 2; break; case 2: this._point = 3; // proceed default: point$2(this, x, y); break; } this._l01_a = this._l12_a, this._l12_a = this._l23_a; this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a; this._x0 = this._x1, this._x1 = this._x2, this._x2 = x; this._y0 = this._y1, this._y1 = this._y2, this._y2 = y; } }; var curveCatmullRom = (function custom(alpha) { function catmullRom(context) { return alpha ? new CatmullRom(context, alpha) : new Cardinal(context, 0); } catmullRom.alpha = function(alpha) { return custom(+alpha); }; return catmullRom; })(0.5); function CatmullRomClosed(context, alpha) { this._context = context; this._alpha = alpha; } CatmullRomClosed.prototype = { areaStart: noop$2, areaEnd: noop$2, lineStart: function() { this._x0 = this._x1 = this._x2 = this._x3 = this._x4 = this._x5 = this._y0 = this._y1 = this._y2 = this._y3 = this._y4 = this._y5 = NaN; this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0; }, lineEnd: function() { switch (this._point) { case 1: { this._context.moveTo(this._x3, this._y3); this._context.closePath(); break; } case 2: { this._context.lineTo(this._x3, this._y3); this._context.closePath(); break; } case 3: { this.point(this._x3, this._y3); this.point(this._x4, this._y4); this.point(this._x5, this._y5); break; } } }, point: function(x, y) { x = +x, y = +y; if (this._point) { var x23 = this._x2 - x, y23 = this._y2 - y; this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha)); } switch (this._point) { case 0: this._point = 1; this._x3 = x, this._y3 = y; break; case 1: this._point = 2; this._context.moveTo(this._x4 = x, this._y4 = y); break; case 2: this._point = 3; this._x5 = x, this._y5 = y; break; default: point$2(this, x, y); break; } this._l01_a = this._l12_a, this._l12_a = this._l23_a; this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a; this._x0 = this._x1, this._x1 = this._x2, this._x2 = x; this._y0 = this._y1, this._y1 = this._y2, this._y2 = y; } }; (function custom(alpha) { function catmullRom(context) { return alpha ? new CatmullRomClosed(context, alpha) : new CardinalClosed(context, 0); } catmullRom.alpha = function(alpha) { return custom(+alpha); }; return catmullRom; })(0.5); function CatmullRomOpen(context, alpha) { this._context = context; this._alpha = alpha; } CatmullRomOpen.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._x0 = this._x1 = this._x2 = this._y0 = this._y1 = this._y2 = NaN; this._l01_a = this._l12_a = this._l23_a = this._l01_2a = this._l12_2a = this._l23_2a = this._point = 0; }, lineEnd: function() { if (this._line || (this._line !== 0 && this._point === 3)) this._context.closePath(); this._line = 1 - this._line; }, point: function(x, y) { x = +x, y = +y; if (this._point) { var x23 = this._x2 - x, y23 = this._y2 - y; this._l23_a = Math.sqrt(this._l23_2a = Math.pow(x23 * x23 + y23 * y23, this._alpha)); } switch (this._point) { case 0: this._point = 1; break; case 1: this._point = 2; break; case 2: this._point = 3; this._line ? this._context.lineTo(this._x2, this._y2) : this._context.moveTo(this._x2, this._y2); break; case 3: this._point = 4; // proceed default: point$2(this, x, y); break; } this._l01_a = this._l12_a, this._l12_a = this._l23_a; this._l01_2a = this._l12_2a, this._l12_2a = this._l23_2a; this._x0 = this._x1, this._x1 = this._x2, this._x2 = x; this._y0 = this._y1, this._y1 = this._y2, this._y2 = y; } }; (function custom(alpha) { function catmullRom(context) { return alpha ? new CatmullRomOpen(context, alpha) : new CardinalOpen(context, 0); } catmullRom.alpha = function(alpha) { return custom(+alpha); }; return catmullRom; })(0.5); function sign(x) { return x < 0 ? -1 : 1; } // Calculate the slopes of the tangents (Hermite-type interpolation) based on // the following paper: Steffen, M. 1990. A Simple Method for Monotonic // Interpolation in One Dimension. Astronomy and Astrophysics, Vol. 239, NO. // NOV(II), P. 443, 1990. function slope3(that, x2, y2) { var h0 = that._x1 - that._x0, h1 = x2 - that._x1, s0 = (that._y1 - that._y0) / (h0 || h1 < 0 && -0), s1 = (y2 - that._y1) / (h1 || h0 < 0 && -0), p = (s0 * h1 + s1 * h0) / (h0 + h1); return (sign(s0) + sign(s1)) * Math.min(Math.abs(s0), Math.abs(s1), 0.5 * Math.abs(p)) || 0; } // Calculate a one-sided slope. function slope2(that, t) { var h = that._x1 - that._x0; return h ? (3 * (that._y1 - that._y0) / h - t) / 2 : t; } // According to https://en.wikipedia.org/wiki/Cubic_Hermite_spline#Representations // "you can express cubic Hermite interpolation in terms of cubic Bézier curves // with respect to the four values p0, p0 + m0 / 3, p1 - m1 / 3, p1". function point$3(that, t0, t1) { var x0 = that._x0, y0 = that._y0, x1 = that._x1, y1 = that._y1, dx = (x1 - x0) / 3; that._context.bezierCurveTo(x0 + dx, y0 + dx * t0, x1 - dx, y1 - dx * t1, x1, y1); } function MonotoneX(context) { this._context = context; } MonotoneX.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._x0 = this._x1 = this._y0 = this._y1 = this._t0 = NaN; this._point = 0; }, lineEnd: function() { switch (this._point) { case 2: this._context.lineTo(this._x1, this._y1); break; case 3: point$3(this, this._t0, slope2(this, this._t0)); break; } if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath(); this._line = 1 - this._line; }, point: function(x, y) { var t1 = NaN; x = +x, y = +y; if (x === this._x1 && y === this._y1) return; // Ignore coincident points. switch (this._point) { case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break; case 1: this._point = 2; break; case 2: this._point = 3; point$3(this, slope2(this, t1 = slope3(this, x, y)), t1); break; default: point$3(this, this._t0, t1 = slope3(this, x, y)); break; } this._x0 = this._x1, this._x1 = x; this._y0 = this._y1, this._y1 = y; this._t0 = t1; } } function MonotoneY(context) { this._context = new ReflectContext(context); } (MonotoneY.prototype = Object.create(MonotoneX.prototype)).point = function(x, y) { MonotoneX.prototype.point.call(this, y, x); }; function ReflectContext(context) { this._context = context; } ReflectContext.prototype = { moveTo: function(x, y) { this._context.moveTo(y, x); }, closePath: function() { this._context.closePath(); }, lineTo: function(x, y) { this._context.lineTo(y, x); }, bezierCurveTo: function(x1, y1, x2, y2, x, y) { this._context.bezierCurveTo(y1, x1, y2, x2, y, x); } }; function monotoneX(context) { return new MonotoneX(context); } function monotoneY(context) { return new MonotoneY(context); } function Natural(context) { this._context = context; } Natural.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._x = []; this._y = []; }, lineEnd: function() { var x = this._x, y = this._y, n = x.length; if (n) { this._line ? this._context.lineTo(x[0], y[0]) : this._context.moveTo(x[0], y[0]); if (n === 2) { this._context.lineTo(x[1], y[1]); } else { var px = controlPoints(x), py = controlPoints(y); for (var i0 = 0, i1 = 1; i1 < n; ++i0, ++i1) { this._context.bezierCurveTo(px[0][i0], py[0][i0], px[1][i0], py[1][i0], x[i1], y[i1]); } } } if (this._line || (this._line !== 0 && n === 1)) this._context.closePath(); this._line = 1 - this._line; this._x = this._y = null; }, point: function(x, y) { this._x.push(+x); this._y.push(+y); } }; // See https://www.particleincell.com/2012/bezier-splines/ for derivation. function controlPoints(x) { var i, n = x.length - 1, m, a = new Array(n), b = new Array(n), r = new Array(n); a[0] = 0, b[0] = 2, r[0] = x[0] + 2 * x[1]; for (i = 1; i < n - 1; ++i) a[i] = 1, b[i] = 4, r[i] = 4 * x[i] + 2 * x[i + 1]; a[n - 1] = 2, b[n - 1] = 7, r[n - 1] = 8 * x[n - 1] + x[n]; for (i = 1; i < n; ++i) m = a[i] / b[i - 1], b[i] -= m, r[i] -= m * r[i - 1]; a[n - 1] = r[n - 1] / b[n - 1]; for (i = n - 2; i >= 0; --i) a[i] = (r[i] - a[i + 1]) / b[i]; b[n - 1] = (x[n] + a[n - 1]) / 2; for (i = 0; i < n - 1; ++i) b[i] = 2 * x[i + 1] - a[i + 1]; return [a, b]; } function curveNatural(context) { return new Natural(context); } function Step(context, t) { this._context = context; this._t = t; } Step.prototype = { areaStart: function() { this._line = 0; }, areaEnd: function() { this._line = NaN; }, lineStart: function() { this._x = this._y = NaN; this._point = 0; }, lineEnd: function() { if (0 < this._t && this._t < 1 && this._point === 2) this._context.lineTo(this._x, this._y); if (this._line || (this._line !== 0 && this._point === 1)) this._context.closePath(); if (this._line >= 0) this._t = 1 - this._t, this._line = 1 - this._line; }, point: function(x, y) { x = +x, y = +y; switch (this._point) { case 0: this._point = 1; this._line ? this._context.lineTo(x, y) : this._context.moveTo(x, y); break; case 1: this._point = 2; // proceed default: { if (this._t <= 0) { this._context.lineTo(this._x, y); this._context.lineTo(x, y); } else { var x1 = this._x * (1 - this._t) + x * this._t; this._context.lineTo(x1, this._y); this._context.lineTo(x1, y); } break; } } this._x = x, this._y = y; } }; function curveStep(context) { return new Step(context, 0.5); } function stepBefore(context) { return new Step(context, 0); } function stepAfter(context) { return new Step(context, 1); } var lookup = { basis: { curve: curveBasis }, bundle: { curve: curveBundle, tension: 'beta', value: 0.85 }, cardinal: { curve: curveCardinal, tension: 'tension', value: 0 }, catmullRom: { curve: curveCatmullRom, tension: 'alpha', value: 0.5 }, linear: { curve: curveLinear }, monotone: { horizontal: monotoneY, vertical: monotoneX }, natural: { curve: curveNatural }, step: { curve: curveStep }, stepAfter: { curve: stepAfter }, stepBefore: { curve: stepBefore } }; function curves(type, orientation, tension) { var entry = lookup.hasOwnProperty(type) && lookup[type], curve = null; if (entry) { curve = entry.curve || entry[orientation || 'vertical']; if (entry.tension && tension != null) { curve = curve[entry.tension](tension); } } return curve; } // Path parsing and rendering code adapted from fabric.js -- Thanks! var cmdlen = { m:2, l:2, h:1, v:1, c:6, s:4, q:4, t:2, a:7 }; var regexp = [/([MLHVCSQTAZmlhvcsqtaz])/g, /###/, /(\d)([-+])/g, /\s|,|###/]; function pathParse(pathstr) { var result = [], path, curr, chunks, parsed, param, cmd, len, i, j, n, m; // First, break path into command sequence path = pathstr .slice() .replace(regexp[0], '###$1') .split(regexp[1]) .slice(1); // Next, parse each command in turn for (i=0, n=path.length; i<n; ++i) { curr = path[i]; chunks = curr .slice(1) .trim() .replace(regexp[2],'$1###$2') .split(regexp[3]); cmd = curr.charAt(0); parsed = [cmd]; for (j=0, m=chunks.length; j<m; ++j) { if ((param = +chunks[j]) === param) { // not NaN parsed.push(param); } } len = cmdlen[cmd.toLowerCase()]; if (parsed.length-1 > len) { for (j=1, m=parsed.length; j<m; j+=len) { result.push([cmd].concat(parsed.slice(j, j+len))); } } else { result.push(parsed); } } return result; } var segmentCache = {}; var bezierCache = {}; var join = [].join; // Copied from Inkscape svgtopdf, thanks! function segments(x, y, rx, ry, large, sweep, rotateX, ox, oy) { var key = join.call(arguments); if (segmentCache[key]) { return segmentCache[key]; } var th = rotateX * (Math.PI/180); var sin_th = Math.sin(th); var cos_th = Math.cos(th); rx = Math.abs(rx); ry = Math.abs(ry); var px = cos_th * (ox - x) * 0.5 + sin_th * (oy - y) * 0.5; var py = cos_th * (oy - y) * 0.5 - sin_th * (ox - x) * 0.5; var pl = (px*px) / (rx*rx) + (py*py) / (ry*ry); if (pl > 1) { pl = Math.sqrt(pl); rx *= pl; ry *= pl; } var a00 = cos_th / rx; var a01 = sin_th / rx; var a10 = (-sin_th) / ry; var a11 = (cos_th) / ry; var x0 = a00 * ox + a01 * oy; var y0 = a10 * ox + a11 * oy; var x1 = a00 * x + a01 * y; var y1 = a10 * x + a11 * y; var d = (x1-x0) * (x1-x0) + (y1-y0) * (y1-y0); var sfactor_sq = 1 / d - 0.25; if (sfactor_sq < 0) sfactor_sq = 0; var sfactor = Math.sqrt(sfactor_sq); if (sweep == large) sfactor = -sfactor; var xc = 0.5 * (x0 + x1) - sfactor * (y1-y0); var yc = 0.5 * (y0 + y1) + sfactor * (x1-x0); var th0 = Math.atan2(y0-yc, x0-xc); var th1 = Math.atan2(y1-yc, x1-xc); var th_arc = th1-th0; if (th_arc < 0 && sweep === 1){ th_arc += 2 * Math.PI; } else if (th_arc > 0 && sweep === 0) { th_arc -= 2 * Math.PI; } var segs = Math.ceil(Math.abs(th_arc / (Math.PI * 0.5 + 0.001))); var result = []; for (var i=0; i<segs; ++i) { var th2 = th0 + i * th_arc / segs; var th3 = th0 + (i+1) * th_arc / segs; result[i] = [xc, yc, th2, th3, rx, ry, sin_th, cos_th]; } return (segmentCache[key] = result); } function bezier(params) { var key = join.call(params); if (bezierCache[key]) { return bezierCache[key]; } var cx = params[0], cy = params[1], th0 = params[2], th1 = params[3], rx = params[4], ry = params[5], sin_th = params[6], cos_th = params[7]; var a00 = cos_th * rx; var a01 = -sin_th * ry; var a10 = sin_th * rx; var a11 = cos_th * ry; var cos_th0 = Math.cos(th0); var sin_th0 = Math.sin(th0); var cos_th1 = Math.cos(th1); var sin_th1 = Math.sin(th1); var th_half = 0.5 * (th1 - th0); var sin_th_h2 = Math.sin(th_half * 0.5); var t = (8/3) * sin_th_h2 * sin_th_h2 / Math.sin(th_half); var x1 = cx + cos_th0 - t * sin_th0; var y1 = cy + sin_th0 + t * cos_th0; var x3 = cx + cos_th1; var y3 = cy + sin_th1; var x2 = x3 + t * sin_th1; var y2 = y3 - t * cos_th1; return (bezierCache[key] = [ a00 * x1 + a01 * y1, a10 * x1 + a11 * y1, a00 * x2 + a01 * y2, a10 * x2 + a11 * y2, a00 * x3 + a01 * y3, a10 * x3 + a11 * y3 ]); } var temp = ['l', 0, 0, 0, 0, 0, 0, 0]; function scale(current, s) { var c = (temp[0] = current[0]); if (c === 'a' || c === 'A') { temp[1] = s * current[1]; temp[2] = s * current[2]; temp[6] = s * current[6]; temp[7] = s * current[7]; } else { for (var i=1, n=current.length; i<n; ++i) { temp[i] = s * current[i]; } } return temp; } function pathRender(context, path, l, t, s) { var current, // current instruction previous = null, x = 0, // current x y = 0, // current y controlX = 0, // current control point x controlY = 0, // current control point y tempX, tempY, tempControlX, tempControlY; if (l == null) l = 0; if (t == null) t = 0; if (s == null) s = 1; if (context.beginPath) context.beginPath(); for (var i=0, len=path.length; i<len; ++i) { current = path[i]; if (s !== 1) current = scale(current, s); switch (current[0]) { // first letter case 'l': // lineto, relative x += current[1]; y += current[2]; context.lineTo(x + l, y + t); break; case 'L': // lineto, absolute x = current[1]; y = current[2]; context.lineTo(x + l, y + t); break; case 'h': // horizontal lineto, relative x += current[1]; context.lineTo(x + l, y + t); break; case 'H': // horizontal lineto, absolute x = current[1]; context.lineTo(x + l, y + t); break; case 'v': // vertical lineto, relative y += current[1]; context.lineTo(x + l, y + t); break; case 'V': // verical lineto, absolute y = current[1]; context.lineTo(x + l, y + t); break; case 'm': // moveTo, relative x += current[1]; y += current[2]; context.moveTo(x + l, y + t); break; case 'M': // moveTo, absolute x = current[1]; y = current[2]; context.moveTo(x + l, y + t); break; case 'c': // bezierCurveTo, relative tempX = x + current[5]; tempY = y + current[6]; controlX = x + current[3]; controlY = y + current[4]; context.bezierCurveTo( x + current[1] + l, // x1 y + current[2] + t, // y1 controlX + l, // x2 controlY + t, // y2 tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'C': // bezierCurveTo, absolute x = current[5]; y = current[6]; controlX = current[3]; controlY = current[4]; context.bezierCurveTo( current[1] + l, current[2] + t, controlX + l, controlY + t, x + l, y + t ); break; case 's': // shorthand cubic bezierCurveTo, relative // transform to absolute x,y tempX = x + current[3]; tempY = y + current[4]; // calculate reflection of previous control points controlX = 2 * x - controlX; controlY = 2 * y - controlY; context.bezierCurveTo( controlX + l, controlY + t, x + current[1] + l, y + current[2] + t, tempX + l, tempY + t ); // set control point to 2nd one of this command // the first control point is assumed to be the reflection of // the second control point on the previous command relative // to the current point. controlX = x + current[1]; controlY = y + current[2]; x = tempX; y = tempY; break; case 'S': // shorthand cubic bezierCurveTo, absolute tempX = current[3]; tempY = current[4]; // calculate reflection of previous control points controlX = 2*x - controlX; controlY = 2*y - controlY; context.bezierCurveTo( controlX + l, controlY + t, current[1] + l, current[2] + t, tempX + l, tempY + t ); x = tempX; y = tempY; // set control point to 2nd one of this command // the first control point is assumed to be the reflection of // the second control point on the previous command relative // to the current point. controlX = current[1]; controlY = current[2]; break; case 'q': // quadraticCurveTo, relative // transform to absolute x,y tempX = x + current[3]; tempY = y + current[4]; controlX = x + current[1]; controlY = y + current[2]; context.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'Q': // quadraticCurveTo, absolute tempX = current[3]; tempY = current[4]; context.quadraticCurveTo( current[1] + l, current[2] + t, tempX + l, tempY + t ); x = tempX; y = tempY; controlX = current[1]; controlY = current[2]; break; case 't': // shorthand quadraticCurveTo, relative // transform to absolute x,y tempX = x + current[1]; tempY = y + current[2]; if (previous[0].match(/[QqTt]/) === null) { // If there is no previous command or if the previous command was not a Q, q, T or t, // assume the control point is coincident with the current point controlX = x; controlY = y; } else if (previous[0] === 't') { // calculate reflection of previous control points for t controlX = 2 * x - tempControlX; controlY = 2 * y - tempControlY; } else if (previous[0] === 'q') { // calculate reflection of previous control points for q controlX = 2 * x - controlX; controlY = 2 * y - controlY; } tempControlX = controlX; tempControlY = controlY; context.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; controlX = x + current[1]; controlY = y + current[2]; break; case 'T': tempX = current[1]; tempY = current[2]; // calculate reflection of previous control points controlX = 2 * x - controlX; controlY = 2 * y - controlY; context.quadraticCurveTo( controlX + l, controlY + t, tempX + l, tempY + t ); x = tempX; y = tempY; break; case 'a': drawArc(context, x + l, y + t, [ current[1], current[2], current[3], current[4], current[5], current[6] + x + l, current[7] + y + t ]); x += current[6]; y += current[7]; break; case 'A': drawArc(context, x + l, y + t, [ current[1], current[2], current[3], current[4], current[5], current[6] + l, current[7] + t ]); x = current[6]; y = current[7]; break; case 'z': case 'Z': context.closePath(); break; } previous = current; } } function drawArc(context, x, y, coords) { var seg = segments( coords[5], // end x coords[6], // end y coords[0], // radius x coords[1], // radius y coords[3], // large flag coords[4], // sweep flag coords[2], // rotation x, y ); for (var i=0; i<seg.length; ++i) { var bez = bezier(seg[i]); context.bezierCurveTo(bez[0], bez[1], bez[2], bez[3], bez[4], bez[5]); } } var tau$2 = 2 * Math.PI; var halfSqrt3 = Math.sqrt(3) / 2; var builtins = { 'circle': { draw: function(context, size) { var r = Math.sqrt(size) / 2; context.moveTo(r, 0); context.arc(0, 0, r, 0, tau$2); } }, 'cross': { draw: function(context, size) { var r = Math.sqrt(size) / 2, s = r / 2.5; context.moveTo(-r, -s); context.lineTo(-r, s); context.lineTo(-s, s); context.lineTo(-s, r); context.lineTo(s, r); context.lineTo(s, s); context.lineTo(r, s); context.lineTo(r, -s); context.lineTo(s, -s); context.lineTo(s, -r); context.lineTo(-s, -r); context.lineTo(-s, -s); context.closePath(); } }, 'diamond': { draw: function(context, size) { var r = Math.sqrt(size) / 2; context.moveTo(-r, 0); context.lineTo(0, -r); context.lineTo(r, 0); context.lineTo(0, r); context.closePath(); } }, 'square': { draw: function(context, size) { var w = Math.sqrt(size), x = -w / 2; context.rect(x, x, w, w); } }, 'triangle-up': { draw: function(context, size) { var r = Math.sqrt(size) / 2, h = halfSqrt3 * r; context.moveTo(0, -h); context.lineTo(-r, h); context.lineTo(r, h); context.closePath(); } }, 'triangle-down': { draw: function(context, size) { var r = Math.sqrt(size) / 2, h = halfSqrt3 * r; context.moveTo(0, h); context.lineTo(-r, -h); context.lineTo(r, -h); context.closePath(); } }, 'triangle-right': { draw: function(context, size) { var r = Math.sqrt(size) / 2, h = halfSqrt3 * r; context.moveTo(h, 0); context.lineTo(-h, -r); context.lineTo(-h, r); context.closePath(); } }, 'triangle-left': { draw: function(context, size) { var r = Math.sqrt(size) / 2, h = halfSqrt3 * r; context.moveTo(-h, 0); context.lineTo(h, -r); context.lineTo(h, r); context.closePath(); } } }; function symbols$1(_) { return builtins.hasOwnProperty(_) ? builtins[_] : customSymbol(_); } var custom = {}; function customSymbol(path) { if (!custom.hasOwnProperty(path)) { var parsed = pathParse(path); custom[path] = { draw: function(context, size) { pathRender(context, parsed, 0, 0, Math.sqrt(size)); } }; } return custom[path]; } function rectangleX(d) { return d.x; } function rectangleY(d) { return d.y; } function rectangleWidth(d) { return d.width; } function rectangleHeight(d) { return d.height; } function constant$3(_) { return function() { return _; }; } function vg_rect() { var x = rectangleX, y = rectangleY, width = rectangleWidth, height = rectangleHeight, cornerRadius = constant$3(0), context = null; function rectangle(_, x0, y0) { var buffer, x1 = x0 != null ? x0 : +x.call(this, _), y1 = y0 != null ? y0 : +y.call(this, _), w = +width.call(this, _), h = +height.call(this, _), cr = +cornerRadius.call(this, _); if (!context) context = buffer = path(); if (cr <= 0) { context.rect(x1, y1, w, h); } else { var x2 = x1 + w, y2 = y1 + h; context.moveTo(x1 + cr, y1); context.lineTo(x2 - cr, y1); context.quadraticCurveTo(x2, y1, x2, y1 + cr); context.lineTo(x2, y2 - cr); context.quadraticCurveTo(x2, y2, x2 - cr, y2); context.lineTo(x1 + cr, y2); context.quadraticCurveTo(x1, y2, x1, y2 - cr); context.lineTo(x1, y1 + cr); context.quadraticCurveTo(x1, y1, x1 + cr, y1); context.closePath(); } if (buffer) return context = null, buffer + '' || null; } rectangle.x = function(_) { return arguments.length ? (x = typeof _ === 'function' ? _ : constant$3(+_), rectangle) : x; }; rectangle.y = function(_) { return arguments.length ? (y = typeof _ === 'function' ? _ : constant$3(+_), rectangle) : y; }; rectangle.width = function(_) { return arguments.length ? (width = typeof _ === 'function' ? _ : constant$3(+_), rectangle) : width; }; rectangle.height = function(_) { return arguments.length ? (height = typeof _ === 'function' ? _ : constant$3(+_), rectangle) : height; }; rectangle.cornerRadius = function(_) { return arguments.length ? (cornerRadius = typeof _ === 'function' ? _ : constant$3(+_), rectangle) : cornerRadius; }; rectangle.context = function(_) { return arguments.length ? (context = _ == null ? null : _, rectangle) : context; }; return rectangle; } var pi$2 = Math.PI; function vg_trail() { var x, y, size, defined, context = null, ready, x1, y1, r1; function point(x2, y2, w2) { var r2 = w2 / 2; if (ready) { // get normal vector var ux = y1 - y2, uy = x2 - x1, ud = Math.sqrt(ux * ux + uy * uy), rx = (ux /= ud) * r1, ry = (uy /= ud) * r1, t = Math.atan2(uy, ux); // draw segment context.moveTo(x1 - rx, y1 - ry); context.lineTo(x2 - ux * r2, y2 - uy * r2); context.arc(x2, y2, r2, t - pi$2, t); context.lineTo(x1 + rx, y1 + ry); context.arc(x1, y1, r1, t, t + pi$2); context.closePath(); } else { ready = 1; } x1 = x2, y1 = y2, r1 = r2; } function trail(data) { var i, n = data.length, d, defined0 = false, buffer; if (context == null) context = buffer = path(); for (i = 0; i <= n; ++i) { if (!(i < n && defined(d = data[i], i, data)) === defined0) { if (defined0 = !defined0) ready = 0; } if (defined0) point(+x(d, i, data), +y(d, i, data), +size(d, i, data)); } if (buffer) return context = null, buffer + '' || null; } trail.x = function(_) { return arguments.length ? (x = _, trail) : x; }; trail.y = function(_) { return arguments.length ? (y = _, trail) : y; }; trail.size = function(_) { return arguments.length ? (size = _, trail) : size; }; trail.defined = function(_) { return arguments.length ? (defined = _, trail) : defined; }; trail.context = function(_) { return arguments.length ? (_ == null ? context = null : context = _, trail) : context; }; return trail; } function x(item) { return item.x || 0; } function y(item) { return item.y || 0; } function w(item) { return item.width || 0; } function wh(item) { return item.width || item.height || 1; } function h(item) { return item.height || 0; } function xw(item) { return (item.x || 0) + (item.width || 0); } function yh(item) { return (item.y || 0) + (item.height || 0); } function cr(item) { return item.cornerRadius || 0; } function pa(item) { return item.padAngle || 0; } function def(item) { return !(item.defined === false); } function size(item) { return item.size == null ? 64 : item.size; } function type$1(item) { return symbols$1(item.shape || 'circle'); } var arcShape = d3_arc().cornerRadius(cr).padAngle(pa); var areavShape = area$1().x(x).y1(y).y0(yh).defined(def); var areahShape = area$1().y(y).x1(x).x0(xw).defined(def); var lineShape = line$1().x(x).y(y).defined(def); var trailShape = vg_trail().x(x).y(y).defined(def).size(wh); var rectShape = vg_rect().x(x).y(y).width(w).height(h).cornerRadius(cr); var symbolShape = d3_symbol().type(type$1).size(size); function arc$1(context, item) { return arcShape.context(context)(item); } function area(context, items) { var item = items[0], interp = item.interpolate || 'linear'; return (interp === 'trail' ? trailShape : (item.orient === 'horizontal' ? areahShape : areavShape) .curve(curves(interp, item.orient, item.tension)) ).context(context)(items); } function shape(context, item) { return (item.mark.shape || item.shape) .context(context)(item); } function line(context, items) { var item = items[0], interp = item.interpolate || 'linear'; return lineShape.curve(curves(interp, item.orient, item.tension)) .context(context)(items); } function rectangle(context, item, x, y) { return rectShape.context(context)(item, x, y); } function symbol(context, item) { return symbolShape.context(context)(item); } function boundStroke(bounds, item) { if (item.stroke && item.opacity !== 0 && item.stokeOpacity !== 0) { bounds.expand(item.strokeWidth != null ? +item.strokeWidth : 1); } return bounds; } var bounds; var tau$3 = Math.PI * 2; var halfPi$1 = Math.PI / 2; function context(_) { return bounds = _, context; } function noop$3() {} function add$1(x, y) { bounds.add(x, y); } context.beginPath = noop$3; context.closePath = noop$3; context.moveTo = add$1; context.lineTo = add$1; context.rect = function(x, y, w, h) { add$1(x, y); add$1(x + w, y + h); }; context.quadraticCurveTo = function(x1, y1, x2, y2) { add$1(x1, y1); add$1(x2, y2); }; context.bezierCurveTo = function(x1, y1, x2, y2, x3, y3) { add$1(x1, y1); add$1(x2, y2); add$1(x3, y3); }; context.arc = function(cx, cy, r, sa, ea, ccw) { if (r === tau$3) { add$1(cx - r, cy - r); add$1(cx + r, cy + r); return; } var xmin = Infinity, xmax = -Infinity, ymin = Infinity, ymax = -Infinity, s, i, x, y; function update(a) { x = r * Math.cos(a); y = r * Math.sin(a); if (x < xmin) xmin = x; if (x > xmax) xmax = x; if (y < ymin) ymin = y; if (y > ymax) ymax = y; } update(sa); update(ea); if (ccw) { s = ea - (ea % halfPi$1) for (i=0; i<4 && s>sa; ++i, s-=halfPi$1) update(s); } else { s = sa - (sa % halfPi$1); for (i=0; i<4 && s<ea; ++i, s+=halfPi$1) update(s); } add$1(cx + xmin, cy + ymin); add$1(cx + xmax, cy + ymax); }; function gradient(context, gradient, bounds) { var w = bounds.width(), h = bounds.height(), x1 = bounds.x1 + gradient.x1 * w, y1 = bounds.y1 + gradient.y1 * h, x2 = bounds.x1 + gradient.x2 * w, y2 = bounds.y1 + gradient.y2 * h, stop = gradient.stops, i = 0, n = stop.length, linearGradient = context.createLinearGradient(x1, y1, x2, y2); for (; i<n; ++i) { linearGradient.addColorStop(stop[i].offset, stop[i].color); } return linearGradient; } function color(context, item, value) { return (value.id) ? gradient(context, value, item.bounds) : value; } function fill(context, item, opacity) { opacity *= (item.fillOpacity==null ? 1 : item.fillOpacity); if (opacity > 0) { context.globalAlpha = opacity; context.fillStyle = color(context, item, item.fill); return true; } else { return false; } } var Empty$1 = []; function stroke(context, item, opacity) { var lw = (lw = item.strokeWidth) != null ? lw : 1, lc; if (lw <= 0) return false; opacity *= (item.strokeOpacity==null ? 1 : item.strokeOpacity); if (opacity > 0) { context.globalAlpha = opacity; context.strokeStyle = color(context, item, item.stroke); context.lineWidth = lw; context.lineCap = (lc = item.strokeCap) != null ? lc : 'butt'; if (context.setLineDash) { context.setLineDash(item.strokeDash || Empty$1); context.lineDashOffset = item.strokeDashOffset || 0; } return true; } else { return false; } } function compare$1(a, b) { return a.zindex - b.zindex || a.index - b.index; } function zorder(scene) { if (!scene.zdirty) return scene.zitems; var items = scene.items, output = [], item, i, n; for (i=0, n=items.length; i<n; ++i) { item = items[i]; item.index = i; if (item.zindex) output.push(item); } scene.zdirty = false; return scene.zitems = output.sort(compare$1); } function visit(scene, visitor) { var items = scene.items, i, n; if (!items || !items.length) return; var zitems = zorder(scene); if (zitems && zitems.length) { for (i=0, n=items.length; i<n; ++i) { if (!items[i].zindex) visitor(items[i]); } items = zitems; } for (i=0, n=items.length; i<n; ++i) { visitor(items[i]); } } function pickVisit(scene, visitor) { var items = scene.items, hit, i; if (!items || !items.length) return null; var zitems = zorder(scene); if (zitems && zitems.length) items = zitems; for (i=items.length; --i >= 0;) { if (hit = visitor(items[i])) return hit; } if (items === zitems) { for (items=scene.items, i=items.length; --i >= 0;) { if (!items[i].zindex) { if (hit = visitor(items[i])) return hit; } } } return null; } function drawAll(path) { return function(context, scene, bounds) { visit(scene, function(item) { if (!bounds || bounds.intersects(item.bounds)) { drawPath(path, context, item, item); } }); }; } function drawOne(path) { return function(context, scene, bounds) { if (scene.items.length && (!bounds || bounds.intersects(scene.bounds))) { drawPath(path, context, scene.items[0], scene.items); } }; } function drawPath(path, context, item, items) { var opacity = item.opacity == null ? 1 : item.opacity; if (opacity === 0) return; if (path(context, items)) return; if (item.fill && fill(context, item, opacity)) { context.fill(); } if (item.stroke && stroke(context, item, opacity)) { context.stroke(); } } var trueFunc = function() { return true; }; function pick(test) { if (!test) test = trueFunc; return function(context, scene, x, y, gx, gy) { if (context.pixelRatio > 1) { x *= context.pixelRatio; y *= context.pixelRatio; } return pickVisit(scene, function(item) { var b = item.bounds; // first hit test against bounding box if ((b && !b.contains(gx, gy)) || !b) return; // if in bounding box, perform more careful test if (test(context, item, x, y, gx, gy)) return item; }); }; } function hitPath(path, filled) { return function(context, o, x, y) { var item = Array.isArray(o) ? o[0] : o, fill = (filled == null) ? item.fill : filled, stroke = item.stroke && context.isPointInStroke, lw, lc; if (stroke) { lw = item.strokeWidth; lc = item.strokeCap; context.lineWidth = lw != null ? lw : 1; context.lineCap = lc != null ? lc : 'butt'; } return path(context, o) ? false : (fill && context.isPointInPath(x, y)) || (stroke && context.isPointInStroke(x, y)); }; } function pickPath(path) { return pick(hitPath(path)); } function translate(x, y) { return 'translate(' + x + ',' + y + ')'; } function translateItem(item) { return translate(item.x || 0, item.y || 0); } function markItemPath(type, shape) { function attr(emit, item) { emit('transform', translateItem(item)); emit('d', shape(null, item)); } function bound(bounds, item) { shape(context(bounds), item); return boundStroke(bounds, item) .translate(item.x || 0, item.y || 0); } function draw(context, item) { var x = item.x || 0, y = item.y || 0; context.translate(x, y); context.beginPath(); shape(context, item); context.translate(-x, -y); } return { type: type, tag: 'path', nested: false, attr: attr, bound: bound, draw: drawAll(draw), pick: pickPath(draw) }; } var arc = markItemPath('arc', arc$1); function markMultiItemPath(type, shape) { function attr(emit, item) { var items = item.mark.items; if (items.length) emit('d', shape(null, items)); } function bound(bounds, mark) { var items = mark.items; return items.length === 0 ? bounds : (shape(context(bounds), items), boundStroke(bounds, items[0])); } function draw(context, items) { context.beginPath(); shape(context, items); } var hit = hitPath(draw); function pick(context, scene, x, y, gx, gy) { var items = scene.items, b = scene.bounds; if (!items || !items.length || b && !b.contains(gx, gy)) { return null; } if (context.pixelRatio > 1) { x *= context.pixelRatio; y *= context.pixelRatio; } return hit(context, items, x, y) ? items[0] : null; } return { type: type, tag: 'path', nested: true, attr: attr, bound: bound, draw: drawOne(draw), pick: pick }; } var area$2 = markMultiItemPath('area', area); function attr(emit, item, renderer) { var id = null, defs, c; emit('transform', translateItem(item)); if (item.clip) { defs = renderer._defs; id = item.clip_id || (item.clip_id = 'clip' + defs.clip_id++); c = defs.clipping[id] || (defs.clipping[id] = {id: id}); c.width = item.width || 0; c.height = item.height || 0; } emit('clip-path', id ? ('url(#' + id + ')') : null); } function background(emit, item) { var offset = item.stroke ? 0.5 : 0; emit('class', 'background'); emit('d', rectangle(null, item, offset, offset)); } function bound(bounds, group) { if (!group.clip && group.items) { var items = group.items; for (var j=0, m=items.length; j<m; ++j) { bounds.union(items[j].bounds); } } if (group.clip || group.width || group.height) { boundStroke( bounds.add(0, 0).add(group.width || 0, group.height || 0), group ); } return bounds.translate(group.x || 0, group.y || 0); } function draw(context, scene, bounds) { var renderer = this; visit(scene, function(group) { var gx = group.x || 0, gy = group.y || 0, w = group.width || 0, h = group.height || 0, offset, opacity; // setup graphics context context.save(); context.translate(gx, gy); // draw group background if (group.stroke || group.fill) { opacity = group.opacity == null ? 1 : group.opacity; if (opacity > 0) { context.beginPath(); offset = group.stroke ? 0.5 : 0; rectangle(context, group, offset, offset); if (group.fill && fill(context, group, opacity)) { context.fill(); } if (group.stroke && stroke(context, group, opacity)) { context.stroke(); } } } // set clip and bounds if (group.clip) { context.beginPath(); context.rect(0, 0, w, h); context.clip(); } if (bounds) bounds.translate(-gx, -gy); // draw group contents visit(group, function(item) { renderer.draw(context, item, bounds); }); // restore graphics context if (bounds) bounds.translate(gx, gy); context.restore(); }); } function pick$1(context, scene, x, y, gx, gy) { if (scene.bounds && !scene.bounds.contains(gx, gy) || !scene.items) { return null; } var handler = this; return pickVisit(scene, function(group) { var hit, dx, dy, b; // first hit test against bounding box // if a group is clipped, that should be handled by the bounds check. b = group.bounds; if (b && !b.contains(gx, gy)) return; // passed bounds check, so test sub-groups dx = (group.x || 0); dy = (group.y || 0); context.save(); context.translate(dx, dy); dx = gx - dx; dy = gy - dy; hit = pickVisit(group, function(mark) { return (mark.interactive !== false || mark.marktype === 'group') ? handler.pick(mark, x, y, dx, dy) : null; }); context.restore(); if (hit) return hit; hit = scene.interactive !== false && (group.fill || group.stroke) && dx >= 0 && dx <= group.width && dy >= 0 && dy <= group.height; return hit ? group : null; }); } var group = { type: 'group', tag: 'g', nested: false, attr: attr, bound: bound, draw: draw, pick: pick$1, background: background }; function getImage(item, renderer) { var image = item.image; if (!image || image.url !== item.url) { image = {loaded: false, width: 0, height: 0}; renderer.loadImage(item.url).then(function(image) { item.image = image; item.image.url = item.url; }); } return image; } function imageXOffset(align, w) { return align === 'center' ? w / 2 : align === 'right' ? w : 0; } function imageYOffset(baseline, h) { return baseline === 'middle' ? h / 2 : baseline === 'bottom' ? h : 0; } function attr$1(emit, item, renderer) { var image = getImage(item, renderer), x = item.x || 0, y = item.y || 0, w = item.width || image.width || 0, h = item.height || image.height || 0; x -= imageXOffset(item.align, w); y -= imageYOffset(item.baseline, h); emit('href', image.src || '', 'http://www.w3.org/1999/xlink', 'xlink:href'); emit('transform', translate(x, y)); emit('width', w); emit('height', h); } function bound$1(bounds, item) { var image = item.image, x = item.x || 0, y = item.y || 0, w = item.width || (image && image.width) || 0, h = item.height || (image && image.height) || 0; x -= imageXOffset(item.align, w); y -= imageYOffset(item.baseline, h); return bounds.set(x, y, x + w, y + h); } function draw$1(context, scene, bounds) { var renderer = this; visit(scene, function(item) { if (bounds && !bounds.intersects(item.bounds)) return; // bounds check var image = getImage(item, renderer), x = item.x || 0, y = item.y || 0, w = item.width || image.width || 0, h = item.height || image.height || 0, opacity; x -= imageXOffset(item.align, w); y -= imageYOffset(item.baseline, h); if (image.loaded) { context.globalAlpha = (opacity = item.opacity) != null ? opacity : 1; context.drawImage(image, x, y, w, h); } }); } var image = { type: 'image', tag: 'image', nested: false, attr: attr$1, bound: bound$1, draw: draw$1, pick: pick() }; var line$2 = markMultiItemPath('line', line); function attr$2(emit, item) { emit('transform', translateItem(item)); emit('d', item.path); } function path$1(context, item) { var path = item.path; if (path == null) return true; var cache = item.pathCache; if (!cache || cache.path !== path) { (item.pathCache = cache = pathParse(path)).path = path; } pathRender(context, cache, item.x, item.y); } function bound$2(bounds, item) { return path$1(context(bounds), item) ? bounds.set(0, 0, 0, 0) : boundStroke(bounds, item); } var path$2 = { type: 'path', tag: 'path', nested: false, attr: attr$2, bound: bound$2, draw: drawAll(path$1), pick: pickPath(path$1) }; function attr$3(emit, item) { emit('d', rectangle(null, item)); } function bound$3(bounds, item) { var x, y; return boundStroke(bounds.set( x = item.x || 0, y = item.y || 0, (x + item.width) || 0, (y + item.height) || 0 ), item); } function draw$2(context, item) { context.beginPath(); rectangle(context, item); } var rect = { type: 'rect', tag: 'path', nested: false, attr: attr$3, bound: bound$3, draw: drawAll(draw$2), pick: pickPath(draw$2) }; function attr$4(emit, item) { emit('transform', translateItem(item)); emit('x2', item.x2 != null ? item.x2 - (item.x||0) : 0); emit('y2', item.y2 != null ? item.y2 - (item.y||0) : 0); } function bound$4(bounds, item) { var x1, y1; return boundStroke(bounds.set( x1 = item.x || 0, y1 = item.y || 0, item.x2 != null ? item.x2 : x1, item.y2 != null ? item.y2 : y1 ), item); } function path$3(context, item, opacity) { var x1, y1, x2, y2; if (item.stroke && stroke(context, item, opacity)) { x1 = item.x || 0; y1 = item.y || 0; x2 = item.x2 != null ? item.x2 : x1; y2 = item.y2 != null ? item.y2 : y1; context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); return true; } return false; } function draw$3(context, scene, bounds) { visit(scene, function(item) { if (bounds && !bounds.intersects(item.bounds)) return; // bounds check var opacity = item.opacity == null ? 1 : item.opacity; if (opacity && path$3(context, item, opacity)) { context.stroke(); } }); } function hit(context, item, x, y) { if (!context.isPointInStroke) return false; return path$3(context, item, 1) && context.isPointInStroke(x, y); } var rule = { type: 'rule', tag: 'line', nested: false, attr: attr$4, bound: bound$4, draw: draw$3, pick: pick(hit) }; var shape$1 = markItemPath('shape', shape); var symbol$1 = markItemPath('symbol', symbol); var context$1; function estimateWidth(item) { // make dumb, simple estimate if no canvas is available return ~~(0.8 * textValue(item).length * height(item)); } function measureWidth(item) { // measure text width if canvas is available context$1.font = font(item); return context$1.measureText(textValue(item.text)).width; } function height(item) { return item.fontSize != null ? item.fontSize : 11; } var textMetrics = { height: height, measureWidth: measureWidth, estimateWidth: estimateWidth, width: (context$1 = Canvas$1(1, 1)) ? (context$1 = context$1.getContext('2d'), measureWidth) : estimateWidth }; function textValue(s) { return s != null ? String(s) : ''; } function font(item, quote) { var font = item.font; if (quote && font) { font = String(font).replace(/\"/g, '\''); } return '' + (item.fontStyle ? item.fontStyle + ' ' : '') + (item.fontVariant ? item.fontVariant + ' ' : '') + (item.fontWeight ? item.fontWeight + ' ' : '') + height(item) + 'px ' + (font || 'sans-serif'); } function offset(item) { // perform our own font baseline calculation // why? not all browsers support SVG 1.1 'alignment-baseline' :( var baseline = item.baseline, h = height(item); return Math.round( baseline === 'top' ? 0.93*h : baseline === 'middle' ? 0.30*h : baseline === 'bottom' ? -0.21*h : 0 ); } var textAlign = { 'left': 'start', 'center': 'middle', 'right': 'end' }; var tempBounds = new Bounds(); function attr$5(emit, item) { var dx = item.dx || 0, dy = (item.dy || 0) + offset(item), x = item.x || 0, y = item.y || 0, a = item.angle || 0, r = item.radius || 0, t; if (r) { t = (item.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } emit('text-anchor', textAlign[item.align] || 'start'); if (a) { t = translate(x, y) + ' rotate('+a+')'; if (dx || dy) t += ' ' + translate(dx, dy); } else { t = translate(x + dx, y + dy); } emit('transform', t); } function bound$5(bounds, item, noRotate) { var h = textMetrics.height(item), a = item.align, r = item.radius || 0, x = item.x || 0, y = item.y || 0, dx = item.dx || 0, dy = (item.dy || 0) + offset(item) - Math.round(0.8*h), // use 4/5 offset w, t; if (r) { t = (item.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } // horizontal alignment w = textMetrics.width(item); if (a === 'center') { dx -= (w / 2); } else if (a === 'right') { dx -= w; } else { // left by default, do nothing } bounds.set(dx+=x, dy+=y, dx+w, dy+h); if (item.angle && !noRotate) { bounds.rotate(item.angle*Math.PI/180, x, y); } return bounds.expand(noRotate ? 0 : 1); } function draw$4(context, scene, bounds) { visit(scene, function(item) { var opacity, x, y, r, t, str; if (bounds && !bounds.intersects(item.bounds)) return; // bounds check if (!(str = textValue(item.text))) return; // get text string opacity = item.opacity == null ? 1 : item.opacity; if (opacity === 0) return; context.font = font(item); context.textAlign = item.align || 'left'; x = item.x || 0; y = item.y || 0; if ((r = item.radius)) { t = (item.theta || 0) - Math.PI/2; x += r * Math.cos(t); y += r * Math.sin(t); } if (item.angle) { context.save(); context.translate(x, y); context.rotate(item.angle * Math.PI/180); x = y = 0; // reset x, y } x += (item.dx || 0); y += (item.dy || 0) + offset(item); if (item.fill && fill(context, item, opacity)) { context.fillText(str, x, y); } if (item.stroke && stroke(context, item, opacity)) { context.strokeText(str, x, y); } if (item.angle) context.restore(); }); } function hit$1(context, item, x, y, gx, gy) { if (item.fontSize <= 0) return false; if (!item.angle) return true; // bounds sufficient if no rotation // project point into space of unrotated bounds var b = bound$5(tempBounds, item, true), a = -item.angle * Math.PI / 180, cos = Math.cos(a), sin = Math.sin(a), ix = item.x, iy = item.y, px = cos*gx - sin*gy + (ix - ix*cos + iy*sin), py = sin*gx + cos*gy + (iy - ix*sin - iy*cos); return b.contains(px, py); } var text$1 = { type: 'text', tag: 'text', nested: false, attr: attr$5, bound: bound$5, draw: draw$4, pick: pick(hit$1) }; var Marks = { arc: arc, area: area$2, group: group, image: image, line: line$2, path: path$2, rect: rect, rule: rule, shape: shape$1, symbol: symbol$1, text: text$1 }; function boundItem(item, func, opt) { var type = Marks[item.mark.marktype], bound = func || type.bound; if (type.nested) item = item.mark; var curr = item.bounds, prev = item.bounds_prev || (item.bounds_prev = new Bounds()); if (curr) { prev.clear().union(curr); curr.clear(); } else { item.bounds = new Bounds(); } bound(item.bounds, item, opt); if (!curr) prev.clear().union(item.bounds); return item.bounds; } var DUMMY = {mark: null}; function boundMark(mark, bounds, opt) { var type = Marks[mark.marktype], bound = type.bound, items = mark.items, hasItems = items && items.length, i, n, item, b; if (type.nested) { item = hasItems ? items[0] : (DUMMY.mark = mark, DUMMY); // no items, fake it b = boundItem(item, bound, opt); bounds = bounds && bounds.union(b) || b; return bounds; } bounds = bounds || mark.bounds && mark.bounds.clear() || new Bounds(); if (hasItems) { for (i=0, n=items.length; i<n; ++i) { bounds.union(boundItem(items[i], bound, opt)); } } return mark.bounds = bounds; } var keys$1 = [ 'marktype', 'name', 'role', 'interactive', 'clip', 'items', 'zindex', 'x', 'y', 'width', 'height', 'align', 'baseline', // layout 'fill', 'fillOpacity', 'opacity', // fill 'stroke', 'strokeOpacity', 'strokeWidth', 'strokeCap', // stroke 'strokeDash', 'strokeDashOffset', // stroke dash 'startAngle', 'endAngle', 'innerRadius', 'outerRadius', // arc 'cornerRadius', 'padAngle', // arc, rect 'interpolate', 'tension', 'orient', 'defined', // area, line 'url', // image 'path', // path 'x2', 'y2', // rule 'size', 'shape', // symbol 'text', 'angle', 'theta', 'radius', 'dx', 'dy', // text 'font', 'fontSize', 'fontWeight', 'fontStyle', 'fontVariant' // font ]; function toJSON(scene, indent) { return JSON.stringify(scene, keys$1, indent); } function fromJSON(json) { var scene = (typeof json === 'string' ? JSON.parse(json) : json); return initialize(scene); } function initialize(scene) { var type = scene.marktype, items = scene.items, parent, i, n; if (items) { for (i=0, n=items.length; i<n; ++i) { parent = type ? 'mark' : 'group'; items[i][parent] = scene; if (items[i].zindex) items[i][parent].zdirty = true; if ('group' === (type || parent)) initialize(items[i]); } } if (type) boundMark(scene); return scene; } function Scenegraph(scene) { if (arguments.length) { this.root = fromJSON(scene); } else { this.root = createMark({ marktype: 'group', name: 'root', role: 'frame' }); this.root.items = [new GroupItem(this.root)]; } } var prototype$34 = Scenegraph.prototype; prototype$34.toJSON = function(indent) { return toJSON(this.root, indent || 0); }; prototype$34.mark = function(scenepath, markdef) { var markpath = scenepath.marks, itempath = scenepath.items, item = this.root.items[0], mark, index, i, n; try { for (i=0, n=markpath.length; i<n; ++i) { mark = item.items[markpath[i]]; if (!mark) break; index = itempath[i] || 0; item = mark.items[index] || mark.items[mark.items.length-1]; } if (!mark) { mark = createMark(markdef, item); item.items[markpath[i]] = mark; if (mark.zindex) mark.group.zdirty = true; return mark; } throw n; } catch (err) { error$1('Invalid scenegraph path: ' + JSON.stringify(scenepath)); } }; function error$1(msg) { throw Error(msg); } function createMark(def, group) { return { bounds: new Bounds(), bounds_prev: new Bounds(), clip: !!def.clip, group: group, interactive: def.interactive === false ? false : true, items: [], marktype: def.marktype, name: def.name || undefined, role: def.role || undefined, zindex: def.zindex || 0 }; } function Handler() { this._active = null; this._handlers = {}; } var prototype$35 = Handler.prototype; prototype$35.initialize = function(el, origin, obj) { this._el = el; this._obj = obj || null; return this.origin(origin); }; prototype$35.element = function() { return this._el; }; prototype$35.origin = function(origin) { this._origin = origin || [0, 0]; return this; }; prototype$35.scene = function(scene) { if (!arguments.length) return this._scene; this._scene = scene; return this; }; // add an event handler // subclasses should override prototype$35.on = function(/*type, handler*/) {}; // remove an event handler // subclasses should override prototype$35.off = function(/*type, handler*/) {}; // return an array with all registered event handlers prototype$35.handlers = function() { var h = this._handlers, a = [], k; for (k in h) { a.push.apply(a, h[k]); } return a; }; prototype$35.eventName = function(name) { var i = name.indexOf('.'); return i < 0 ? name : name.slice(0,i); }; /** * Create a new Renderer instance. * @param {object} [imageLoader] - Optional loader instance for * image URL sanitization. If not specified, a standard loader * instance will be generated. * @constructor */ function Renderer(imageLoader) { this._el = null; this._bgcolor = null; this._loader = new ImageLoader(imageLoader); } var prototype$36 = Renderer.prototype; /** * Initialize a new Renderer instance. * @param {DOMElement} el - The containing DOM element for the display. * @param {number} width - The width of the display, in pixels. * @param {number} height - The height of the display, in pixels. * @param {Array<number>} origin - The origin of the display, in pixels. * The coordinate system will be translated to this point. * @return {Renderer} - This renderer instance; */ prototype$36.initialize = function(el, width, height, origin) { this._el = el; return this.resize(width, height, origin); }; /** * Returns the parent container element for a visualization. * @return {DOMElement} - The containing DOM element. */ prototype$36.element = function() { return this._el; }; /** * Returns the scene element (e.g., canvas or SVG) of the visualization * Subclasses must override if the first child is not the scene element. * @return {DOMElement} - The scene (e.g., canvas or SVG) element. */ prototype$36.scene = function() { return this._el && this._el.firstChild; }; /** * Get / set the background color. */ prototype$36.background = function(bgcolor) { if (arguments.length === 0) return this._bgcolor; this._bgcolor = bgcolor; return this; }; /** * Resize the display. * @param {number} width - The new width of the display, in pixels. * @param {number} height - The new height of the display, in pixels. * @param {Array<number>} origin - The new origin of the display, in pixels. * The coordinate system will be translated to this point. * @return {Renderer} - This renderer instance; */ prototype$36.resize = function(width, height, origin) { this._width = width; this._height = height; this._origin = origin || [0, 0]; return this; }; /** * Render an input scenegraph, potentially with a set of dirty items. * This method will perform an immediate rendering with available resources. * The renderer may also need to perform image loading to perform a complete * render. This process can lead to asynchronous re-rendering of the scene * after this method returns. To receive notification when rendering is * complete, use the renderAsync method instead. * @param {object} scene - The root mark of a scenegraph to render. * @param {Array<object>} [items] - An optional array of dirty items. * If provided, the renderer may optimize the redraw of these items. * @return {Renderer} - This renderer instance. */ prototype$36.render = function(scene, items) { var r = this; // bind arguments into a render call, and cache it // this function may be subsequently called for async redraw r._call = function() { r._render(scene, items); }; // invoke the renderer r._call(); // clear the cached call for garbage collection // async redraws will stash their own copy r._call = null; return r; }; /** * Internal rendering method. Renderer subclasses should override this * method to actually perform rendering. * @param {object} scene - The root mark of a scenegraph to render. * @param {Array<object>} [items] - An optional array of dirty items. * If provided, the renderer may optimize the redraw of these items. */ prototype$36._render = function(/*scene, items*/) { // subclasses to override }; /** * Asynchronous rendering method. Similar to render, but returns a Promise * that resolves when all rendering is completed. Sometimes a renderer must * perform image loading to get a complete rendering. The returned * Promise will not resolve until this process completes. * @param {object} scene - The root mark of a scenegraph to render. * @param {Array<object>} [items] - An optional array of dirty items. * If provided, the renderer may optimize the redraw of these items. * @return {Promise} - A Promise that resolves when rendering is complete. */ prototype$36.renderAsync = function(scene, items) { var r = this.render(scene, items); return this._ready ? this._ready.then(function() { return r; }) : Promise.resolve(r); }; /** * Requests an image to include in the rendered scene. * This method proxies a call to ImageLoader.loadImage, but also tracks * image loading progress and invokes a re-render once complete. * @return {Image} - The requested image instance. * The image content may not be loaded yet. */ prototype$36.loadImage = function(uri) { var r = this, p = r._loader.loadImage(uri); if (!r._ready) { // re-render the scene when image loading completes var call = r._call; r._ready = r._loader.ready() .then(function(redraw) { if (redraw) call(); r._ready = null; }); } return p; }; function point$4(event, el) { var rect = el.getBoundingClientRect(); return [ event.clientX - rect.left - (el.clientLeft || 0), event.clientY - rect.top - (el.clientTop || 0) ]; } // create a new DOM element function create(doc, tag, ns) { return ns ? doc.createElementNS(ns, tag) : doc.createElement(tag); } // find first child element with matching tag function find(el, tag) { tag = tag.toLowerCase(); var nodes = el.childNodes, i = 0, n = nodes.length; for (; i<n; ++i) if (nodes[i].tagName.toLowerCase() === tag) { return nodes[i]; } } // retrieve child element at given index // create & insert if doesn't exist or if tags do not match function child(el, index, tag, ns) { var a = el.childNodes[index], b; if (!a || a.tagName.toLowerCase() !== tag.toLowerCase()) { b = a || null; a = create(el.ownerDocument, tag, ns); el.insertBefore(a, b); } return a; } // remove all child elements at or above the given index function clear(el, index) { var nodes = el.childNodes, curr = nodes.length; while (curr > index) el.removeChild(nodes[--curr]); return el; } // generate css class name for mark function cssClass(mark) { return 'mark-' + mark.marktype + (mark.role ? ' role-' + mark.role : '') + (mark.name ? ' ' + mark.name : ''); } function CanvasHandler() { Handler.call(this); this._down = null; this._touch = null; this._first = true; } var prototype$37 = inherits$1(CanvasHandler, Handler); prototype$37.initialize = function(el, origin, obj) { // add event listeners var canvas = this._canvas = el && find(el, 'canvas'); if (canvas) { var that = this; this.events.forEach(function(type) { canvas.addEventListener(type, function(evt) { if (prototype$37[type]) { prototype$37[type].call(that, evt); } else { that.fire(type, evt); } }); }); } return Handler.prototype.initialize.call(this, el, origin, obj); }; prototype$37.canvas = function() { return this._canvas; }; // retrieve the current canvas context prototype$37.context = function() { return this._canvas.getContext('2d'); }; // supported events prototype$37.events = [ 'keydown', 'keypress', 'keyup', 'dragenter', 'dragleave', 'dragover', 'mousedown', 'mouseup', 'mousemove', 'mouseout', 'mouseover', 'click', 'dblclick', 'wheel', 'mousewheel', 'touchstart', 'touchmove', 'touchend' ]; // to keep firefox happy prototype$37.DOMMouseScroll = function(evt) { this.fire('mousewheel', evt); }; function move(moveEvent, overEvent, outEvent) { return function(evt) { var a = this._active, p = this.pickEvent(evt); if (p === a) { // active item and picked item are the same this.fire(moveEvent, evt); // fire move } else { // active item and picked item are different if (!a || !a.exit) { // fire out for prior active item // suppress if active item was removed from scene this.fire(outEvent, evt); } this._active = p; // set new active item this.fire(overEvent, evt); // fire over for new active item this.fire(moveEvent, evt); // fire move for new active item } }; } function inactive(type) { return function(evt) { this.fire(type, evt); this._active = null; }; } prototype$37.mousemove = move('mousemove', 'mouseover', 'mouseout'); prototype$37.dragover = move('dragover', 'dragenter', 'dragleave'); prototype$37.mouseout = inactive('mouseout'); prototype$37.dragleave = inactive('dragleave'); prototype$37.mousedown = function(evt) { this._down = this._active; this.fire('mousedown', evt); }; prototype$37.click = function(evt) { if (this._down === this._active) { this.fire('click', evt); this._down = null; } }; prototype$37.touchstart = function(evt) { this._touch = this.pickEvent(evt.changedTouches[0]); if (this._first) { this._active = this._touch; this._first = false; } this.fire('touchstart', evt, true); }; prototype$37.touchmove = function(evt) { this.fire('touchmove', evt, true); }; prototype$37.touchend = function(evt) { this.fire('touchend', evt, true); this._touch = null; }; // fire an event prototype$37.fire = function(type, evt, touch) { var a = touch ? this._touch : this._active, h = this._handlers[type], i, len; if (h) { evt.vegaType = type; for (i=0, len=h.length; i<len; ++i) { h[i].handler.call(this._obj, evt, a); } } }; // add an event handler prototype$37.on = function(type, handler) { var name = this.eventName(type), h = this._handlers; (h[name] || (h[name] = [])).push({ type: type, handler: handler }); return this; }; // remove an event handler prototype$37.off = function(type, handler) { var name = this.eventName(type), h = this._handlers[name], i; if (!h) return; for (i=h.length; --i>=0;) { if (h[i].type !== type) continue; if (!handler || h[i].handler === handler) h.splice(i, 1); } return this; }; prototype$37.pickEvent = function(evt) { var p = point$4(evt, this._canvas), o = this._origin; return this.pick(this._scene, p[0], p[1], p[0] - o[0], p[1] - o[1]); }; // find the scenegraph item at the current mouse position // x, y -- the absolute x, y mouse coordinates on the canvas element // gx, gy -- the relative coordinates within the current group prototype$37.pick = function(scene, x, y, gx, gy) { var g = this.context(), mark = Marks[scene.marktype]; return mark.pick.call(this, g, scene, x, y, gx, gy); }; var devicePixelRatio = typeof window !== 'undefined' ? window.devicePixelRatio || 1 : 1; function resize(canvas, width, height, origin) { var scale = typeof HTMLElement !== 'undefined' && canvas instanceof HTMLElement && canvas.parentNode != null; var context = canvas.getContext('2d'), ratio = scale ? devicePixelRatio : 1; canvas.width = width * ratio; canvas.height = height * ratio; if (ratio !== 1) { canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; } context.pixelRatio = ratio; context.setTransform( ratio, 0, 0, ratio, ratio * origin[0], ratio * origin[1] ); return canvas; } function CanvasRenderer(imageLoader) { Renderer.call(this, imageLoader); this._redraw = false; } var prototype$38 = inherits$1(CanvasRenderer, Renderer); var base = Renderer.prototype; var tempBounds$1 = new Bounds(); prototype$38.initialize = function(el, width, height, origin) { this._canvas = Canvas$1(1, 1); // instantiate a small canvas if (el) { clear(el, 0).appendChild(this._canvas); this._canvas.setAttribute('class', 'marks'); } // this method will invoke resize to size the canvas appropriately return base.initialize.call(this, el, width, height, origin); }; prototype$38.resize = function(width, height, origin) { base.resize.call(this, width, height, origin); resize(this._canvas, this._width, this._height, this._origin); return this._redraw = true, this; }; prototype$38.canvas = function() { return this._canvas; }; prototype$38.context = function() { return this._canvas ? this._canvas.getContext('2d') : null; }; function clipToBounds(g, items) { var b = new Bounds(), i, n, item, mark, group; for (i=0, n=items.length; i<n; ++i) { item = items[i]; mark = item.mark; group = mark.group; item = Marks[mark.marktype].nested ? mark : item; b.union(translate$1(item.bounds, group)); if (item.bounds_prev) { b.union(translate$1(item.bounds_prev, group)); } } b.round(); g.beginPath(); g.rect(b.x1, b.y1, b.width(), b.height()); g.clip(); return b; } function translate$1(bounds, group) { if (group == null) return bounds; var b = tempBounds$1.clear().union(bounds); for (; group != null; group = group.mark.group) { b.translate(group.x || 0, group.y || 0); } return b; } prototype$38._render = function(scene, items) { var g = this.context(), o = this._origin, w = this._width, h = this._height, b; // setup g.save(); b = (!items || this._redraw) ? (this._redraw = false, null) : clipToBounds(g, items); this.clear(-o[0], -o[1], w, h); // render this.draw(g, scene, b); // takedown g.restore(); return this; }; prototype$38.draw = function(ctx, scene, bounds) { var mark = Marks[scene.marktype]; mark.draw.call(this, ctx, scene, bounds); }; prototype$38.clear = function(x, y, w, h) { var g = this.context(); g.clearRect(x, y, w, h); if (this._bgcolor != null) { g.fillStyle = this._bgcolor; g.fillRect(x, y, w, h); } }; function SVGHandler() { Handler.call(this); } var prototype$39 = inherits$1(SVGHandler, Handler); prototype$39.initialize = function(el, origin, obj) { this._svg = el && find(el, 'svg'); return Handler.prototype.initialize.call(this, el, origin, obj); }; prototype$39.svg = function() { return this._svg; }; // wrap an event listener for the SVG DOM prototype$39.listener = function(handler) { var that = this; return function(evt) { var target = evt.target, item = target.__data__; evt.vegaType = evt.type; item = Array.isArray(item) ? item[0] : item; handler.call(that._obj, evt, item); }; }; // add an event handler prototype$39.on = function(type, handler) { var name = this.eventName(type), h = this._handlers, x = { type: type, handler: handler, listener: this.listener(handler) }; (h[name] || (h[name] = [])).push(x); if (this._svg) { this._svg.addEventListener(name, x.listener); } return this; }; // remove an event handler prototype$39.off = function(type, handler) { var name = this.eventName(type), svg = this._svg, h = this._handlers[name], i; if (!h) return; for (i=h.length; --i>=0;) { if (h[i].type === type && !handler || h[i].handler === handler) { if (this._svg) { svg.removeEventListener(name, h[i].listener); } h.splice(i, 1); } } return this; }; // generate string for an opening xml tag // tag: the name of the xml tag // attr: hash of attribute name-value pairs to include // raw: additional raw string to include in tag markup function openTag(tag, attr, raw) { var s = '<' + tag, key, val; if (attr) { for (key in attr) { val = attr[key]; if (val != null) { s += ' ' + key + '="' + val + '"'; } } } if (raw) s += ' ' + raw; return s + '>'; } // generate string for closing xml tag // tag: the name of the xml tag function closeTag(tag) { return '</' + tag + '>'; } var metadata = { 'version': '1.1', 'xmlns': 'http://www.w3.org/2000/svg', 'xmlns:xlink': 'http://www.w3.org/1999/xlink' }; var styles = { 'fill': 'fill', 'fillOpacity': 'fill-opacity', 'stroke': 'stroke', 'strokeWidth': 'stroke-width', 'strokeOpacity': 'stroke-opacity', 'strokeCap': 'stroke-linecap', 'strokeDash': 'stroke-dasharray', 'strokeDashOffset': 'stroke-dashoffset', 'opacity': 'opacity' }; var styleProperties = Object.keys(styles); var ns = metadata.xmlns; function SVGRenderer(imageLoader) { Renderer.call(this, imageLoader); this._dirtyID = 0; this._svg = null; this._root = null; this._defs = null; } var prototype$40 = inherits$1(SVGRenderer, Renderer); var base$1 = Renderer.prototype; prototype$40.initialize = function(el, width, height, padding) { if (el) { this._svg = child(el, 0, 'svg', ns); this._svg.setAttribute('class', 'marks'); clear(el, 1); // set the svg root group this._root = child(this._svg, 0, 'g', ns); clear(this._svg, 1); } // create the svg definitions cache this._defs = { clip_id: 1, gradient: {}, clipping: {} }; // set background color if defined this.background(this._bgcolor); return base$1.initialize.call(this, el, width, height, padding); }; prototype$40.background = function(bgcolor) { if (arguments.length && this._svg) { this._svg.style.setProperty('background-color', bgcolor); } return base$1.background.apply(this, arguments); }; prototype$40.resize = function(width, height, origin) { base$1.resize.call(this, width, height, origin); if (this._svg) { this._svg.setAttribute('width', this._width); this._svg.setAttribute('height', this._height); this._root.setAttribute('transform', 'translate(' + this._origin + ')'); } return this; }; prototype$40.svg = function() { if (!this._svg) return null; var attr = { 'class': 'marks', 'width': this._width, 'height': this._height }; for (var key in metadata) { attr[key] = metadata[key]; } return openTag('svg', attr) + this._svg.innerHTML + closeTag('svg'); }; // -- Render entry point -- prototype$40._render = function(scene, items) { // perform spot updates and re-render markup if (this._dirtyCheck(items)) { if (this._dirtyAll) this._resetDefs(); this.draw(this._root, scene); clear(this._root, 1); } this.updateDefs(); return this; }; // -- Manage SVG definitions ('defs') block -- prototype$40.updateDefs = function() { var svg = this._svg, defs = this._defs, el = defs.el, index = 0, id; for (id in defs.gradient) { if (!el) defs.el = (el = child(svg, 0, 'defs', ns)); updateGradient(el, defs.gradient[id], index++); } for (id in defs.clipping) { if (!el) defs.el = (el = child(svg, 0, 'defs', ns)); updateClipping(el, defs.clipping[id], index++); } // clean-up if (el) { if (index === 0) { svg.removeChild(el); defs.el = null; } else { clear(el, index); } } }; function updateGradient(el, grad, index) { var i, n, stop; el = child(el, index, 'linearGradient', ns); el.setAttribute('id', grad.id); el.setAttribute('x1', grad.x1); el.setAttribute('x2', grad.x2); el.setAttribute('y1', grad.y1); el.setAttribute('y2', grad.y2); for (i=0, n=grad.stops.length; i<n; ++i) { stop = child(el, i, 'stop', ns); stop.setAttribute('offset', grad.stops[i].offset); stop.setAttribute('stop-color', grad.stops[i].color); } clear(el, i); } function updateClipping(el, clip, index) { var rect; el = child(el, index, 'clipPath', ns); el.setAttribute('id', clip.id); rect = child(el, 0, 'rect', ns); rect.setAttribute('x', 0); rect.setAttribute('y', 0); rect.setAttribute('width', clip.width); rect.setAttribute('height', clip.height); } prototype$40._resetDefs = function() { var def = this._defs; def.clip_id = 1; def.gradient = {}; def.clipping = {}; }; // -- Manage rendering of items marked as dirty -- prototype$40.isDirty = function(item) { return this._dirtyAll || !item._svg || item.dirty === this._dirtyID; }; prototype$40._dirtyCheck = function(items) { this._dirtyAll = true; if (!items) return true; var id = ++this._dirtyID, item, mark, type, mdef, i, n, o; for (i=0, n=items.length; i<n; ++i) { item = items[i]; mark = item.mark; if (mark.marktype !== type) { // memoize mark instance lookup type = mark.marktype; mdef = Marks[type]; } if (mark.zdirty && mark.dirty !== id) { this._dirtyAll = false; mark.dirty = id; dirtyParents(mark.group, id); } if (item.exit) { // EXIT if (mdef.nested && mark.items.length) { // if nested mark with remaining points, update instead o = mark.items[0]; if (o._svg) this._update(mdef, o._svg, o); } else if (item._svg) { // otherwise remove from DOM item._svg.remove(); } item._svg = null; continue; } item = (mdef.nested ? mark.items[0] : item); if (item._update === id) continue; // already visited if (!item._svg || !item._svg.ownerSVGElement) { // ENTER this._dirtyAll = false; dirtyParents(item, id); } else { // IN-PLACE UPDATE this._update(mdef, item._svg, item); } item._update = id; } return !this._dirtyAll; }; function dirtyParents(item, id) { for (; item && item.dirty !== id; item=item.mark.group) { item.dirty = id; if (item.mark && item.mark.dirty !== id) { item.mark.dirty = id; } else return; } } // -- Construct & maintain scenegraph to SVG mapping --- // Draw a mark container. prototype$40.draw = function(el, scene, prev) { if (!this.isDirty(scene)) return scene._svg; var renderer = this, mdef = Marks[scene.marktype], events = scene.interactive === false ? 'none' : null, isGroup = mdef.tag === 'g', sibling = null, i = 0, parent; parent = bind(scene, el, prev, 'g'); parent.setAttribute('class', cssClass(scene)); if (!isGroup && events) { parent.style.setProperty('pointer-events', events); } function process(item) { var dirty = renderer.isDirty(item), node = bind(item, parent, sibling, mdef.tag); if (dirty) { renderer._update(mdef, node, item); if (isGroup) recurse(renderer, node, item); } sibling = node; ++i; } if (mdef.nested) { if (scene.items.length) process(scene.items[0]); } else { visit(scene, process); } clear(parent, i); return parent; }; // Recursively process group contents. function recurse(renderer, el, group) { var prev = el.firstChild, // group background idx = 0; visit(group, function(item) { prev = renderer.draw(el, item, prev); ++idx; }); // remove any extraneous DOM elements clear(el, 1 + idx); } // Bind a scenegraph item to an SVG DOM element. // Create new SVG elements as needed. function bind(item, el, sibling, tag) { var node = item._svg, doc; // create a new dom node if needed if (!node) { doc = el.ownerDocument; node = create(doc, tag, ns); item._svg = node; if (item.mark) { node.__data__ = item; node.__values__ = {fill: 'default'}; // create background element if (tag === 'g') { var bg = create(doc, 'path', ns); bg.setAttribute('class', 'background'); node.appendChild(bg); bg.__data__ = item; } } } if (doc || node.previousSibling !== sibling) { el.insertBefore(node, sibling ? sibling.nextSibling : el.firstChild); } return node; } // -- Set attributes & styles on SVG elements --- var element = null; var values$1 = null; // temp var for current values hash // Extra configuration for certain mark types var mark_extras = { group: function(mdef, el, item) { element = el.childNodes[0]; values$1 = el.__values__; // use parent's values hash mdef.background(emit, item, this); var value = item.mark.interactive === false ? 'none' : null; if (value !== values$1.events) { element.style.setProperty('pointer-events', value); values$1.events = value; } }, text: function(mdef, el, item) { var str = textValue(item.text); if (str !== values$1.text) { el.textContent = str; values$1.text = str; } str = font(item); if (str !== values$1.font) { el.style.setProperty('font', str); values$1.font = str; } } }; prototype$40._update = function(mdef, el, item) { // set dom element and values cache // provides access to emit method element = el; values$1 = el.__values__; // apply svg attributes mdef.attr(emit, item, this); // some marks need special treatment var extra = mark_extras[mdef.type]; if (extra) extra(mdef, el, item); // apply svg css styles // note: element may be modified by 'extra' method this.style(element, item); }; function emit(name, value, ns) { // early exit if value is unchanged if (value === values$1[name]) return; if (value != null) { // if value is provided, update DOM attribute if (ns) { element.setAttributeNS(ns, name, value); } else { element.setAttribute(name, value); } } else { // else remove DOM attribute if (ns) { element.removeAttributeNS(ns, name); } else { element.removeAttribute(name); } } // note current value for future comparison values$1[name] = value; } prototype$40.style = function(el, o) { if (o == null) return; var i, n, prop, name, value; for (i=0, n=styleProperties.length; i<n; ++i) { prop = styleProperties[i]; value = o[prop]; if (value === values$1[prop]) continue; name = styles[prop]; if (value == null) { if (name === 'fill') { el.style.setProperty(name, 'none'); } else { el.style.removeProperty(name); } } else { if (value.id) { // ensure definition is included this._defs.gradient[value.id] = value; value = 'url(' + href() + '#' + value.id + ')'; } el.style.setProperty(name, value+''); } values$1[prop] = value; } }; function href() { return typeof window !== 'undefined' ? window.location.href : ''; } function SVGStringRenderer(imageLoader) { Renderer.call(this, imageLoader); this._text = { head: '', root: '', foot: '', defs: '', body: '' }; this._defs = { clip_id: 1, gradient: {}, clipping: {} }; } var prototype$41 = inherits$1(SVGStringRenderer, Renderer); var base$2 = Renderer.prototype; prototype$41.resize = function(width, height, origin) { base$2.resize.call(this, width, height, origin); var o = this._origin, t = this._text; var attr = { 'class': 'marks', 'width': this._width, 'height': this._height }; for (var key in metadata) { attr[key] = metadata[key]; } t.head = openTag('svg', attr); t.root = openTag('g', { transform: 'translate(' + o + ')' }); t.foot = closeTag('g') + closeTag('svg'); return this; }; prototype$41.svg = function() { var t = this._text; return t.head + t.defs + t.root + t.body + t.foot; }; prototype$41._render = function(scene) { this._text.body = this.mark(scene); this._text.defs = this.buildDefs(); return this; }; prototype$41.reset = function() { this._defs.clip_id = 0; return this; }; prototype$41.buildDefs = function() { var all = this._defs, defs = '', i, id, def, stops; for (id in all.gradient) { def = all.gradient[id]; stops = def.stops; defs += openTag('linearGradient', { id: id, x1: def.x1, x2: def.x2, y1: def.y1, y2: def.y2 }); for (i=0; i<stops.length; ++i) { defs += openTag('stop', { offset: stops[i].offset, 'stop-color': stops[i].color }) + closeTag('stop'); } defs += closeTag('linearGradient'); } for (id in all.clipping) { def = all.clipping[id]; defs += openTag('clipPath', {id: id}); defs += openTag('rect', { x: 0, y: 0, width: def.width, height: def.height }) + closeTag('rect'); defs += closeTag('clipPath'); } return (defs.length > 0) ? openTag('defs') + defs + closeTag('defs') : ''; }; var object$1; function emit$1(name, value, ns, prefixed) { object$1[prefixed || name] = value; } prototype$41.attributes = function(attr, item) { object$1 = {}; attr(emit$1, item, this); return object$1; }; prototype$41.mark = function(scene) { var renderer = this, mdef = Marks[scene.marktype], tag = mdef.tag, defs = this._defs, str = '', style; if (tag !== 'g' && scene.interactive === false) { style = 'style="pointer-events: none;"'; } // render opening group tag str += openTag('g', { 'class': cssClass(scene) }, style); // render contained elements function process(item) { style = (tag !== 'g') ? applyStyles(item, scene, tag, defs) : null; str += openTag(tag, renderer.attributes(mdef.attr, item), style); if (tag === 'text') { str += escape_text(textValue(item.text)); } else if (tag === 'g') { str += openTag('path', renderer.attributes(mdef.background, item), applyStyles(item, scene, 'bgrect', defs)) + closeTag('path'); str += renderer.markGroup(item); } str += closeTag(tag); } if (mdef.nested) { if (scene.items && scene.items.length) process(scene.items[0]); } else { visit(scene, process); } // render closing group tag return str + closeTag('g'); }; prototype$41.markGroup = function(scene) { var renderer = this, str = ''; visit(scene, function(item) { str += renderer.mark(item); }); return str; }; function applyStyles(o, mark, tag, defs) { if (o == null) return ''; var i, n, prop, name, value, s = ''; if (tag === 'bgrect' && mark.interactive === false) { s += 'pointer-events: none;'; } if (tag === 'text') { s += 'font: ' + font(o) + ';'; } for (i=0, n=styleProperties.length; i<n; ++i) { prop = styleProperties[i]; name = styles[prop]; value = o[prop]; if (value == null) { if (name === 'fill') { s += (s.length ? ' ' : '') + 'fill: none;'; } } else { if (value.id) { // ensure definition is included defs.gradient[value.id] = value; value = 'url(#' + value.id + ')'; } s += (s.length ? ' ' : '') + name + ': ' + value + ';'; } } return s ? 'style="' + s + '"' : null; } function escape_text(s) { return s.replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } function scaleGradient(scale, p0, p1, count) { var gradient = Gradient(p0, p1), stops = scale.domain(), min = stops[0], max = stops[stops.length-1], i, n, fraction; if (scale.type !== 'linear' && scale.ticks) { stops = scale.ticks(+count || 15); if (min !== stops[0]) stops.unshift(min); if (max !== stops[stops.length-1]) stops.push(max); } fraction = scale.range ? scale.copy().domain([min, max]).range([0, 1]) : function(_) { return (_ - min) / (max - min); }; for (i=0, n=stops.length; i<n; ++i) { gradient.stop(fraction(stops[i]), scale(stops[i])); } return gradient; } var array$2 = Array.prototype; var map$2 = array$2.map; var slice$2 = array$2.slice; var implicit = {name: "implicit"}; function ordinal(range) { var index = map$1(), domain = [], unknown = implicit; range = range == null ? [] : slice$2.call(range); function scale(d) { var key = d + "", i = index.get(key); if (!i) { if (unknown !== implicit) return unknown; index.set(key, i = domain.push(d)); } return range[(i - 1) % range.length]; } scale.domain = function(_) { if (!arguments.length) return domain.slice(); domain = [], index = map$1(); var i = -1, n = _.length, d, key; while (++i < n) if (!index.has(key = (d = _[i]) + "")) index.set(key, domain.push(d)); return scale; }; scale.range = function(_) { return arguments.length ? (range = slice$2.call(_), scale) : range.slice(); }; scale.unknown = function(_) { return arguments.length ? (unknown = _, scale) : unknown; }; scale.copy = function() { return ordinal() .domain(domain) .range(range) .unknown(unknown); }; return scale; } function define(constructor, factory, prototype) { constructor.prototype = factory.prototype = prototype; prototype.constructor = constructor; } function extend$1(parent, definition) { var prototype = Object.create(parent.prototype); for (var key in definition) prototype[key] = definition[key]; return prototype; } function Color() {} var darker = 0.7; var brighter = 1 / darker; var reHex3 = /^#([0-9a-f]{3})$/; var reHex6 = /^#([0-9a-f]{6})$/; var reRgbInteger = /^rgb\(\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*\)$/; var reRgbPercent = /^rgb\(\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*\)$/; var reRgbaInteger = /^rgba\(\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+)\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var reRgbaPercent = /^rgba\(\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var reHslPercent = /^hsl\(\s*([-+]?\d+(?:\.\d+)?)\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*\)$/; var reHslaPercent = /^hsla\(\s*([-+]?\d+(?:\.\d+)?)\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)%\s*,\s*([-+]?\d+(?:\.\d+)?)\s*\)$/; var named = { aliceblue: 0xf0f8ff, antiquewhite: 0xfaebd7, aqua: 0x00ffff, aquamarine: 0x7fffd4, azure: 0xf0ffff, beige: 0xf5f5dc, bisque: 0xffe4c4, black: 0x000000, blanchedalmond: 0xffebcd, blue: 0x0000ff, blueviolet: 0x8a2be2, brown: 0xa52a2a, burlywood: 0xdeb887, cadetblue: 0x5f9ea0, chartreuse: 0x7fff00, chocolate: 0xd2691e, coral: 0xff7f50, cornflowerblue: 0x6495ed, cornsilk: 0xfff8dc, crimson: 0xdc143c, cyan: 0x00ffff, darkblue: 0x00008b, darkcyan: 0x008b8b, darkgoldenrod: 0xb8860b, darkgray: 0xa9a9a9, darkgreen: 0x006400, darkgrey: 0xa9a9a9, darkkhaki: 0xbdb76b, darkmagenta: 0x8b008b, darkolivegreen: 0x556b2f, darkorange: 0xff8c00, darkorchid: 0x9932cc, darkred: 0x8b0000, darksalmon: 0xe9967a, darkseagreen: 0x8fbc8f, darkslateblue: 0x483d8b, darkslategray: 0x2f4f4f, darkslategrey: 0x2f4f4f, darkturquoise: 0x00ced1, darkviolet: 0x9400d3, deeppink: 0xff1493, deepskyblue: 0x00bfff, dimgray: 0x696969, dimgrey: 0x696969, dodgerblue: 0x1e90ff, firebrick: 0xb22222, floralwhite: 0xfffaf0, forestgreen: 0x228b22, fuchsia: 0xff00ff, gainsboro: 0xdcdcdc, ghostwhite: 0xf8f8ff, gold: 0xffd700, goldenrod: 0xdaa520, gray: 0x808080, green: 0x008000, greenyellow: 0xadff2f, grey: 0x808080, honeydew: 0xf0fff0, hotpink: 0xff69b4, indianred: 0xcd5c5c, indigo: 0x4b0082, ivory: 0xfffff0, khaki: 0xf0e68c, lavender: 0xe6e6fa, lavenderblush: 0xfff0f5, lawngreen: 0x7cfc00, lemonchiffon: 0xfffacd, lightblue: 0xadd8e6, lightcoral: 0xf08080, lightcyan: 0xe0ffff, lightgoldenrodyellow: 0xfafad2, lightgray: 0xd3d3d3, lightgreen: 0x90ee90, lightgrey: 0xd3d3d3, lightpink: 0xffb6c1, lightsalmon: 0xffa07a, lightseagreen: 0x20b2aa, lightskyblue: 0x87cefa, lightslategray: 0x778899, lightslategrey: 0x778899, lightsteelblue: 0xb0c4de, lightyellow: 0xffffe0, lime: 0x00ff00, limegreen: 0x32cd32, linen: 0xfaf0e6, magenta: 0xff00ff, maroon: 0x800000, mediumaquamarine: 0x66cdaa, mediumblue: 0x0000cd, mediumorchid: 0xba55d3, mediumpurple: 0x9370db, mediumseagreen: 0x3cb371, mediumslateblue: 0x7b68ee, mediumspringgreen: 0x00fa9a, mediumturquoise: 0x48d1cc, mediumvioletred: 0xc71585, midnightblue: 0x191970, mintcream: 0xf5fffa, mistyrose: 0xffe4e1, moccasin: 0xffe4b5, navajowhite: 0xffdead, navy: 0x000080, oldlace: 0xfdf5e6, olive: 0x808000, olivedrab: 0x6b8e23, orange: 0xffa500, orangered: 0xff4500, orchid: 0xda70d6, palegoldenrod: 0xeee8aa, palegreen: 0x98fb98, paleturquoise: 0xafeeee, palevioletred: 0xdb7093, papayawhip: 0xffefd5, peachpuff: 0xffdab9, peru: 0xcd853f, pink: 0xffc0cb, plum: 0xdda0dd, powderblue: 0xb0e0e6, purple: 0x800080, rebeccapurple: 0x663399, red: 0xff0000, rosybrown: 0xbc8f8f, royalblue: 0x4169e1, saddlebrown: 0x8b4513, salmon: 0xfa8072, sandybrown: 0xf4a460, seagreen: 0x2e8b57, seashell: 0xfff5ee, sienna: 0xa0522d, silver: 0xc0c0c0, skyblue: 0x87ceeb, slateblue: 0x6a5acd, slategray: 0x708090, slategrey: 0x708090, snow: 0xfffafa, springgreen: 0x00ff7f, steelblue: 0x4682b4, tan: 0xd2b48c, teal: 0x008080, thistle: 0xd8bfd8, tomato: 0xff6347, turquoise: 0x40e0d0, violet: 0xee82ee, wheat: 0xf5deb3, white: 0xffffff, whitesmoke: 0xf5f5f5, yellow: 0xffff00, yellowgreen: 0x9acd32 }; define(Color, color$1, { displayable: function() { return this.rgb().displayable(); }, toString: function() { return this.rgb() + ""; } }); function color$1(format) { var m; format = (format + "").trim().toLowerCase(); return (m = reHex3.exec(format)) ? (m = parseInt(m[1], 16), new Rgb((m >> 8 & 0xf) | (m >> 4 & 0x0f0), (m >> 4 & 0xf) | (m & 0xf0), ((m & 0xf) << 4) | (m & 0xf), 1)) // #f00 : (m = reHex6.exec(format)) ? rgbn(parseInt(m[1], 16)) // #ff0000 : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0) : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%) : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1) : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1) : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%) : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1) : named.hasOwnProperty(format) ? rgbn(named[format]) : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null; } function rgbn(n) { return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1); } function rgba(r, g, b, a) { if (a <= 0) r = g = b = NaN; return new Rgb(r, g, b, a); } function rgbConvert(o) { if (!(o instanceof Color)) o = color$1(o); if (!o) return new Rgb; o = o.rgb(); return new Rgb(o.r, o.g, o.b, o.opacity); } function rgb(r, g, b, opacity) { return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity); } function Rgb(r, g, b, opacity) { this.r = +r; this.g = +g; this.b = +b; this.opacity = +opacity; } define(Rgb, rgb, extend$1(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, rgb: function() { return this; }, displayable: function() { return (0 <= this.r && this.r <= 255) && (0 <= this.g && this.g <= 255) && (0 <= this.b && this.b <= 255) && (0 <= this.opacity && this.opacity <= 1); }, toString: function() { var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a)); return (a === 1 ? "rgb(" : "rgba(") + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.b) || 0)) + (a === 1 ? ")" : ", " + a + ")"); } })); function hsla(h, s, l, a) { if (a <= 0) h = s = l = NaN; else if (l <= 0 || l >= 1) h = s = NaN; else if (s <= 0) h = NaN; return new Hsl(h, s, l, a); } function hslConvert(o) { if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); if (!(o instanceof Color)) o = color$1(o); if (!o) return new Hsl; if (o instanceof Hsl) return o; o = o.rgb(); var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2; if (s) { if (r === max) h = (g - b) / s + (g < b) * 6; else if (g === max) h = (b - r) / s + 2; else h = (r - g) / s + 4; s /= l < 0.5 ? max + min : 2 - max - min; h *= 60; } else { s = l > 0 && l < 1 ? 0 : h; } return new Hsl(h, s, l, o.opacity); } function hsl(h, s, l, opacity) { return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity); } function Hsl(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } define(Hsl, hsl, extend$1(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, rgb: function() { var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2; return new Rgb( hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), hsl2rgb(h, m1, m2), hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), this.opacity ); }, displayable: function() { return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1); } })); /* From FvD 13.37, CSS Color Module Level 3 */ function hsl2rgb(h, m1, m2) { return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255; } var deg2rad = Math.PI / 180; var rad2deg = 180 / Math.PI; var Kn = 18; var Xn = 0.950470; var Yn = 1; var Zn = 1.088830; var t0$1 = 4 / 29; var t1$1 = 6 / 29; var t2 = 3 * t1$1 * t1$1; var t3 = t1$1 * t1$1 * t1$1; function labConvert(o) { if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity); if (o instanceof Hcl) { var h = o.h * deg2rad; return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity); } if (!(o instanceof Rgb)) o = rgbConvert(o); var b = rgb2xyz(o.r), a = rgb2xyz(o.g), l = rgb2xyz(o.b), x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn), y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn), z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn); return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity); } function lab(l, a, b, opacity) { return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity); } function Lab(l, a, b, opacity) { this.l = +l; this.a = +a; this.b = +b; this.opacity = +opacity; } define(Lab, lab, extend$1(Color, { brighter: function(k) { return new Lab(this.l + Kn * (k == null ? 1 : k), this.a, this.b, this.opacity); }, darker: function(k) { return new Lab(this.l - Kn * (k == null ? 1 : k), this.a, this.b, this.opacity); }, rgb: function() { var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200; y = Yn * lab2xyz(y); x = Xn * lab2xyz(x); z = Zn * lab2xyz(z); return new Rgb( xyz2rgb( 3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z), xyz2rgb( 0.0556434 * x - 0.2040259 * y + 1.0572252 * z), this.opacity ); } })); function xyz2lab(t) { return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0$1; } function lab2xyz(t) { return t > t1$1 ? t * t * t : t2 * (t - t0$1); } function xyz2rgb(x) { return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); } function rgb2xyz(x) { return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); } function hclConvert(o) { if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity); if (!(o instanceof Lab)) o = labConvert(o); var h = Math.atan2(o.b, o.a) * rad2deg; return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity); } function hcl(h, c, l, opacity) { return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity); } function Hcl(h, c, l, opacity) { this.h = +h; this.c = +c; this.l = +l; this.opacity = +opacity; } define(Hcl, hcl, extend$1(Color, { brighter: function(k) { return new Hcl(this.h, this.c, this.l + Kn * (k == null ? 1 : k), this.opacity); }, darker: function(k) { return new Hcl(this.h, this.c, this.l - Kn * (k == null ? 1 : k), this.opacity); }, rgb: function() { return labConvert(this).rgb(); } })); var A = -0.14861; var B = +1.78277; var C = -0.29227; var D = -0.90649; var E = +1.97294; var ED = E * D; var EB = E * B; var BC_DA = B * C - D * A; function cubehelixConvert(o) { if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity); if (!(o instanceof Rgb)) o = rgbConvert(o); var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k = (E * (g - l) - C * bl) / D, s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1 h = s ? Math.atan2(k, bl) * rad2deg - 120 : NaN; return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity); } function cubehelix(h, s, l, opacity) { return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity); } function Cubehelix(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } define(Cubehelix, cubehelix, extend$1(Color, { brighter: function(k) { k = k == null ? brighter : Math.pow(brighter, k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); }, darker: function(k) { k = k == null ? darker : Math.pow(darker, k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); }, rgb: function() { var h = isNaN(this.h) ? 0 : (this.h + 120) * deg2rad, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh = Math.cos(h), sinh = Math.sin(h); return new Rgb( 255 * (l + a * (A * cosh + B * sinh)), 255 * (l + a * (C * cosh + D * sinh)), 255 * (l + a * (E * cosh)), this.opacity ); } })); function basis(t1, v0, v1, v2, v3) { var t2 = t1 * t1, t3 = t2 * t1; return ((1 - 3 * t1 + 3 * t2 - t3) * v0 + (4 - 6 * t2 + 3 * t3) * v1 + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2 + t3 * v3) / 6; } function basis$1(values) { var n = values.length - 1; return function(t) { var i = t <= 0 ? (t = 0) : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1; return basis((t - i / n) * n, v0, v1, v2, v3); }; } function constant$4(x) { return function() { return x; }; } function linear$1(a, d) { return function(t) { return a + t * d; }; } function exponential(a, b, y) { return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) { return Math.pow(a + t * b, y); }; } function hue(a, b) { var d = b - a; return d ? linear$1(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant$4(isNaN(a) ? b : a); } function gamma(y) { return (y = +y) === 1 ? nogamma : function(a, b) { return b - a ? exponential(a, b, y) : constant$4(isNaN(a) ? b : a); }; } function nogamma(a, b) { var d = b - a; return d ? linear$1(a, d) : constant$4(isNaN(a) ? b : a); } var rgb$1 = (function rgbGamma(y) { var color = gamma(y); function rgb$$(start, end) { var r = color((start = rgb(start)).r, (end = rgb(end)).r), g = color(start.g, end.g), b = color(start.b, end.b), opacity = color(start.opacity, end.opacity); return function(t) { start.r = r(t); start.g = g(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } rgb$$.gamma = rgbGamma; return rgb$$; })(1); function rgbSpline(spline) { return function(colors) { var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color; for (i = 0; i < n; ++i) { color = rgb(colors[i]); r[i] = color.r || 0; g[i] = color.g || 0; b[i] = color.b || 0; } r = spline(r); g = spline(g); b = spline(b); color.opacity = 1; return function(t) { color.r = r(t); color.g = g(t); color.b = b(t); return color + ""; }; }; } var interpolateRgbBasis = rgbSpline(basis$1); function array$3(a, b) { var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = new Array(nb), c = new Array(nb), i; for (i = 0; i < na; ++i) x[i] = interpolateValue(a[i], b[i]); for (; i < nb; ++i) c[i] = b[i]; return function(t) { for (i = 0; i < na; ++i) c[i] = x[i](t); return c; }; } function date(a, b) { var d = new Date; return a = +a, b -= a, function(t) { return d.setTime(a + b * t), d; }; } function reinterpolate(a, b) { return a = +a, b -= a, function(t) { return a + b * t; }; } function object$2(a, b) { var i = {}, c = {}, k; if (a === null || typeof a !== "object") a = {}; if (b === null || typeof b !== "object") b = {}; for (k in b) { if (k in a) { i[k] = interpolateValue(a[k], b[k]); } else { c[k] = b[k]; } } return function(t) { for (k in i) c[k] = i[k](t); return c; }; } var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g; var reB = new RegExp(reA.source, "g"); function zero$1(b) { return function() { return b; }; } function one$1(b) { return function(t) { return b(t) + ""; }; } function string(a, b) { var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b am, // current match in a bm, // current match in b bs, // string preceding current number in b, if any i = -1, // index in s s = [], // string constants and placeholders q = []; // number interpolators // Coerce inputs to strings. a = a + "", b = b + ""; // Interpolate pairs of numbers in a & b. while ((am = reA.exec(a)) && (bm = reB.exec(b))) { if ((bs = bm.index) > bi) { // a string precedes the next number in b bs = b.slice(bi, bs); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match if (s[i]) s[i] += bm; // coalesce with previous string else s[++i] = bm; } else { // interpolate non-matching numbers s[++i] = null; q.push({i: i, x: reinterpolate(am, bm)}); } bi = reB.lastIndex; } // Add remains of b. if (bi < b.length) { bs = b.slice(bi); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } // Special optimization for only a single match. // Otherwise, interpolate each of the numbers and rejoin the string. return s.length < 2 ? (q[0] ? one$1(q[0].x) : zero$1(b)) : (b = q.length, function(t) { for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }); } function interpolateValue(a, b) { var t = typeof b, c; return b == null || t === "boolean" ? constant$4(b) : (t === "number" ? reinterpolate : t === "string" ? ((c = color$1(b)) ? (b = c, rgb$1) : string) : b instanceof color$1 ? rgb$1 : b instanceof Date ? date : Array.isArray(b) ? array$3 : isNaN(b) ? object$2 : reinterpolate)(a, b); } function interpolateRound(a, b) { return a = +a, b -= a, function(t) { return Math.round(a + b * t); }; } function cubehelix$1(hue) { return (function cubehelixGamma(y) { y = +y; function cubehelix$$(start, end) { var h = hue((start = cubehelix(start)).h, (end = cubehelix(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); return function(t) { start.h = h(t); start.s = s(t); start.l = l(Math.pow(t, y)); start.opacity = opacity(t); return start + ""; }; } cubehelix$$.gamma = cubehelixGamma; return cubehelix$$; })(1); } cubehelix$1(hue); var interpolateCubehelixLong = cubehelix$1(nogamma); function constant$5(x) { return function() { return x; }; } function number$2(x) { return +x; } var unit = [0, 1]; function deinterpolate(a, b) { return (b -= (a = +a)) ? function(x) { return (x - a) / b; } : constant$5(b); } function deinterpolateClamp(deinterpolate) { return function(a, b) { var d = deinterpolate(a = +a, b = +b); return function(x) { return x <= a ? 0 : x >= b ? 1 : d(x); }; }; } function reinterpolateClamp(reinterpolate) { return function(a, b) { var r = reinterpolate(a = +a, b = +b); return function(t) { return t <= 0 ? a : t >= 1 ? b : r(t); }; }; } function bimap(domain, range, deinterpolate, reinterpolate) { var d0 = domain[0], d1 = domain[1], r0 = range[0], r1 = range[1]; if (d1 < d0) d0 = deinterpolate(d1, d0), r0 = reinterpolate(r1, r0); else d0 = deinterpolate(d0, d1), r0 = reinterpolate(r0, r1); return function(x) { return r0(d0(x)); }; } function polymap(domain, range, deinterpolate, reinterpolate) { var j = Math.min(domain.length, range.length) - 1, d = new Array(j), r = new Array(j), i = -1; // Reverse descending domains. if (domain[j] < domain[0]) { domain = domain.slice().reverse(); range = range.slice().reverse(); } while (++i < j) { d[i] = deinterpolate(domain[i], domain[i + 1]); r[i] = reinterpolate(range[i], range[i + 1]); } return function(x) { var i = bisectRight(domain, x, 1, j) - 1; return r[i](d[i](x)); }; } function copy$1(source, target) { return target .domain(source.domain()) .range(source.range()) .interpolate(source.interpolate()) .clamp(source.clamp()); } // deinterpolate(a, b)(x) takes a domain value x in [a,b] and returns the corresponding parameter t in [0,1]. // reinterpolate(a, b)(t) takes a parameter t in [0,1] and returns the corresponding domain value x in [a,b]. function continuous(deinterpolate$$, reinterpolate) { var domain = unit, range = unit, interpolate = interpolateValue, clamp = false, piecewise, output, input; function rescale() { piecewise = Math.min(domain.length, range.length) > 2 ? polymap : bimap; output = input = null; return scale; } function scale(x) { return (output || (output = piecewise(domain, range, clamp ? deinterpolateClamp(deinterpolate$$) : deinterpolate$$, interpolate)))(+x); } scale.invert = function(y) { return (input || (input = piecewise(range, domain, deinterpolate, clamp ? reinterpolateClamp(reinterpolate) : reinterpolate)))(+y); }; scale.domain = function(_) { return arguments.length ? (domain = map$2.call(_, number$2), rescale()) : domain.slice(); }; scale.range = function(_) { return arguments.length ? (range = slice$2.call(_), rescale()) : range.slice(); }; scale.rangeRound = function(_) { return range = slice$2.call(_), interpolate = interpolateRound, rescale(); }; scale.clamp = function(_) { return arguments.length ? (clamp = !!_, rescale()) : clamp; }; scale.interpolate = function(_) { return arguments.length ? (interpolate = _, rescale()) : interpolate; }; return rescale(); } // Computes the decimal coefficient and exponent of the specified number x with // significant digits p, where x is positive and p is in [1, 21] or undefined. // For example, formatDecimal(1.23) returns ["123", 0]. function formatDecimal(x, p) { if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; // NaN, ±Infinity var i, coefficient = x.slice(0, i); // The string returned by toExponential either has the form \d\.\d+e[-+]\d+ // (e.g., 1.2e+3) or the form \de[-+]\d+ (e.g., 1e+3). return [ coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient, +x.slice(i + 1) ]; } function exponent(x) { return x = formatDecimal(Math.abs(x)), x ? x[1] : NaN; } function formatGroup(grouping, thousands) { return function(value, width) { var i = value.length, t = [], j = 0, g = grouping[0], length = 0; while (i > 0 && g > 0) { if (length + g + 1 > width) g = Math.max(1, width - length); t.push(value.substring(i -= g, i + g)); if ((length += g + 1) > width) break; g = grouping[j = (j + 1) % grouping.length]; } return t.reverse().join(thousands); }; } function formatDefault(x, p) { x = x.toPrecision(p); out: for (var n = x.length, i = 1, i0 = -1, i1; i < n; ++i) { switch (x[i]) { case ".": i0 = i1 = i; break; case "0": if (i0 === 0) i0 = i; i1 = i; break; case "e": break out; default: if (i0 > 0) i0 = 0; break; } } return i0 > 0 ? x.slice(0, i0) + x.slice(i1 + 1) : x; } var prefixExponent; function formatPrefixAuto(x, p) { var d = formatDecimal(x, p); if (!d) return x + ""; var coefficient = d[0], exponent = d[1], i = exponent - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent / 3))) * 3) + 1, n = coefficient.length; return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimal(x, Math.max(0, p + i - 1))[0]; // less than 1y! } function formatRounded(x, p) { var d = formatDecimal(x, p); if (!d) return x + ""; var coefficient = d[0], exponent = d[1]; return exponent < 0 ? "0." + new Array(-exponent).join("0") + coefficient : coefficient.length > exponent + 1 ? coefficient.slice(0, exponent + 1) + "." + coefficient.slice(exponent + 1) : coefficient + new Array(exponent - coefficient.length + 2).join("0"); } var formatTypes = { "": formatDefault, "%": function(x, p) { return (x * 100).toFixed(p); }, "b": function(x) { return Math.round(x).toString(2); }, "c": function(x) { return x + ""; }, "d": function(x) { return Math.round(x).toString(10); }, "e": function(x, p) { return x.toExponential(p); }, "f": function(x, p) { return x.toFixed(p); }, "g": function(x, p) { return x.toPrecision(p); }, "o": function(x) { return Math.round(x).toString(8); }, "p": function(x, p) { return formatRounded(x * 100, p); }, "r": formatRounded, "s": formatPrefixAuto, "X": function(x) { return Math.round(x).toString(16).toUpperCase(); }, "x": function(x) { return Math.round(x).toString(16); } }; // [[fill]align][sign][symbol][0][width][,][.precision][type] var re = /^(?:(.)?([<>=^]))?([+\-\( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?([a-z%])?$/i; function formatSpecifier(specifier) { return new FormatSpecifier(specifier); } function FormatSpecifier(specifier) { if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier); var match, fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zero = !!match[5], width = match[6] && +match[6], comma = !!match[7], precision = match[8] && +match[8].slice(1), type = match[9] || ""; // The "n" type is an alias for ",g". if (type === "n") comma = true, type = "g"; // Map invalid types to the default format. else if (!formatTypes[type]) type = ""; // If zero fill is specified, padding goes after sign and before digits. if (zero || (fill === "0" && align === "=")) zero = true, fill = "0", align = "="; this.fill = fill; this.align = align; this.sign = sign; this.symbol = symbol; this.zero = zero; this.width = width; this.comma = comma; this.precision = precision; this.type = type; } FormatSpecifier.prototype.toString = function() { return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width == null ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision == null ? "" : "." + Math.max(0, this.precision | 0)) + this.type; }; var prefixes = ["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"]; function identity$5(x) { return x; } function formatLocale$1(locale) { var group = locale.grouping && locale.thousands ? formatGroup(locale.grouping, locale.thousands) : identity$5, currency = locale.currency, decimal = locale.decimal; function newFormat(specifier) { specifier = formatSpecifier(specifier); var fill = specifier.fill, align = specifier.align, sign = specifier.sign, symbol = specifier.symbol, zero = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, type = specifier.type; // Compute the prefix and suffix. // For SI-prefix, the suffix is lazily computed. var prefix = symbol === "$" ? currency[0] : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currency[1] : /[%p]/.test(type) ? "%" : ""; // What format function should we use? // Is this an integer type? // Can this type generate exponential notation? var formatType = formatTypes[type], maybeSuffix = !type || /[defgprs%]/.test(type); // Set the default precision if not specified, // or clamp the specified precision to the supported range. // For significant precision, it must be in [1, 21]. // For fixed precision, it must be in [0, 20]. precision = precision == null ? (type ? 6 : 12) : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision)); function format(value) { var valuePrefix = prefix, valueSuffix = suffix, i, n, c; if (type === "c") { valueSuffix = formatType(value) + valueSuffix; value = ""; } else { value = +value; // Convert negative to positive, and compute the prefix. // Note that -0 is not less than 0, but 1 / -0 is! var valueNegative = (value < 0 || 1 / value < 0) && (value *= -1, true); // Perform the initial formatting. value = formatType(value, precision); // If the original value was negative, it may be rounded to zero during // formatting; treat this as (positive) zero. if (valueNegative) { i = -1, n = value.length; valueNegative = false; while (++i < n) { if (c = value.charCodeAt(i), (48 < c && c < 58) || (type === "x" && 96 < c && c < 103) || (type === "X" && 64 < c && c < 71)) { valueNegative = true; break; } } } // Compute the prefix and suffix. valuePrefix = (valueNegative ? (sign === "(" ? sign : "-") : sign === "-" || sign === "(" ? "" : sign) + valuePrefix; valueSuffix = valueSuffix + (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + (valueNegative && sign === "(" ? ")" : ""); // Break the formatted value into the integer “value” part that can be // grouped, and fractional or exponential “suffix” part that is not. if (maybeSuffix) { i = -1, n = value.length; while (++i < n) { if (c = value.charCodeAt(i), 48 > c || c > 57) { valueSuffix = (c === 46 ? decimal + value.slice(i + 1) : value.slice(i)) + valueSuffix; value = value.slice(0, i); break; } } } } // If the fill character is not "0", grouping is applied before padding. if (comma && !zero) value = group(value, Infinity); // Compute the padding. var length = valuePrefix.length + value.length + valueSuffix.length, padding = length < width ? new Array(width - length + 1).join(fill) : ""; // If the fill character is "0", grouping is applied after padding. if (comma && zero) value = group(padding + value, padding.length ? width - valueSuffix.length : Infinity), padding = ""; // Reconstruct the final output based on the desired alignment. switch (align) { case "<": return valuePrefix + value + valueSuffix + padding; case "=": return valuePrefix + padding + value + valueSuffix; case "^": return padding.slice(0, length = padding.length >> 1) + valuePrefix + value + valueSuffix + padding.slice(length); } return padding + valuePrefix + value + valueSuffix; } format.toString = function() { return specifier + ""; }; return format; } function formatPrefix(specifier, value) { var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3]; return function(value) { return f(k * value) + prefix; }; } return { format: newFormat, formatPrefix: formatPrefix }; } var locale$1; var format; var formatPrefix; defaultLocale$1({ decimal: ".", thousands: ",", grouping: [3], currency: ["$", ""] }); function defaultLocale$1(definition) { locale$1 = formatLocale$1(definition); format = locale$1.format; formatPrefix = locale$1.formatPrefix; return locale$1; } function precisionFixed(step) { return Math.max(0, -exponent(Math.abs(step))); } function precisionPrefix(step, value) { return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value) / 3))) * 3 - exponent(Math.abs(step))); } function precisionRound(step, max) { step = Math.abs(step), max = Math.abs(max) - step; return Math.max(0, exponent(max) - exponent(step)) + 1; } function tickFormat(domain, count, specifier) { var start = domain[0], stop = domain[domain.length - 1], step = tickStep(start, stop, count == null ? 10 : count), precision; specifier = formatSpecifier(specifier == null ? ",f" : specifier); switch (specifier.type) { case "s": { var value = Math.max(Math.abs(start), Math.abs(stop)); if (specifier.precision == null && !isNaN(precision = precisionPrefix(step, value))) specifier.precision = precision; return formatPrefix(specifier, value); } case "": case "e": case "g": case "p": case "r": { if (specifier.precision == null && !isNaN(precision = precisionRound(step, Math.max(Math.abs(start), Math.abs(stop))))) specifier.precision = precision - (specifier.type === "e"); break; } case "f": case "%": { if (specifier.precision == null && !isNaN(precision = precisionFixed(step))) specifier.precision = precision - (specifier.type === "%") * 2; break; } } return format(specifier); } function linearish(scale) { var domain = scale.domain; scale.ticks = function(count) { var d = domain(); return ticks(d[0], d[d.length - 1], count == null ? 10 : count); }; scale.tickFormat = function(count, specifier) { return tickFormat(domain(), count, specifier); }; scale.nice = function(count) { var d = domain(), i = d.length - 1, n = count == null ? 10 : count, start = d[0], stop = d[i], step = tickStep(start, stop, n); if (step) { step = tickStep(Math.floor(start / step) * step, Math.ceil(stop / step) * step, n); d[0] = Math.floor(start / step) * step; d[i] = Math.ceil(stop / step) * step; domain(d); } return scale; }; return scale; } function linear() { var scale = continuous(deinterpolate, reinterpolate); scale.copy = function() { return copy$1(scale, linear()); }; return linearish(scale); } function identity$3() { var domain = [0, 1]; function scale(x) { return +x; } scale.invert = scale; scale.domain = scale.range = function(_) { return arguments.length ? (domain = map$2.call(_, number$2), scale) : domain.slice(); }; scale.copy = function() { return identity$3().domain(domain); }; return linearish(scale); } function nice(domain, interval) { domain = domain.slice(); var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], t; if (x1 < x0) { t = i0, i0 = i1, i1 = t; t = x0, x0 = x1, x1 = t; } domain[i0] = interval.floor(x0); domain[i1] = interval.ceil(x1); return domain; } function deinterpolate$1(a, b) { return (b = Math.log(b / a)) ? function(x) { return Math.log(x / a) / b; } : constant$5(b); } function reinterpolate$1(a, b) { return a < 0 ? function(t) { return -Math.pow(-b, t) * Math.pow(-a, 1 - t); } : function(t) { return Math.pow(b, t) * Math.pow(a, 1 - t); }; } function pow10(x) { return isFinite(x) ? +("1e" + x) : x < 0 ? 0 : x; } function powp(base) { return base === 10 ? pow10 : base === Math.E ? Math.exp : function(x) { return Math.pow(base, x); }; } function logp(base) { return base === Math.E ? Math.log : base === 10 && Math.log10 || base === 2 && Math.log2 || (base = Math.log(base), function(x) { return Math.log(x) / base; }); } function reflect(f) { return function(x) { return -f(-x); }; } function log$1() { var scale = continuous(deinterpolate$1, reinterpolate$1).domain([1, 10]), domain = scale.domain, base = 10, logs = logp(10), pows = powp(10); function rescale() { logs = logp(base), pows = powp(base); if (domain()[0] < 0) logs = reflect(logs), pows = reflect(pows); return scale; } scale.base = function(_) { return arguments.length ? (base = +_, rescale()) : base; }; scale.domain = function(_) { return arguments.length ? (domain(_), rescale()) : domain(); }; scale.ticks = function(count) { var d = domain(), u = d[0], v = d[d.length - 1], r; if (r = v < u) i = u, u = v, v = i; var i = logs(u), j = logs(v), p, k, t, n = count == null ? 10 : +count, z = []; if (!(base % 1) && j - i < n) { i = Math.round(i) - 1, j = Math.round(j) + 1; if (u > 0) for (; i < j; ++i) { for (k = 1, p = pows(i); k < base; ++k) { t = p * k; if (t < u) continue; if (t > v) break; z.push(t); } } else for (; i < j; ++i) { for (k = base - 1, p = pows(i); k >= 1; --k) { t = p * k; if (t < u) continue; if (t > v) break; z.push(t); } } } else { z = ticks(i, j, Math.min(j - i, n)).map(pows); } return r ? z.reverse() : z; }; scale.tickFormat = function(count, specifier) { if (specifier == null) specifier = base === 10 ? ".0e" : ","; if (typeof specifier !== "function") specifier = format(specifier); if (count === Infinity) return specifier; if (count == null) count = 10; var k = Math.max(1, base * count / scale.ticks().length); // TODO fast estimate? return function(d) { var i = d / pows(Math.round(logs(d))); if (i * base < base - 0.5) i *= base; return i <= k ? specifier(d) : ""; }; }; scale.nice = function() { return domain(nice(domain(), { floor: function(x) { return pows(Math.floor(logs(x))); }, ceil: function(x) { return pows(Math.ceil(logs(x))); } })); }; scale.copy = function() { return copy$1(scale, log$1().base(base)); }; return scale; } function raise(x, exponent) { return x < 0 ? -Math.pow(-x, exponent) : Math.pow(x, exponent); } function pow() { var exponent = 1, scale = continuous(deinterpolate, reinterpolate), domain = scale.domain; function deinterpolate(a, b) { return (b = raise(b, exponent) - (a = raise(a, exponent))) ? function(x) { return (raise(x, exponent) - a) / b; } : constant$5(b); } function reinterpolate(a, b) { b = raise(b, exponent) - (a = raise(a, exponent)); return function(t) { return raise(a + b * t, 1 / exponent); }; } scale.exponent = function(_) { return arguments.length ? (exponent = +_, domain(domain())) : exponent; }; scale.copy = function() { return copy$1(scale, pow().exponent(exponent)); }; return linearish(scale); } function sqrt() { return pow().exponent(0.5); } function quantile() { var domain = [], range = [], thresholds = []; function rescale() { var i = 0, n = Math.max(1, range.length); thresholds = new Array(n - 1); while (++i < n) thresholds[i - 1] = threshold(domain, i / n); return scale; } function scale(x) { if (!isNaN(x = +x)) return range[bisectRight(thresholds, x)]; } scale.invertExtent = function(y) { var i = range.indexOf(y); return i < 0 ? [NaN, NaN] : [ i > 0 ? thresholds[i - 1] : domain[0], i < thresholds.length ? thresholds[i] : domain[domain.length - 1] ]; }; scale.domain = function(_) { if (!arguments.length) return domain.slice(); domain = []; for (var i = 0, n = _.length, d; i < n; ++i) if (d = _[i], d != null && !isNaN(d = +d)) domain.push(d); domain.sort(ascending); return rescale(); }; scale.range = function(_) { return arguments.length ? (range = slice$2.call(_), rescale()) : range.slice(); }; scale.quantiles = function() { return thresholds.slice(); }; scale.copy = function() { return quantile() .domain(domain) .range(range); }; return scale; } function quantize$1() { var x0 = 0, x1 = 1, n = 1, domain = [0.5], range = [0, 1]; function scale(x) { if (x <= x) return range[bisectRight(domain, x, 0, n)]; } function rescale() { var i = -1; domain = new Array(n); while (++i < n) domain[i] = ((i + 1) * x1 - (i - n) * x0) / (n + 1); return scale; } scale.domain = function(_) { return arguments.length ? (x0 = +_[0], x1 = +_[1], rescale()) : [x0, x1]; }; scale.range = function(_) { return arguments.length ? (n = (range = slice$2.call(_)).length - 1, rescale()) : range.slice(); }; scale.invertExtent = function(y) { var i = range.indexOf(y); return i < 0 ? [NaN, NaN] : i < 1 ? [x0, domain[0]] : i >= n ? [domain[n - 1], x1] : [domain[i - 1], domain[i]]; }; scale.copy = function() { return quantize$1() .domain([x0, x1]) .range(range); }; return linearish(scale); } function threshold$1() { var domain = [0.5], range = [0, 1], n = 1; function scale(x) { if (x <= x) return range[bisectRight(domain, x, 0, n)]; } scale.domain = function(_) { return arguments.length ? (domain = slice$2.call(_), n = Math.min(domain.length, range.length - 1), scale) : domain.slice(); }; scale.range = function(_) { return arguments.length ? (range = slice$2.call(_), n = Math.min(domain.length, range.length - 1), scale) : range.slice(); }; scale.invertExtent = function(y) { var i = range.indexOf(y); return [domain[i - 1], domain[i]]; }; scale.copy = function() { return threshold$1() .domain(domain) .range(range); }; return scale; } var durationSecond$1 = 1000; var durationMinute$1 = durationSecond$1 * 60; var durationHour$1 = durationMinute$1 * 60; var durationDay$1 = durationHour$1 * 24; var durationWeek$1 = durationDay$1 * 7; var durationMonth = durationDay$1 * 30; var durationYear = durationDay$1 * 365; function date$1(t) { return new Date(t); } function number$3(t) { return t instanceof Date ? +t : +new Date(+t); } function calendar(year, month, week, day, hour, minute, second, millisecond, format) { var scale = continuous(deinterpolate, reinterpolate), invert = scale.invert, domain = scale.domain; var formatMillisecond = format(".%L"), formatSecond = format(":%S"), formatMinute = format("%I:%M"), formatHour = format("%I %p"), formatDay = format("%a %d"), formatWeek = format("%b %d"), formatMonth = format("%B"), formatYear = format("%Y"); var tickIntervals = [ [second, 1, durationSecond$1], [second, 5, 5 * durationSecond$1], [second, 15, 15 * durationSecond$1], [second, 30, 30 * durationSecond$1], [minute, 1, durationMinute$1], [minute, 5, 5 * durationMinute$1], [minute, 15, 15 * durationMinute$1], [minute, 30, 30 * durationMinute$1], [ hour, 1, durationHour$1 ], [ hour, 3, 3 * durationHour$1 ], [ hour, 6, 6 * durationHour$1 ], [ hour, 12, 12 * durationHour$1 ], [ day, 1, durationDay$1 ], [ day, 2, 2 * durationDay$1 ], [ week, 1, durationWeek$1 ], [ month, 1, durationMonth ], [ month, 3, 3 * durationMonth ], [ year, 1, durationYear ] ]; function tickFormat(date) { return (second(date) < date ? formatMillisecond : minute(date) < date ? formatSecond : hour(date) < date ? formatMinute : day(date) < date ? formatHour : month(date) < date ? (week(date) < date ? formatDay : formatWeek) : year(date) < date ? formatMonth : formatYear)(date); } function tickInterval(interval, start, stop, step) { if (interval == null) interval = 10; // If a desired tick count is specified, pick a reasonable tick interval // based on the extent of the domain and a rough estimate of tick size. // Otherwise, assume interval is already a time interval and use it. if (typeof interval === "number") { var target = Math.abs(stop - start) / interval, i = bisector(function(i) { return i[2]; }).right(tickIntervals, target); if (i === tickIntervals.length) { step = tickStep(start / durationYear, stop / durationYear, interval); interval = year; } else if (i) { i = tickIntervals[target / tickIntervals[i - 1][2] < tickIntervals[i][2] / target ? i - 1 : i]; step = i[1]; interval = i[0]; } else { step = tickStep(start, stop, interval); interval = millisecond; } } return step == null ? interval : interval.every(step); } scale.invert = function(y) { return new Date(invert(y)); }; scale.domain = function(_) { return arguments.length ? domain(map$2.call(_, number$3)) : domain().map(date$1); }; scale.ticks = function(interval, step) { var d = domain(), t0 = d[0], t1 = d[d.length - 1], r = t1 < t0, t; if (r) t = t0, t0 = t1, t1 = t; t = tickInterval(interval, t0, t1, step); t = t ? t.range(t0, t1 + 1) : []; // inclusive stop return r ? t.reverse() : t; }; scale.tickFormat = function(count, specifier) { return specifier == null ? tickFormat : format(specifier); }; scale.nice = function(interval, step) { var d = domain(); return (interval = tickInterval(interval, d[0], d[d.length - 1], step)) ? domain(nice(d, interval)) : scale; }; scale.copy = function() { return copy$1(scale, calendar(year, month, week, day, hour, minute, second, millisecond, format)); }; return scale; } function scaleTime() { return calendar(year, month, timeWeek, day, hour, minute, second, millisecond, timeFormat).domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]); } function scaleUtc() { return calendar(utcYear, utcMonth, utcWeek, utcDay, utcHour, utcMinute, second, millisecond, utcFormat).domain([Date.UTC(2000, 0, 1), Date.UTC(2000, 0, 2)]); } function colors(s) { return s.match(/.{6}/g).map(function(x) { return "#" + x; }); } var schemeCategory10 = colors("1f77b4ff7f0e2ca02cd627289467bd8c564be377c27f7f7fbcbd2217becf"); var schemeCategory20b = colors("393b795254a36b6ecf9c9ede6379398ca252b5cf6bcedb9c8c6d31bd9e39e7ba52e7cb94843c39ad494ad6616be7969c7b4173a55194ce6dbdde9ed6"); var schemeCategory20c = colors("3182bd6baed69ecae1c6dbefe6550dfd8d3cfdae6bfdd0a231a35474c476a1d99bc7e9c0756bb19e9ac8bcbddcdadaeb636363969696bdbdbdd9d9d9"); var schemeCategory20 = colors("1f77b4aec7e8ff7f0effbb782ca02c98df8ad62728ff98969467bdc5b0d58c564bc49c94e377c2f7b6d27f7f7fc7c7c7bcbd22dbdb8d17becf9edae5"); var interpolateCubehelixDefault = interpolateCubehelixLong(cubehelix(300, 0.5, 0.0), cubehelix(-240, 0.5, 1.0)); var interpolateWarm = interpolateCubehelixLong(cubehelix(-100, 0.75, 0.35), cubehelix(80, 1.50, 0.8)); var interpolateCool = interpolateCubehelixLong(cubehelix(260, 0.75, 0.35), cubehelix(80, 1.50, 0.8)); var rainbow = cubehelix(); function interpolateRainbow(t) { if (t < 0 || t > 1) t -= Math.floor(t); var ts = Math.abs(t - 0.5); rainbow.h = 360 * t - 100; rainbow.s = 1.5 - 1.5 * ts; rainbow.l = 0.8 - 0.9 * ts; return rainbow + ""; } function ramp(range) { var n = range.length; return function(t) { return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))]; }; } var interpolateViridis = ramp(colors("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")); var interpolateMagma = ramp(colors("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")); var interpolateInferno = ramp(colors("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")); var interpolatePlasma = ramp(colors("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921")); function sequential(interpolator) { var x0 = 0, x1 = 1, clamp = false; function scale(x) { var t = (x - x0) / (x1 - x0); return interpolator(clamp ? Math.max(0, Math.min(1, t)) : t); } scale.domain = function(_) { return arguments.length ? (x0 = +_[0], x1 = +_[1], scale) : [x0, x1]; }; scale.clamp = function(_) { return arguments.length ? (clamp = !!_, scale) : clamp; }; scale.interpolator = function(_) { return arguments.length ? (interpolator = _, scale) : interpolator; }; scale.copy = function() { return sequential(interpolator).domain([x0, x1]).clamp(clamp); }; return linearish(scale); } function band() { var scale = ordinal().unknown(undefined), domain = scale.domain, ordinalRange = scale.range, range$$ = [0, 1], step, bandwidth, round = false, paddingInner = 0, paddingOuter = 0, align = 0.5; delete scale.unknown; function rescale() { var n = domain().length, reverse = range$$[1] < range$$[0], start = range$$[reverse - 0], stop = range$$[1 - reverse]; step = (stop - start) / Math.max(1, n - paddingInner + paddingOuter * 2); if (round) step = Math.floor(step); start += (stop - start - step * (n - paddingInner)) * align; bandwidth = step * (1 - paddingInner); if (round) start = Math.round(start), bandwidth = Math.round(bandwidth); var values = range(n).map(function(i) { return start + step * i; }); return ordinalRange(reverse ? values.reverse() : values); } scale.domain = function(_) { return arguments.length ? (domain(_), rescale()) : domain(); }; scale.range = function(_) { return arguments.length ? (range$$ = [+_[0], +_[1]], rescale()) : range$$.slice(); }; scale.rangeRound = function(_) { return range$$ = [+_[0], +_[1]], round = true, rescale(); }; scale.bandwidth = function() { return bandwidth; }; scale.step = function() { return step; }; scale.round = function(_) { return arguments.length ? (round = !!_, rescale()) : round; }; scale.padding = function(_) { return arguments.length ? (paddingInner = paddingOuter = Math.max(0, Math.min(1, _)), rescale()) : paddingInner; }; scale.paddingInner = function(_) { return arguments.length ? (paddingInner = Math.max(0, Math.min(1, _)), rescale()) : paddingInner; }; scale.paddingOuter = function(_) { return arguments.length ? (paddingOuter = Math.max(0, Math.min(1, _)), rescale()) : paddingOuter; }; scale.align = function(_) { return arguments.length ? (align = Math.max(0, Math.min(1, _)), rescale()) : align; }; scale.invertRange = function(_) { var lo = +_[0], hi = +_[1], reverse = range$$[1] < range$$[0], values = reverse ? ordinalRange().reverse() : ordinalRange(), n = values.length - 1, a, b, t; // order range inputs, bail if outside of scale range if (hi < lo) t = lo, lo = hi, hi = t; if (hi < values[0] || lo > range$$[1-reverse]) return undefined; // binary search to index into scale range a = Math.max(0, bisectRight(values, lo) - 1); b = lo===hi ? a : bisectRight(values, hi) - 1; // increment index a if lo is within padding gap if (lo - values[a] > bandwidth + 1e-10) ++a; if (reverse) t = a, a = n - b, b = n - t; // map + swap return (a > b) ? undefined : domain().slice(a, b+1); }; scale.invert = function(_) { var value = scale.invertRange([_, _]); return value ? value[0] : value; }; scale.copy = function() { return band() .domain(domain()) .range(range$$) .round(round) .paddingInner(paddingInner) .paddingOuter(paddingOuter) .align(align); }; return rescale(); } function pointish(scale) { var copy = scale.copy; scale.padding = scale.paddingOuter; delete scale.paddingInner; delete scale.paddingOuter; scale.copy = function() { return pointish(copy()); }; return scale; } function point$5() { return pointish(band().paddingInner(1)); } function index(scheme) { var domain = [], length = 0, lookup = {}, interp = scheme ? sequential(scheme) : linear(); function scale(_) { if (lookup.hasOwnProperty(_)) return interp(lookup[_]); } scale.domain = function(_) { if (!arguments.length) return domain.slice(); domain = _.slice(); length = domain.length; lookup = {}; for (var i=0; i<length;) lookup[domain[i]] = i++; interp.domain([0, length - 1]); return scale; }; if (!scheme) { // sequential scales do not export an invert method scale.invert = function(_) { return domain[interp.invert(_)]; }; scale.invertRange = function(_) { var lo = interp.invert(_[0]), hi = interp.invert(_[1]), t; if (lo > hi) t = lo, lo = hi, hi = t; t = domain.slice( Math.max(0, Math.ceil(lo)), Math.min(length, Math.floor(hi) + 1) ); return t.length ? t : undefined; }; } (scheme ? ['interpolator'] : ['interpolate', 'range', 'rangeRound']) .forEach(function(method) { scale[method] = function() { var r = interp[method].apply(null, arguments); return arguments.length ? scale : r; }; }); scale.copy = function() { return (scheme ? index(scheme).interpolator(interp.interpolator()) : index().interpolate(interp.interpolate()).range(interp.range()) ).domain(domain); }; return scale; } function invertRange(scale) { return function(_) { var lo = _[0], hi = _[1], t; if (hi < lo) t = lo, lo = hi, hi = t; return [ scale.invert(lo), scale.invert(hi) ]; } } function invertRangeExtent(scale) { return function(_) { var range = scale.range(), lo = _[0], hi = _[1], min = -1, max, t, i, n; if (hi < lo) t = lo, lo = hi, hi = t; for (i=0, n=range.length; i<n; ++i) { if (range[i] >= lo && range[i] <= hi) { if (min < 0) min = i; max = i; } } if (min < 0) return undefined; lo = scale.invertExtent(range[min]); hi = scale.invertExtent(range[max]); return [ lo[0] === undefined ? lo[1] : lo[0], hi[1] === undefined ? hi[0] : hi[1] ]; } } function colors$1(specifier) { var n = specifier.length / 6 | 0, colors = new Array(n), i = 0; while (i < n) colors[i] = "#" + specifier.slice(i * 6, ++i * 6); return colors; } var schemeAccent = colors$1("7fc97fbeaed4fdc086ffff99386cb0f0027fbf5b17666666"); var schemeDark2 = colors$1("1b9e77d95f027570b3e7298a66a61ee6ab02a6761d666666"); var schemePaired = colors$1("a6cee31f78b4b2df8a33a02cfb9a99e31a1cfdbf6fff7f00cab2d66a3d9affff99b15928"); var schemePastel1 = colors$1("fbb4aeb3cde3ccebc5decbe4fed9a6ffffcce5d8bdfddaecf2f2f2"); var schemePastel2 = colors$1("b3e2cdfdcdaccbd5e8f4cae4e6f5c9fff2aef1e2cccccccc"); var schemeSet1 = colors$1("e41a1c377eb84daf4a984ea3ff7f00ffff33a65628f781bf999999"); var schemeSet2 = colors$1("66c2a5fc8d628da0cbe78ac3a6d854ffd92fe5c494b3b3b3"); var schemeSet3 = colors$1("8dd3c7ffffb3bebadafb807280b1d3fdb462b3de69fccde5d9d9d9bc80bdccebc5ffed6f"); function ramp$1(scheme) { return interpolateRgbBasis(scheme[scheme.length - 1]); } var scheme = new Array(3).concat( "d8b365f5f5f55ab4ac", "a6611adfc27d80cdc1018571", "a6611adfc27df5f5f580cdc1018571", "8c510ad8b365f6e8c3c7eae55ab4ac01665e", "8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e", "8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e", "8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e", "5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30", "5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30" ).map(colors$1); var interpolateBrBG = ramp$1(scheme); var scheme$1 = new Array(3).concat( "af8dc3f7f7f77fbf7b", "7b3294c2a5cfa6dba0008837", "7b3294c2a5cff7f7f7a6dba0008837", "762a83af8dc3e7d4e8d9f0d37fbf7b1b7837", "762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837", "762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837", "762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837", "40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b", "40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b" ).map(colors$1); var interpolatePRGn = ramp$1(scheme$1); var scheme$2 = new Array(3).concat( "e9a3c9f7f7f7a1d76a", "d01c8bf1b6dab8e1864dac26", "d01c8bf1b6daf7f7f7b8e1864dac26", "c51b7de9a3c9fde0efe6f5d0a1d76a4d9221", "c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221", "c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221", "c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221", "8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419", "8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419" ).map(colors$1); var interpolatePiYG = ramp$1(scheme$2); var scheme$3 = new Array(3).concat( "f1a340f7f7f7998ec3", "e66101fdb863b2abd25e3c99", "e66101fdb863f7f7f7b2abd25e3c99", "b35806f1a340fee0b6d8daeb998ec3542788", "b35806f1a340fee0b6f7f7f7d8daeb998ec3542788", "b35806e08214fdb863fee0b6d8daebb2abd28073ac542788", "b35806e08214fdb863fee0b6f7f7f7d8daebb2abd28073ac542788", "7f3b08b35806e08214fdb863fee0b6d8daebb2abd28073ac5427882d004b", "7f3b08b35806e08214fdb863fee0b6f7f7f7d8daebb2abd28073ac5427882d004b" ).map(colors$1); var interpolatePuOr = ramp$1(scheme$3); var scheme$4 = new Array(3).concat( "ef8a62f7f7f767a9cf", "ca0020f4a58292c5de0571b0", "ca0020f4a582f7f7f792c5de0571b0", "b2182bef8a62fddbc7d1e5f067a9cf2166ac", "b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac", "b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac", "b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac", "67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061", "67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061" ).map(colors$1); var interpolateRdBu = ramp$1(scheme$4); var scheme$5 = new Array(3).concat( "ef8a62ffffff999999", "ca0020f4a582bababa404040", "ca0020f4a582ffffffbababa404040", "b2182bef8a62fddbc7e0e0e09999994d4d4d", "b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d", "b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d", "b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d", "67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a", "67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a" ).map(colors$1); var interpolateRdGy = ramp$1(scheme$5); var scheme$6 = new Array(3).concat( "fc8d59ffffbf91bfdb", "d7191cfdae61abd9e92c7bb6", "d7191cfdae61ffffbfabd9e92c7bb6", "d73027fc8d59fee090e0f3f891bfdb4575b4", "d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4", "d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4", "d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4", "a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695", "a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695" ).map(colors$1); var interpolateRdYlBu = ramp$1(scheme$6); var scheme$7 = new Array(3).concat( "fc8d59ffffbf91cf60", "d7191cfdae61a6d96a1a9641", "d7191cfdae61ffffbfa6d96a1a9641", "d73027fc8d59fee08bd9ef8b91cf601a9850", "d73027fc8d59fee08bffffbfd9ef8b91cf601a9850", "d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850", "d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850", "a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837", "a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837" ).map(colors$1); var interpolateRdYlGn = ramp$1(scheme$7); var scheme$8 = new Array(3).concat( "fc8d59ffffbf99d594", "d7191cfdae61abdda42b83ba", "d7191cfdae61ffffbfabdda42b83ba", "d53e4ffc8d59fee08be6f59899d5943288bd", "d53e4ffc8d59fee08bffffbfe6f59899d5943288bd", "d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd", "d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd", "9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2", "9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2" ).map(colors$1); var interpolateSpectral = ramp$1(scheme$8); var scheme$9 = new Array(3).concat( "e5f5f999d8c92ca25f", "edf8fbb2e2e266c2a4238b45", "edf8fbb2e2e266c2a42ca25f006d2c", "edf8fbccece699d8c966c2a42ca25f006d2c", "edf8fbccece699d8c966c2a441ae76238b45005824", "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824", "f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b" ).map(colors$1); var interpolateBuGn = ramp$1(scheme$9); var scheme$10 = new Array(3).concat( "e0ecf49ebcda8856a7", "edf8fbb3cde38c96c688419d", "edf8fbb3cde38c96c68856a7810f7c", "edf8fbbfd3e69ebcda8c96c68856a7810f7c", "edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b", "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b", "f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b" ).map(colors$1); var interpolateBuPu = ramp$1(scheme$10); var scheme$11 = new Array(3).concat( "e0f3dba8ddb543a2ca", "f0f9e8bae4bc7bccc42b8cbe", "f0f9e8bae4bc7bccc443a2ca0868ac", "f0f9e8ccebc5a8ddb57bccc443a2ca0868ac", "f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e", "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e", "f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081" ).map(colors$1); var interpolateGnBu = ramp$1(scheme$11); var scheme$12 = new Array(3).concat( "fee8c8fdbb84e34a33", "fef0d9fdcc8afc8d59d7301f", "fef0d9fdcc8afc8d59e34a33b30000", "fef0d9fdd49efdbb84fc8d59e34a33b30000", "fef0d9fdd49efdbb84fc8d59ef6548d7301f990000", "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000", "fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000" ).map(colors$1); var interpolateOrRd = ramp$1(scheme$12); var scheme$13 = new Array(3).concat( "ece2f0a6bddb1c9099", "f6eff7bdc9e167a9cf02818a", "f6eff7bdc9e167a9cf1c9099016c59", "f6eff7d0d1e6a6bddb67a9cf1c9099016c59", "f6eff7d0d1e6a6bddb67a9cf3690c002818a016450", "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450", "fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636" ).map(colors$1); var interpolatePuBuGn = ramp$1(scheme$13); var scheme$14 = new Array(3).concat( "ece7f2a6bddb2b8cbe", "f1eef6bdc9e174a9cf0570b0", "f1eef6bdc9e174a9cf2b8cbe045a8d", "f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d", "f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b", "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b", "fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858" ).map(colors$1); var interpolatePuBu = ramp$1(scheme$14); var scheme$15 = new Array(3).concat( "e7e1efc994c7dd1c77", "f1eef6d7b5d8df65b0ce1256", "f1eef6d7b5d8df65b0dd1c77980043", "f1eef6d4b9dac994c7df65b0dd1c77980043", "f1eef6d4b9dac994c7df65b0e7298ace125691003f", "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f", "f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f" ).map(colors$1); var interpolatePuRd = ramp$1(scheme$15); var scheme$16 = new Array(3).concat( "fde0ddfa9fb5c51b8a", "feebe2fbb4b9f768a1ae017e", "feebe2fbb4b9f768a1c51b8a7a0177", "feebe2fcc5c0fa9fb5f768a1c51b8a7a0177", "feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177", "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177", "fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a" ).map(colors$1); var interpolateRdPu = ramp$1(scheme$16); var scheme$17 = new Array(3).concat( "edf8b17fcdbb2c7fb8", "ffffcca1dab441b6c4225ea8", "ffffcca1dab441b6c42c7fb8253494", "ffffccc7e9b47fcdbb41b6c42c7fb8253494", "ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84", "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84", "ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58" ).map(colors$1); var interpolateYlGnBu = ramp$1(scheme$17); var scheme$18 = new Array(3).concat( "f7fcb9addd8e31a354", "ffffccc2e69978c679238443", "ffffccc2e69978c67931a354006837", "ffffccd9f0a3addd8e78c67931a354006837", "ffffccd9f0a3addd8e78c67941ab5d238443005a32", "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32", "ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529" ).map(colors$1); var interpolateYlGn = ramp$1(scheme$18); var scheme$19 = new Array(3).concat( "fff7bcfec44fd95f0e", "ffffd4fed98efe9929cc4c02", "ffffd4fed98efe9929d95f0e993404", "ffffd4fee391fec44ffe9929d95f0e993404", "ffffd4fee391fec44ffe9929ec7014cc4c028c2d04", "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04", "ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506" ).map(colors$1); var interpolateYlOrBr = ramp$1(scheme$19); var scheme$20 = new Array(3).concat( "ffeda0feb24cf03b20", "ffffb2fecc5cfd8d3ce31a1c", "ffffb2fecc5cfd8d3cf03b20bd0026", "ffffb2fed976feb24cfd8d3cf03b20bd0026", "ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026", "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026", "ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026" ).map(colors$1); var interpolateYlOrRd = ramp$1(scheme$20); var scheme$21 = new Array(3).concat( "deebf79ecae13182bd", "eff3ffbdd7e76baed62171b5", "eff3ffbdd7e76baed63182bd08519c", "eff3ffc6dbef9ecae16baed63182bd08519c", "eff3ffc6dbef9ecae16baed64292c62171b5084594", "f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594", "f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b" ).map(colors$1); var interpolateBlues = ramp$1(scheme$21); var scheme$22 = new Array(3).concat( "e5f5e0a1d99b31a354", "edf8e9bae4b374c476238b45", "edf8e9bae4b374c47631a354006d2c", "edf8e9c7e9c0a1d99b74c47631a354006d2c", "edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32", "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32", "f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b" ).map(colors$1); var interpolateGreens = ramp$1(scheme$22); var scheme$23 = new Array(3).concat( "f0f0f0bdbdbd636363", "f7f7f7cccccc969696525252", "f7f7f7cccccc969696636363252525", "f7f7f7d9d9d9bdbdbd969696636363252525", "f7f7f7d9d9d9bdbdbd969696737373525252252525", "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525", "fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000" ).map(colors$1); var interpolateGreys = ramp$1(scheme$23); var scheme$24 = new Array(3).concat( "efedf5bcbddc756bb1", "f2f0f7cbc9e29e9ac86a51a3", "f2f0f7cbc9e29e9ac8756bb154278f", "f2f0f7dadaebbcbddc9e9ac8756bb154278f", "f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486", "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486", "fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d" ).map(colors$1); var interpolatePurples = ramp$1(scheme$24); var scheme$25 = new Array(3).concat( "fee0d2fc9272de2d26", "fee5d9fcae91fb6a4acb181d", "fee5d9fcae91fb6a4ade2d26a50f15", "fee5d9fcbba1fc9272fb6a4ade2d26a50f15", "fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d", "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d", "fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d" ).map(colors$1); var interpolateReds = ramp$1(scheme$25); var scheme$26 = new Array(3).concat( "fee6cefdae6be6550d", "feeddefdbe85fd8d3cd94701", "feeddefdbe85fd8d3ce6550da63603", "feeddefdd0a2fdae6bfd8d3ce6550da63603", "feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04", "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04", "fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704" ).map(colors$1); var interpolateOranges = ramp$1(scheme$26); var schemes = { // d3 built-in categorical palettes category10: schemeCategory10, category20: schemeCategory20, category20b: schemeCategory20b, category20c: schemeCategory20c, // extended categorical palettes accent: schemeAccent, dark2: schemeDark2, paired: schemePaired, pastel1: schemePastel1, pastel2: schemePastel2, set1: schemeSet1, set2: schemeSet2, set3: schemeSet3, // d3 built-in interpolators cubehelix: interpolateCubehelixDefault, rainbow: interpolateRainbow, warm: interpolateWarm, cool: interpolateCool, viridis: interpolateViridis, magma: interpolateMagma, inferno: interpolateInferno, plasma: interpolatePlasma, // diverging brbg: interpolateBrBG, prgn: interpolatePRGn, piyg: interpolatePiYG, puor: interpolatePuOr, rdbu: interpolateRdBu, rdgy: interpolateRdGy, rdylbu: interpolateRdYlBu, rdylgn: interpolateRdYlGn, spectral: interpolateSpectral, // repeat with friendlier names brownbluegreen: interpolateBrBG, purplegreen: interpolatePRGn, pinkyellowgreen: interpolatePiYG, purpleorange: interpolatePuOr, redblue: interpolateRdBu, redgrey: interpolateRdGy, redyellowblue: interpolateRdYlBu, redyellowgreen: interpolateRdYlGn, // sequential multi-hue bugn: interpolateBuGn, bupu: interpolateBuPu, gnbu: interpolateGnBu, orrd: interpolateOrRd, pubugn: interpolatePuBuGn, pubu: interpolatePuBu, purd: interpolatePuRd, rdpu: interpolateRdPu, ylgnbu: interpolateYlGnBu, ylgn: interpolateYlGn, ylorbr: interpolateYlOrBr, ylorrd: interpolateYlOrRd, // repeat with friendlier names bluegreen: interpolateBuGn, bluepurple: interpolateBuPu, greenblue: interpolateGnBu, orangered: interpolateOrRd, purplebluegreen: interpolatePuBuGn, purpleblue: interpolatePuBu, purplered: interpolatePuRd, redpurple: interpolateRdPu, yellowgreenblue: interpolateYlGnBu, yellowgreen: interpolateYlGn, yelloworangebrown: interpolateYlOrBr, yelloworangered: interpolateYlOrRd, // sequential single-hue blues: interpolateBlues, greens: interpolateGreens, greys: interpolateGreys, purples: interpolatePurples, reds: interpolateReds, oranges: interpolateOranges }; function reverseInterpolator(interpolator) { return function(i) { return interpolator(1 - i); }; } function getScheme(name, scheme) { return arguments.length > 1 ? (schemes[name] = scheme, this) : schemes.hasOwnProperty(name) ? schemes[name] : null; } /** * Augment scales with their type and needed inverse methods. */ function create$1(type, constructor) { return function scale(scheme, reverse) { if (scheme) { if (!(scheme = getScheme(scheme))) { error('Unrecognized scale scheme: ' + scheme) } if (reverse) { scheme = isFunction(scheme) ? reverseInterpolator(scheme) : scheme.slice().reverse(); } } var s = constructor(scheme); s.type = type; if (!s.invertRange) { s.invertRange = s.invert ? invertRange(s) : s.invertExtent ? invertRangeExtent(s) : undefined; } return s; }; } function scale$1(type, scale) { return arguments.length > 1 ? (scales[type] = create$1(type, scale), this) : scales.hasOwnProperty(type) ? scales[type] : null; } var scales = { // base scale types identity: identity$3, linear: linear, log: log$1, ordinal: ordinal, pow: pow, sqrt: sqrt, quantile: quantile, quantize: quantize$1, threshold: threshold$1, time: scaleTime, utc: scaleUtc, sequential: sequential, // extended scale types band: band, point: point$5, index: index }; for (var key$2 in scales) { scale$1(key$2, scales[key$2]); } // Adds floating point numbers with twice the normal precision. // Reference: J. R. Shewchuk, Adaptive Precision Floating-Point Arithmetic and // Fast Robust Geometric Predicates, Discrete & Computational Geometry 18(3) // 305–363 (1997). // Code adapted from GeographicLib by Charles F. F. Karney, // http://geographiclib.sourceforge.net/ function adder() { return new Adder; } function Adder() { this.reset(); } Adder.prototype = { constructor: Adder, reset: function() { this.s = // rounded value this.t = 0; // exact error }, add: function(y) { add$2(temp$1, y, this.t); add$2(this, temp$1.s, this.s); if (this.s) this.t += temp$1.t; else this.s = temp$1.t; }, valueOf: function() { return this.s; } }; var temp$1 = new Adder; function add$2(adder, a, b) { var x = adder.s = a + b, bv = x - a, av = x - bv; adder.t = (a - av) + (b - bv); } var epsilon$2 = 1e-6; var pi$3 = Math.PI; var halfPi$2 = pi$3 / 2; var quarterPi = pi$3 / 4; var tau$4 = pi$3 * 2; var degrees$1 = 180 / pi$3; var radians = pi$3 / 180; var abs = Math.abs; var atan = Math.atan; var atan2 = Math.atan2; var cos = Math.cos; var ceil = Math.ceil; var exp = Math.exp; var log$2 = Math.log; var pow$1 = Math.pow; var sin = Math.sin; var sign$1 = Math.sign || function(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; }; var sqrt$1 = Math.sqrt; var tan = Math.tan; function acos(x) { return x > 1 ? 0 : x < -1 ? pi$3 : Math.acos(x); } function asin$1(x) { return x > 1 ? halfPi$2 : x < -1 ? -halfPi$2 : Math.asin(x); } function noop$4() {} function streamGeometry(geometry, stream) { if (geometry && streamGeometryType.hasOwnProperty(geometry.type)) { streamGeometryType[geometry.type](geometry, stream); } } var streamObjectType = { Feature: function(feature, stream) { streamGeometry(feature.geometry, stream); }, FeatureCollection: function(object, stream) { var features = object.features, i = -1, n = features.length; while (++i < n) streamGeometry(features[i].geometry, stream); } }; var streamGeometryType = { Sphere: function(object, stream) { stream.sphere(); }, Point: function(object, stream) { object = object.coordinates; stream.point(object[0], object[1], object[2]); }, MultiPoint: function(object, stream) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) object = coordinates[i], stream.point(object[0], object[1], object[2]); }, LineString: function(object, stream) { streamLine(object.coordinates, stream, 0); }, MultiLineString: function(object, stream) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) streamLine(coordinates[i], stream, 0); }, Polygon: function(object, stream) { streamPolygon(object.coordinates, stream); }, MultiPolygon: function(object, stream) { var coordinates = object.coordinates, i = -1, n = coordinates.length; while (++i < n) streamPolygon(coordinates[i], stream); }, GeometryCollection: function(object, stream) { var geometries = object.geometries, i = -1, n = geometries.length; while (++i < n) streamGeometry(geometries[i], stream); } }; function streamLine(coordinates, stream, closed) { var i = -1, n = coordinates.length - closed, coordinate; stream.lineStart(); while (++i < n) coordinate = coordinates[i], stream.point(coordinate[0], coordinate[1], coordinate[2]); stream.lineEnd(); } function streamPolygon(coordinates, stream) { var i = -1, n = coordinates.length; stream.polygonStart(); while (++i < n) streamLine(coordinates[i], stream, 1); stream.polygonEnd(); } function geoStream(object, stream) { if (object && streamObjectType.hasOwnProperty(object.type)) { streamObjectType[object.type](object, stream); } else { streamGeometry(object, stream); } } var areaRingSum = adder(); var areaSum = adder(); var lambda00; var phi00; var lambda0; var cosPhi0; var sinPhi0; var areaStream = { point: noop$4, lineStart: noop$4, lineEnd: noop$4, polygonStart: function() { areaRingSum.reset(); areaStream.lineStart = areaRingStart; areaStream.lineEnd = areaRingEnd; }, polygonEnd: function() { var areaRing = +areaRingSum; areaSum.add(areaRing < 0 ? tau$4 + areaRing : areaRing); this.lineStart = this.lineEnd = this.point = noop$4; }, sphere: function() { areaSum.add(tau$4); } }; function areaRingStart() { areaStream.point = areaPointFirst; } function areaRingEnd() { areaPoint(lambda00, phi00); } function areaPointFirst(lambda, phi) { areaStream.point = areaPoint; lambda00 = lambda, phi00 = phi; lambda *= radians, phi *= radians; lambda0 = lambda, cosPhi0 = cos(phi = phi / 2 + quarterPi), sinPhi0 = sin(phi); } function areaPoint(lambda, phi) { lambda *= radians, phi *= radians; phi = phi / 2 + quarterPi; // half the angular distance from south pole // Spherical excess E for a spherical triangle with vertices: south pole, // previous point, current point. Uses a formula derived from Cagnoli’s // theorem. See Todhunter, Spherical Trig. (1871), Sec. 103, Eq. (2). var dLambda = lambda - lambda0, sdLambda = dLambda >= 0 ? 1 : -1, adLambda = sdLambda * dLambda, cosPhi = cos(phi), sinPhi = sin(phi), k = sinPhi0 * sinPhi, u = cosPhi0 * cosPhi + k * cos(adLambda), v = k * sdLambda * sin(adLambda); areaRingSum.add(atan2(v, u)); // Advance the previous points. lambda0 = lambda, cosPhi0 = cosPhi, sinPhi0 = sinPhi; } function spherical(cartesian) { return [atan2(cartesian[1], cartesian[0]), asin$1(cartesian[2])]; } function cartesian(spherical) { var lambda = spherical[0], phi = spherical[1], cosPhi = cos(phi); return [cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)]; } function cartesianDot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } function cartesianCross(a, b) { return [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; } // TODO return a function cartesianAddInPlace(a, b) { a[0] += b[0], a[1] += b[1], a[2] += b[2]; } function cartesianScale(vector, k) { return [vector[0] * k, vector[1] * k, vector[2] * k]; } // TODO return d function cartesianNormalizeInPlace(d) { var l = sqrt$1(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]); d[0] /= l, d[1] /= l, d[2] /= l; } var lambda0$1; var phi0; var lambda1; var phi1; var lambda2; var lambda00$1; var phi00$1; var p0; var deltaSum = adder(); var ranges; var range$1; var boundsStream = { point: boundsPoint, lineStart: boundsLineStart, lineEnd: boundsLineEnd, polygonStart: function() { boundsStream.point = boundsRingPoint; boundsStream.lineStart = boundsRingStart; boundsStream.lineEnd = boundsRingEnd; deltaSum.reset(); areaStream.polygonStart(); }, polygonEnd: function() { areaStream.polygonEnd(); boundsStream.point = boundsPoint; boundsStream.lineStart = boundsLineStart; boundsStream.lineEnd = boundsLineEnd; if (areaRingSum < 0) lambda0$1 = -(lambda1 = 180), phi0 = -(phi1 = 90); else if (deltaSum > epsilon$2) phi1 = 90; else if (deltaSum < -epsilon$2) phi0 = -90; range$1[0] = lambda0$1, range$1[1] = lambda1; } }; function boundsPoint(lambda, phi) { ranges.push(range$1 = [lambda0$1 = lambda, lambda1 = lambda]); if (phi < phi0) phi0 = phi; if (phi > phi1) phi1 = phi; } function linePoint(lambda, phi) { var p = cartesian([lambda * radians, phi * radians]); if (p0) { var normal = cartesianCross(p0, p), equatorial = [normal[1], -normal[0], 0], inflection = cartesianCross(equatorial, normal); cartesianNormalizeInPlace(inflection); inflection = spherical(inflection); var delta = lambda - lambda2, sign = delta > 0 ? 1 : -1, lambdai = inflection[0] * degrees$1 * sign, phii, antimeridian = abs(delta) > 180; if (antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) { phii = inflection[1] * degrees$1; if (phii > phi1) phi1 = phii; } else if (lambdai = (lambdai + 360) % 360 - 180, antimeridian ^ (sign * lambda2 < lambdai && lambdai < sign * lambda)) { phii = -inflection[1] * degrees$1; if (phii < phi0) phi0 = phii; } else { if (phi < phi0) phi0 = phi; if (phi > phi1) phi1 = phi; } if (antimeridian) { if (lambda < lambda2) { if (angle(lambda0$1, lambda) > angle(lambda0$1, lambda1)) lambda1 = lambda; } else { if (angle(lambda, lambda1) > angle(lambda0$1, lambda1)) lambda0$1 = lambda; } } else { if (lambda1 >= lambda0$1) { if (lambda < lambda0$1) lambda0$1 = lambda; if (lambda > lambda1) lambda1 = lambda; } else { if (lambda > lambda2) { if (angle(lambda0$1, lambda) > angle(lambda0$1, lambda1)) lambda1 = lambda; } else { if (angle(lambda, lambda1) > angle(lambda0$1, lambda1)) lambda0$1 = lambda; } } } } else { boundsPoint(lambda, phi); } p0 = p, lambda2 = lambda; } function boundsLineStart() { boundsStream.point = linePoint; } function boundsLineEnd() { range$1[0] = lambda0$1, range$1[1] = lambda1; boundsStream.point = boundsPoint; p0 = null; } function boundsRingPoint(lambda, phi) { if (p0) { var delta = lambda - lambda2; deltaSum.add(abs(delta) > 180 ? delta + (delta > 0 ? 360 : -360) : delta); } else { lambda00$1 = lambda, phi00$1 = phi; } areaStream.point(lambda, phi); linePoint(lambda, phi); } function boundsRingStart() { areaStream.lineStart(); } function boundsRingEnd() { boundsRingPoint(lambda00$1, phi00$1); areaStream.lineEnd(); if (abs(deltaSum) > epsilon$2) lambda0$1 = -(lambda1 = 180); range$1[0] = lambda0$1, range$1[1] = lambda1; p0 = null; } // Finds the left-right distance between two longitudes. // This is almost the same as (lambda1 - lambda0 + 360°) % 360°, except that we want // the distance between ±180° to be 360°. function angle(lambda0, lambda1) { return (lambda1 -= lambda0) < 0 ? lambda1 + 360 : lambda1; } var W0; var W1; var X0; var Y0; var Z0; var X1; var Y1; var Z1; var X2; var Y2; var Z2; var lambda00$2; var phi00$2; var x0; var y0; var z0; // previous point var centroidStream = { sphere: noop$4, point: centroidPoint, lineStart: centroidLineStart, lineEnd: centroidLineEnd, polygonStart: function() { centroidStream.lineStart = centroidRingStart; centroidStream.lineEnd = centroidRingEnd; }, polygonEnd: function() { centroidStream.lineStart = centroidLineStart; centroidStream.lineEnd = centroidLineEnd; } }; // Arithmetic mean of Cartesian vectors. function centroidPoint(lambda, phi) { lambda *= radians, phi *= radians; var cosPhi = cos(phi); centroidPointCartesian(cosPhi * cos(lambda), cosPhi * sin(lambda), sin(phi)); } function centroidPointCartesian(x, y, z) { ++W0; X0 += (x - X0) / W0; Y0 += (y - Y0) / W0; Z0 += (z - Z0) / W0; } function centroidLineStart() { centroidStream.point = centroidLinePointFirst; } function centroidLinePointFirst(lambda, phi) { lambda *= radians, phi *= radians; var cosPhi = cos(phi); x0 = cosPhi * cos(lambda); y0 = cosPhi * sin(lambda); z0 = sin(phi); centroidStream.point = centroidLinePoint; centroidPointCartesian(x0, y0, z0); } function centroidLinePoint(lambda, phi) { lambda *= radians, phi *= radians; var cosPhi = cos(phi), x = cosPhi * cos(lambda), y = cosPhi * sin(lambda), z = sin(phi), w = atan2(sqrt$1((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z); W1 += w; X1 += w * (x0 + (x0 = x)); Y1 += w * (y0 + (y0 = y)); Z1 += w * (z0 + (z0 = z)); centroidPointCartesian(x0, y0, z0); } function centroidLineEnd() { centroidStream.point = centroidPoint; } // See J. E. Brock, The Inertia Tensor for a Spherical Triangle, // J. Applied Mechanics 42, 239 (1975). function centroidRingStart() { centroidStream.point = centroidRingPointFirst; } function centroidRingEnd() { centroidRingPoint(lambda00$2, phi00$2); centroidStream.point = centroidPoint; } function centroidRingPointFirst(lambda, phi) { lambda00$2 = lambda, phi00$2 = phi; lambda *= radians, phi *= radians; centroidStream.point = centroidRingPoint; var cosPhi = cos(phi); x0 = cosPhi * cos(lambda); y0 = cosPhi * sin(lambda); z0 = sin(phi); centroidPointCartesian(x0, y0, z0); } function centroidRingPoint(lambda, phi) { lambda *= radians, phi *= radians; var cosPhi = cos(phi), x = cosPhi * cos(lambda), y = cosPhi * sin(lambda), z = sin(phi), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = sqrt$1(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -acos(u) / m, // area weight w = atan2(m, u); // line weight X2 += v * cx; Y2 += v * cy; Z2 += v * cz; W1 += w; X1 += w * (x0 + (x0 = x)); Y1 += w * (y0 + (y0 = y)); Z1 += w * (z0 + (z0 = z)); centroidPointCartesian(x0, y0, z0); } function compose(a, b) { function compose(x, y) { return x = a(x, y), b(x[0], x[1]); } if (a.invert && b.invert) compose.invert = function(x, y) { return x = b.invert(x, y), x && a.invert(x[0], x[1]); }; return compose; } function rotationIdentity(lambda, phi) { return [lambda > pi$3 ? lambda - tau$4 : lambda < -pi$3 ? lambda + tau$4 : lambda, phi]; } rotationIdentity.invert = rotationIdentity; function rotateRadians(deltaLambda, deltaPhi, deltaGamma) { return (deltaLambda %= tau$4) ? (deltaPhi || deltaGamma ? compose(rotationLambda(deltaLambda), rotationPhiGamma(deltaPhi, deltaGamma)) : rotationLambda(deltaLambda)) : (deltaPhi || deltaGamma ? rotationPhiGamma(deltaPhi, deltaGamma) : rotationIdentity); } function forwardRotationLambda(deltaLambda) { return function(lambda, phi) { return lambda += deltaLambda, [lambda > pi$3 ? lambda - tau$4 : lambda < -pi$3 ? lambda + tau$4 : lambda, phi]; }; } function rotationLambda(deltaLambda) { var rotation = forwardRotationLambda(deltaLambda); rotation.invert = forwardRotationLambda(-deltaLambda); return rotation; } function rotationPhiGamma(deltaPhi, deltaGamma) { var cosDeltaPhi = cos(deltaPhi), sinDeltaPhi = sin(deltaPhi), cosDeltaGamma = cos(deltaGamma), sinDeltaGamma = sin(deltaGamma); function rotation(lambda, phi) { var cosPhi = cos(phi), x = cos(lambda) * cosPhi, y = sin(lambda) * cosPhi, z = sin(phi), k = z * cosDeltaPhi + x * sinDeltaPhi; return [ atan2(y * cosDeltaGamma - k * sinDeltaGamma, x * cosDeltaPhi - z * sinDeltaPhi), asin$1(k * cosDeltaGamma + y * sinDeltaGamma) ]; } rotation.invert = function(lambda, phi) { var cosPhi = cos(phi), x = cos(lambda) * cosPhi, y = sin(lambda) * cosPhi, z = sin(phi), k = z * cosDeltaGamma - y * sinDeltaGamma; return [ atan2(y * cosDeltaGamma + z * sinDeltaGamma, x * cosDeltaPhi + k * sinDeltaPhi), asin$1(k * cosDeltaPhi - x * sinDeltaPhi) ]; }; return rotation; } // Generates a circle centered at [0°, 0°], with a given radius and precision. function circleStream(stream, radius, delta, direction, t0, t1) { if (!delta) return; var cosRadius = cos(radius), sinRadius = sin(radius), step = direction * delta; if (t0 == null) { t0 = radius + direction * tau$4; t1 = radius - step / 2; } else { t0 = circleRadius(cosRadius, t0); t1 = circleRadius(cosRadius, t1); if (direction > 0 ? t0 < t1 : t0 > t1) t0 += direction * tau$4; } for (var point, t = t0; direction > 0 ? t > t1 : t < t1; t -= step) { point = spherical([cosRadius, -sinRadius * cos(t), -sinRadius * sin(t)]); stream.point(point[0], point[1]); } } // Returns the signed angle of a cartesian point relative to [cosRadius, 0, 0]. function circleRadius(cosRadius, point) { point = cartesian(point), point[0] -= cosRadius; cartesianNormalizeInPlace(point); var radius = acos(-point[1]); return ((-point[2] < 0 ? -radius : radius) + tau$4 - epsilon$2) % tau$4; } function clipBuffer() { var lines = [], line; return { point: function(x, y) { line.push([x, y]); }, lineStart: function() { lines.push(line = []); }, lineEnd: noop$4, rejoin: function() { if (lines.length > 1) lines.push(lines.pop().concat(lines.shift())); }, result: function() { var result = lines; lines = []; line = null; return result; } }; } function clipLine(a, b, x0, y0, x1, y1) { var ax = a[0], ay = a[1], bx = b[0], by = b[1], t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; r = x0 - ax; if (!dx && r > 0) return; r /= dx; if (dx < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dx > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = x1 - ax; if (!dx && r < 0) return; r /= dx; if (dx < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dx > 0) { if (r < t0) return; if (r < t1) t1 = r; } r = y0 - ay; if (!dy && r > 0) return; r /= dy; if (dy < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dy > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = y1 - ay; if (!dy && r < 0) return; r /= dy; if (dy < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dy > 0) { if (r < t0) return; if (r < t1) t1 = r; } if (t0 > 0) a[0] = ax + t0 * dx, a[1] = ay + t0 * dy; if (t1 < 1) b[0] = ax + t1 * dx, b[1] = ay + t1 * dy; return true; } function pointEqual(a, b) { return abs(a[0] - b[0]) < epsilon$2 && abs(a[1] - b[1]) < epsilon$2; } function Intersection(point, points, other, entry) { this.x = point; this.z = points; this.o = other; // another intersection this.e = entry; // is an entry? this.v = false; // visited this.n = this.p = null; // next & previous } // A generalized polygon clipping algorithm: given a polygon that has been cut // into its visible line segments, and rejoins the segments by interpolating // along the clip edge. function clipPolygon(segments, compareIntersection, startInside, interpolate, stream) { var subject = [], clip = [], i, n; segments.forEach(function(segment) { if ((n = segment.length - 1) <= 0) return; var n, p0 = segment[0], p1 = segment[n], x; // If the first and last points of a segment are coincident, then treat as a // closed ring. TODO if all rings are closed, then the winding order of the // exterior ring should be checked. if (pointEqual(p0, p1)) { stream.lineStart(); for (i = 0; i < n; ++i) stream.point((p0 = segment[i])[0], p0[1]); stream.lineEnd(); return; } subject.push(x = new Intersection(p0, segment, null, true)); clip.push(x.o = new Intersection(p0, null, x, false)); subject.push(x = new Intersection(p1, segment, null, false)); clip.push(x.o = new Intersection(p1, null, x, true)); }); if (!subject.length) return; clip.sort(compareIntersection); link(subject); link(clip); for (i = 0, n = clip.length; i < n; ++i) { clip[i].e = startInside = !startInside; } var start = subject[0], points, point; while (1) { // Find first unvisited intersection. var current = start, isSubject = true; while (current.v) if ((current = current.n) === start) return; points = current.z; stream.lineStart(); do { current.v = current.o.v = true; if (current.e) { if (isSubject) { for (i = 0, n = points.length; i < n; ++i) stream.point((point = points[i])[0], point[1]); } else { interpolate(current.x, current.n.x, 1, stream); } current = current.n; } else { if (isSubject) { points = current.p.z; for (i = points.length - 1; i >= 0; --i) stream.point((point = points[i])[0], point[1]); } else { interpolate(current.x, current.p.x, -1, stream); } current = current.p; } current = current.o; points = current.z; isSubject = !isSubject; } while (!current.v); stream.lineEnd(); } } function link(array) { if (!(n = array.length)) return; var n, i = 0, a = array[0], b; while (++i < n) { a.n = b = array[i]; b.p = a; a = b; } a.n = b = array[0]; b.p = a; } var clipMax = 1e9; var clipMin = -clipMax; // TODO Use d3-polygon’s polygonContains here for the ring check? // TODO Eliminate duplicate buffering in clipBuffer and polygon.push? function clipExtent(x0, y0, x1, y1) { function visible(x, y) { return x0 <= x && x <= x1 && y0 <= y && y <= y1; } function interpolate(from, to, direction, stream) { var a = 0, a1 = 0; if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoint(from, to) < 0 ^ direction > 0) { do stream.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0); while ((a = (a + direction + 4) % 4) !== a1); } else { stream.point(to[0], to[1]); } } function corner(p, direction) { return abs(p[0] - x0) < epsilon$2 ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < epsilon$2 ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < epsilon$2 ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2; // abs(p[1] - y1) < epsilon } function compareIntersection(a, b) { return comparePoint(a.x, b.x); } function comparePoint(a, b) { var ca = corner(a, 1), cb = corner(b, 1); return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0]; } return function(stream) { var activeStream = stream, bufferStream = clipBuffer(), segments, polygon, ring, x__, y__, v__, // first point x_, y_, v_, // previous point first, clean; var clipStream = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: polygonStart, polygonEnd: polygonEnd }; function point(x, y) { if (visible(x, y)) activeStream.point(x, y); } function polygonInside() { var winding = 0; for (var i = 0, n = polygon.length; i < n; ++i) { for (var ring = polygon[i], j = 1, m = ring.length, point = ring[0], a0, a1, b0 = point[0], b1 = point[1]; j < m; ++j) { a0 = b0, a1 = b1, point = ring[j], b0 = point[0], b1 = point[1]; if (a1 <= y1) { if (b1 > y1 && (b0 - a0) * (y1 - a1) > (b1 - a1) * (x0 - a0)) ++winding; } else { if (b1 <= y1 && (b0 - a0) * (y1 - a1) < (b1 - a1) * (x0 - a0)) --winding; } } } return winding; } // Buffer geometry within a polygon and then clip it en masse. function polygonStart() { activeStream = bufferStream, segments = [], polygon = [], clean = true; } function polygonEnd() { var startInside = polygonInside(), cleanInside = clean && startInside, visible = (segments = merge(segments)).length; if (cleanInside || visible) { stream.polygonStart(); if (cleanInside) { stream.lineStart(); interpolate(null, null, 1, stream); stream.lineEnd(); } if (visible) { clipPolygon(segments, compareIntersection, startInside, interpolate, stream); } stream.polygonEnd(); } activeStream = stream, segments = polygon = ring = null; } function lineStart() { clipStream.point = linePoint; if (polygon) polygon.push(ring = []); first = true; v_ = false; x_ = y_ = NaN; } // TODO rather than special-case polygons, simply handle them separately. // Ideally, coincident intersection points should be jittered to avoid // clipping issues. function lineEnd() { if (segments) { linePoint(x__, y__); if (v__ && v_) bufferStream.rejoin(); segments.push(bufferStream.result()); } clipStream.point = point; if (v_) activeStream.lineEnd(); } function linePoint(x, y) { var v = visible(x, y); if (polygon) ring.push([x, y]); if (first) { x__ = x, y__ = y, v__ = v; first = false; if (v) { activeStream.lineStart(); activeStream.point(x, y); } } else { if (v && v_) activeStream.point(x, y); else { var a = [x_ = Math.max(clipMin, Math.min(clipMax, x_)), y_ = Math.max(clipMin, Math.min(clipMax, y_))], b = [x = Math.max(clipMin, Math.min(clipMax, x)), y = Math.max(clipMin, Math.min(clipMax, y))]; if (clipLine(a, b, x0, y0, x1, y1)) { if (!v_) { activeStream.lineStart(); activeStream.point(a[0], a[1]); } activeStream.point(b[0], b[1]); if (!v) activeStream.lineEnd(); clean = false; } else if (v) { activeStream.lineStart(); activeStream.point(x, y); clean = false; } } } x_ = x, y_ = y, v_ = v; } return clipStream; }; } var lengthSum = adder(); var lambda0$2; var sinPhi0$1; var cosPhi0$1; var lengthStream = { sphere: noop$4, point: noop$4, lineStart: lengthLineStart, lineEnd: noop$4, polygonStart: noop$4, polygonEnd: noop$4 }; function lengthLineStart() { lengthStream.point = lengthPointFirst; lengthStream.lineEnd = lengthLineEnd; } function lengthLineEnd() { lengthStream.point = lengthStream.lineEnd = noop$4; } function lengthPointFirst(lambda, phi) { lambda *= radians, phi *= radians; lambda0$2 = lambda, sinPhi0$1 = sin(phi), cosPhi0$1 = cos(phi); lengthStream.point = lengthPoint; } function lengthPoint(lambda, phi) { lambda *= radians, phi *= radians; var sinPhi = sin(phi), cosPhi = cos(phi), delta = abs(lambda - lambda0$2), cosDelta = cos(delta), sinDelta = sin(delta), x = cosPhi * sinDelta, y = cosPhi0$1 * sinPhi - sinPhi0$1 * cosPhi * cosDelta, z = sinPhi0$1 * sinPhi + cosPhi0$1 * cosPhi * cosDelta; lengthSum.add(atan2(sqrt$1(x * x + y * y), z)); lambda0$2 = lambda, sinPhi0$1 = sinPhi, cosPhi0$1 = cosPhi; } function graticuleX(y0, y1, dy) { var y = range(y0, y1 - epsilon$2, dy).concat(y1); return function(x) { return y.map(function(y) { return [x, y]; }); }; } function graticuleY(x0, x1, dx) { var x = range(x0, x1 - epsilon$2, dx).concat(x1); return function(y) { return x.map(function(x) { return [x, y]; }); }; } function geoGraticule() { var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5; function graticule() { return {type: "MultiLineString", coordinates: lines()}; } function lines() { return range(ceil(X0 / DX) * DX, X1, DX).map(X) .concat(range(ceil(Y0 / DY) * DY, Y1, DY).map(Y)) .concat(range(ceil(x0 / dx) * dx, x1, dx).filter(function(x) { return abs(x % DX) > epsilon$2; }).map(x)) .concat(range(ceil(y0 / dy) * dy, y1, dy).filter(function(y) { return abs(y % DY) > epsilon$2; }).map(y)); } graticule.lines = function() { return lines().map(function(coordinates) { return {type: "LineString", coordinates: coordinates}; }); }; graticule.outline = function() { return { type: "Polygon", coordinates: [ X(X0).concat( Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ] }; }; graticule.extent = function(_) { if (!arguments.length) return graticule.extentMinor(); return graticule.extentMajor(_).extentMinor(_); }; graticule.extentMajor = function(_) { if (!arguments.length) return [[X0, Y0], [X1, Y1]]; X0 = +_[0][0], X1 = +_[1][0]; Y0 = +_[0][1], Y1 = +_[1][1]; if (X0 > X1) _ = X0, X0 = X1, X1 = _; if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _; return graticule.precision(precision); }; graticule.extentMinor = function(_) { if (!arguments.length) return [[x0, y0], [x1, y1]]; x0 = +_[0][0], x1 = +_[1][0]; y0 = +_[0][1], y1 = +_[1][1]; if (x0 > x1) _ = x0, x0 = x1, x1 = _; if (y0 > y1) _ = y0, y0 = y1, y1 = _; return graticule.precision(precision); }; graticule.step = function(_) { if (!arguments.length) return graticule.stepMinor(); return graticule.stepMajor(_).stepMinor(_); }; graticule.stepMajor = function(_) { if (!arguments.length) return [DX, DY]; DX = +_[0], DY = +_[1]; return graticule; }; graticule.stepMinor = function(_) { if (!arguments.length) return [dx, dy]; dx = +_[0], dy = +_[1]; return graticule; }; graticule.precision = function(_) { if (!arguments.length) return precision; precision = +_; x = graticuleX(y0, y1, 90); y = graticuleY(x0, x1, precision); X = graticuleX(Y0, Y1, 90); Y = graticuleY(X0, X1, precision); return graticule; }; return graticule .extentMajor([[-180, -90 + epsilon$2], [180, 90 - epsilon$2]]) .extentMinor([[-180, -80 - epsilon$2], [180, 80 + epsilon$2]]); } function identity$6(x) { return x; } var areaSum$1 = adder(); var areaRingSum$1 = adder(); var x00; var y00; var x0$1; var y0$1; var areaStream$1 = { point: noop$4, lineStart: noop$4, lineEnd: noop$4, polygonStart: function() { areaStream$1.lineStart = areaRingStart$1; areaStream$1.lineEnd = areaRingEnd$1; }, polygonEnd: function() { areaStream$1.lineStart = areaStream$1.lineEnd = areaStream$1.point = noop$4; areaSum$1.add(abs(areaRingSum$1)); areaRingSum$1.reset(); }, result: function() { var area = areaSum$1 / 2; areaSum$1.reset(); return area; } }; function areaRingStart$1() { areaStream$1.point = areaPointFirst$1; } function areaPointFirst$1(x, y) { areaStream$1.point = areaPoint$1; x00 = x0$1 = x, y00 = y0$1 = y; } function areaPoint$1(x, y) { areaRingSum$1.add(y0$1 * x - x0$1 * y); x0$1 = x, y0$1 = y; } function areaRingEnd$1() { areaPoint$1(x00, y00); } var x0$2 = Infinity; var y0$2 = x0$2; var x1 = -x0$2; var y1 = x1; var boundsStream$1 = { point: boundsPoint$1, lineStart: noop$4, lineEnd: noop$4, polygonStart: noop$4, polygonEnd: noop$4, result: function() { var bounds = [[x0$2, y0$2], [x1, y1]]; x1 = y1 = -(y0$2 = x0$2 = Infinity); return bounds; } }; function boundsPoint$1(x, y) { if (x < x0$2) x0$2 = x; if (x > x1) x1 = x; if (y < y0$2) y0$2 = y; if (y > y1) y1 = y; } var X0$1 = 0; var Y0$1 = 0; var Z0$1 = 0; var X1$1 = 0; var Y1$1 = 0; var Z1$1 = 0; var X2$1 = 0; var Y2$1 = 0; var Z2$1 = 0; var x00$1; var y00$1; var x0$3; var y0$3; var centroidStream$1 = { point: centroidPoint$1, lineStart: centroidLineStart$1, lineEnd: centroidLineEnd$1, polygonStart: function() { centroidStream$1.lineStart = centroidRingStart$1; centroidStream$1.lineEnd = centroidRingEnd$1; }, polygonEnd: function() { centroidStream$1.point = centroidPoint$1; centroidStream$1.lineStart = centroidLineStart$1; centroidStream$1.lineEnd = centroidLineEnd$1; }, result: function() { var centroid = Z2$1 ? [X2$1 / Z2$1, Y2$1 / Z2$1] : Z1$1 ? [X1$1 / Z1$1, Y1$1 / Z1$1] : Z0$1 ? [X0$1 / Z0$1, Y0$1 / Z0$1] : [NaN, NaN]; X0$1 = Y0$1 = Z0$1 = X1$1 = Y1$1 = Z1$1 = X2$1 = Y2$1 = Z2$1 = 0; return centroid; } }; function centroidPoint$1(x, y) { X0$1 += x; Y0$1 += y; ++Z0$1; } function centroidLineStart$1() { centroidStream$1.point = centroidPointFirstLine; } function centroidPointFirstLine(x, y) { centroidStream$1.point = centroidPointLine; centroidPoint$1(x0$3 = x, y0$3 = y); } function centroidPointLine(x, y) { var dx = x - x0$3, dy = y - y0$3, z = sqrt$1(dx * dx + dy * dy); X1$1 += z * (x0$3 + x) / 2; Y1$1 += z * (y0$3 + y) / 2; Z1$1 += z; centroidPoint$1(x0$3 = x, y0$3 = y); } function centroidLineEnd$1() { centroidStream$1.point = centroidPoint$1; } function centroidRingStart$1() { centroidStream$1.point = centroidPointFirstRing; } function centroidRingEnd$1() { centroidPointRing(x00$1, y00$1); } function centroidPointFirstRing(x, y) { centroidStream$1.point = centroidPointRing; centroidPoint$1(x00$1 = x0$3 = x, y00$1 = y0$3 = y); } function centroidPointRing(x, y) { var dx = x - x0$3, dy = y - y0$3, z = sqrt$1(dx * dx + dy * dy); X1$1 += z * (x0$3 + x) / 2; Y1$1 += z * (y0$3 + y) / 2; Z1$1 += z; z = y0$3 * x - x0$3 * y; X2$1 += z * (x0$3 + x); Y2$1 += z * (y0$3 + y); Z2$1 += z * 3; centroidPoint$1(x0$3 = x, y0$3 = y); } function PathContext(context) { this._context = context; } PathContext.prototype = { _radius: 4.5, pointRadius: function(_) { return this._radius = _, this; }, polygonStart: function() { this._line = 0; }, polygonEnd: function() { this._line = NaN; }, lineStart: function() { this._point = 0; }, lineEnd: function() { if (this._line === 0) this._context.closePath(); this._point = NaN; }, point: function(x, y) { switch (this._point) { case 0: { this._context.moveTo(x, y); this._point = 1; break; } case 1: { this._context.lineTo(x, y); break; } default: { this._context.moveTo(x + this._radius, y); this._context.arc(x, y, this._radius, 0, tau$4); break; } } }, result: noop$4 }; function PathString() { this._string = []; } PathString.prototype = { _circle: circle$2(4.5), pointRadius: function(_) { return this._circle = circle$2(_), this; }, polygonStart: function() { this._line = 0; }, polygonEnd: function() { this._line = NaN; }, lineStart: function() { this._point = 0; }, lineEnd: function() { if (this._line === 0) this._string.push("Z"); this._point = NaN; }, point: function(x, y) { switch (this._point) { case 0: { this._string.push("M", x, ",", y); this._point = 1; break; } case 1: { this._string.push("L", x, ",", y); break; } default: { this._string.push("M", x, ",", y, this._circle); break; } } }, result: function() { if (this._string.length) { var result = this._string.join(""); this._string = []; return result; } } }; function circle$2(radius) { return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z"; } function geoPath() { var pointRadius = 4.5, projection, projectionStream, context, contextStream; function path(object) { if (object) { if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments)); geoStream(object, projectionStream(contextStream)); } return contextStream.result(); } path.area = function(object) { geoStream(object, projectionStream(areaStream$1)); return areaStream$1.result(); }; path.bounds = function(object) { geoStream(object, projectionStream(boundsStream$1)); return boundsStream$1.result(); }; path.centroid = function(object) { geoStream(object, projectionStream(centroidStream$1)); return centroidStream$1.result(); }; path.projection = function(_) { return arguments.length ? (projectionStream = (projection = _) == null ? identity$6 : _.stream, path) : projection; }; path.context = function(_) { if (!arguments.length) return context; contextStream = (context = _) == null ? new PathString : new PathContext(_); if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius); return path; }; path.pointRadius = function(_) { if (!arguments.length) return pointRadius; pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_); return path; }; return path.projection(null).context(null); } var sum$2 = adder(); function polygonContains(polygon, point) { var lambda = point[0], phi = point[1], normal = [sin(lambda), -cos(lambda), 0], angle = 0, winding = 0; sum$2.reset(); for (var i = 0, n = polygon.length; i < n; ++i) { if (!(m = (ring = polygon[i]).length)) continue; var ring, m, point0 = ring[m - 1], lambda0 = point0[0], phi0 = point0[1] / 2 + quarterPi, sinPhi0 = sin(phi0), cosPhi0 = cos(phi0); for (var j = 0; j < m; ++j, lambda0 = lambda1, sinPhi0 = sinPhi1, cosPhi0 = cosPhi1, point0 = point1) { var point1 = ring[j], lambda1 = point1[0], phi1 = point1[1] / 2 + quarterPi, sinPhi1 = sin(phi1), cosPhi1 = cos(phi1), delta = lambda1 - lambda0, sign = delta >= 0 ? 1 : -1, absDelta = sign * delta, antimeridian = absDelta > pi$3, k = sinPhi0 * sinPhi1; sum$2.add(atan2(k * sign * sin(absDelta), cosPhi0 * cosPhi1 + k * cos(absDelta))); angle += antimeridian ? delta + sign * tau$4 : delta; // Are the longitudes either side of the point’s meridian (lambda), // and are the latitudes smaller than the parallel (phi)? if (antimeridian ^ lambda0 >= lambda ^ lambda1 >= lambda) { var arc = cartesianCross(cartesian(point0), cartesian(point1)); cartesianNormalizeInPlace(arc); var intersection = cartesianCross(normal, arc); cartesianNormalizeInPlace(intersection); var phiArc = (antimeridian ^ delta >= 0 ? -1 : 1) * asin$1(intersection[2]); if (phi > phiArc || phi === phiArc && (arc[0] || arc[1])) { winding += antimeridian ^ delta >= 0 ? 1 : -1; } } } } // First, determine whether the South pole is inside or outside: // // It is inside if: // * the polygon winds around it in a clockwise direction. // * the polygon does not (cumulatively) wind around it, but has a negative // (counter-clockwise) area. // // Second, count the (signed) number of times a segment crosses a lambda // from the point to the South pole. If it is zero, then the point is the // same side as the South pole. return (angle < -epsilon$2 || angle < epsilon$2 && sum$2 < -epsilon$2) ^ (winding & 1); } function clip(pointVisible, clipLine, interpolate, start) { return function(rotate, sink) { var line = clipLine(sink), rotatedStart = rotate.invert(start[0], start[1]), ringBuffer = clipBuffer(), ringSink = clipLine(ringBuffer), polygonStarted = false, polygon, segments, ring; var clip = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { clip.point = pointRing; clip.lineStart = ringStart; clip.lineEnd = ringEnd; segments = []; polygon = []; }, polygonEnd: function() { clip.point = point; clip.lineStart = lineStart; clip.lineEnd = lineEnd; segments = merge(segments); var startInside = polygonContains(polygon, rotatedStart); if (segments.length) { if (!polygonStarted) sink.polygonStart(), polygonStarted = true; clipPolygon(segments, compareIntersection, startInside, interpolate, sink); } else if (startInside) { if (!polygonStarted) sink.polygonStart(), polygonStarted = true; sink.lineStart(); interpolate(null, null, 1, sink); sink.lineEnd(); } if (polygonStarted) sink.polygonEnd(), polygonStarted = false; segments = polygon = null; }, sphere: function() { sink.polygonStart(); sink.lineStart(); interpolate(null, null, 1, sink); sink.lineEnd(); sink.polygonEnd(); } }; function point(lambda, phi) { var point = rotate(lambda, phi); if (pointVisible(lambda = point[0], phi = point[1])) sink.point(lambda, phi); } function pointLine(lambda, phi) { var point = rotate(lambda, phi); line.point(point[0], point[1]); } function lineStart() { clip.point = pointLine; line.lineStart(); } function lineEnd() { clip.point = point; line.lineEnd(); } function pointRing(lambda, phi) { ring.push([lambda, phi]); var point = rotate(lambda, phi); ringSink.point(point[0], point[1]); } function ringStart() { ringSink.lineStart(); ring = []; } function ringEnd() { pointRing(ring[0][0], ring[0][1]); ringSink.lineEnd(); var clean = ringSink.clean(), ringSegments = ringBuffer.result(), i, n = ringSegments.length, m, segment, point; ring.pop(); polygon.push(ring); ring = null; if (!n) return; // No intersections. if (clean & 1) { segment = ringSegments[0]; if ((m = segment.length - 1) > 0) { if (!polygonStarted) sink.polygonStart(), polygonStarted = true; sink.lineStart(); for (i = 0; i < m; ++i) sink.point((point = segment[i])[0], point[1]); sink.lineEnd(); } return; } // Rejoin connected segments. // TODO reuse ringBuffer.rejoin()? if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift())); segments.push(ringSegments.filter(validSegment)); } return clip; }; } function validSegment(segment) { return segment.length > 1; } // Intersections are sorted along the clip edge. For both antimeridian cutting // and circle clipping, the same comparison is used. function compareIntersection(a, b) { return ((a = a.x)[0] < 0 ? a[1] - halfPi$2 - epsilon$2 : halfPi$2 - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfPi$2 - epsilon$2 : halfPi$2 - b[1]); } var clipAntimeridian = clip( function() { return true; }, clipAntimeridianLine, clipAntimeridianInterpolate, [-pi$3, -halfPi$2] ); // Takes a line and cuts into visible segments. Return values: 0 - there were // intersections or the line was empty; 1 - no intersections; 2 - there were // intersections, and the first and last segments should be rejoined. function clipAntimeridianLine(stream) { var lambda0 = NaN, phi0 = NaN, sign0 = NaN, clean; // no intersections return { lineStart: function() { stream.lineStart(); clean = 1; }, point: function(lambda1, phi1) { var sign1 = lambda1 > 0 ? pi$3 : -pi$3, delta = abs(lambda1 - lambda0); if (abs(delta - pi$3) < epsilon$2) { // line crosses a pole stream.point(lambda0, phi0 = (phi0 + phi1) / 2 > 0 ? halfPi$2 : -halfPi$2); stream.point(sign0, phi0); stream.lineEnd(); stream.lineStart(); stream.point(sign1, phi0); stream.point(lambda1, phi0); clean = 0; } else if (sign0 !== sign1 && delta >= pi$3) { // line crosses antimeridian if (abs(lambda0 - sign0) < epsilon$2) lambda0 -= sign0 * epsilon$2; // handle degeneracies if (abs(lambda1 - sign1) < epsilon$2) lambda1 -= sign1 * epsilon$2; phi0 = clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1); stream.point(sign0, phi0); stream.lineEnd(); stream.lineStart(); stream.point(sign1, phi0); clean = 0; } stream.point(lambda0 = lambda1, phi0 = phi1); sign0 = sign1; }, lineEnd: function() { stream.lineEnd(); lambda0 = phi0 = NaN; }, clean: function() { return 2 - clean; // if intersections, rejoin first and last segments } }; } function clipAntimeridianIntersect(lambda0, phi0, lambda1, phi1) { var cosPhi0, cosPhi1, sinLambda0Lambda1 = sin(lambda0 - lambda1); return abs(sinLambda0Lambda1) > epsilon$2 ? atan((sin(phi0) * (cosPhi1 = cos(phi1)) * sin(lambda1) - sin(phi1) * (cosPhi0 = cos(phi0)) * sin(lambda0)) / (cosPhi0 * cosPhi1 * sinLambda0Lambda1)) : (phi0 + phi1) / 2; } function clipAntimeridianInterpolate(from, to, direction, stream) { var phi; if (from == null) { phi = direction * halfPi$2; stream.point(-pi$3, phi); stream.point(0, phi); stream.point(pi$3, phi); stream.point(pi$3, 0); stream.point(pi$3, -phi); stream.point(0, -phi); stream.point(-pi$3, -phi); stream.point(-pi$3, 0); stream.point(-pi$3, phi); } else if (abs(from[0] - to[0]) > epsilon$2) { var lambda = from[0] < to[0] ? pi$3 : -pi$3; phi = direction * lambda / 2; stream.point(-lambda, phi); stream.point(0, phi); stream.point(lambda, phi); } else { stream.point(to[0], to[1]); } } function clipCircle(radius, delta) { var cr = cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > epsilon$2; // TODO optimise for this common case function interpolate(from, to, direction, stream) { circleStream(stream, radius, delta, direction, from, to); } function visible(lambda, phi) { return cos(lambda) * cos(phi) > cr; } // Takes a line and cuts into visible segments. Return values used for polygon // clipping: 0 - there were intersections or the line was empty; 1 - no // intersections 2 - there were intersections, and the first and last segments // should be rejoined. function clipLine(stream) { var point0, // previous point c0, // code for previous point v0, // visibility of previous point v00, // visibility of first point clean; // no intersections return { lineStart: function() { v00 = v0 = false; clean = 1; }, point: function(lambda, phi) { var point1 = [lambda, phi], point2, v = visible(lambda, phi), c = smallRadius ? v ? 0 : code(lambda, phi) : v ? code(lambda + (lambda < 0 ? pi$3 : -pi$3), phi) : 0; if (!point0 && (v00 = v0 = v)) stream.lineStart(); // Handle degeneracies. // TODO ignore if not clipping polygons. if (v !== v0) { point2 = intersect(point0, point1); if (pointEqual(point0, point2) || pointEqual(point1, point2)) { point1[0] += epsilon$2; point1[1] += epsilon$2; v = visible(point1[0], point1[1]); } } if (v !== v0) { clean = 0; if (v) { // outside going in stream.lineStart(); point2 = intersect(point1, point0); stream.point(point2[0], point2[1]); } else { // inside going out point2 = intersect(point0, point1); stream.point(point2[0], point2[1]); stream.lineEnd(); } point0 = point2; } else if (notHemisphere && point0 && smallRadius ^ v) { var t; // If the codes for two points are different, or are both zero, // and there this segment intersects with the small circle. if (!(c & c0) && (t = intersect(point1, point0, true))) { clean = 0; if (smallRadius) { stream.lineStart(); stream.point(t[0][0], t[0][1]); stream.point(t[1][0], t[1][1]); stream.lineEnd(); } else { stream.point(t[1][0], t[1][1]); stream.lineEnd(); stream.lineStart(); stream.point(t[0][0], t[0][1]); } } } if (v && (!point0 || !pointEqual(point0, point1))) { stream.point(point1[0], point1[1]); } point0 = point1, v0 = v, c0 = c; }, lineEnd: function() { if (v0) stream.lineEnd(); point0 = null; }, // Rejoin first and last segments if there were intersections and the first // and last points were visible. clean: function() { return clean | ((v00 && v0) << 1); } }; } // Intersects the great circle between a and b with the clip circle. function intersect(a, b, two) { var pa = cartesian(a), pb = cartesian(b); // We have two planes, n1.p = d1 and n2.p = d2. // Find intersection line p(t) = c1 n1 + c2 n2 + t (n1 ⨯ n2). var n1 = [1, 0, 0], // normal n2 = cartesianCross(pa, pb), n2n2 = cartesianDot(n2, n2), n1n2 = n2[0], // cartesianDot(n1, n2), determinant = n2n2 - n1n2 * n1n2; // Two polar points. if (!determinant) return !two && a; var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = cartesianCross(n1, n2), A = cartesianScale(n1, c1), B = cartesianScale(n2, c2); cartesianAddInPlace(A, B); // Solve |p(t)|^2 = 1. var u = n1xn2, w = cartesianDot(A, u), uu = cartesianDot(u, u), t2 = w * w - uu * (cartesianDot(A, A) - 1); if (t2 < 0) return; var t = sqrt$1(t2), q = cartesianScale(u, (-w - t) / uu); cartesianAddInPlace(q, A); q = spherical(q); if (!two) return q; // Two intersection points. var lambda0 = a[0], lambda1 = b[0], phi0 = a[1], phi1 = b[1], z; if (lambda1 < lambda0) z = lambda0, lambda0 = lambda1, lambda1 = z; var delta = lambda1 - lambda0, polar = abs(delta - pi$3) < epsilon$2, meridian = polar || delta < epsilon$2; if (!polar && phi1 < phi0) z = phi0, phi0 = phi1, phi1 = z; // Check that the first point is between a and b. if (meridian ? polar ? phi0 + phi1 > 0 ^ q[1] < (abs(q[0] - lambda0) < epsilon$2 ? phi0 : phi1) : phi0 <= q[1] && q[1] <= phi1 : delta > pi$3 ^ (lambda0 <= q[0] && q[0] <= lambda1)) { var q1 = cartesianScale(u, (-w + t) / uu); cartesianAddInPlace(q1, A); return [q, spherical(q1)]; } } // Generates a 4-bit vector representing the location of a point relative to // the small circle's bounding box. function code(lambda, phi) { var r = smallRadius ? radius : pi$3 - radius, code = 0; if (lambda < -r) code |= 1; // left else if (lambda > r) code |= 2; // right if (phi < -r) code |= 4; // below else if (phi > r) code |= 8; // above return code; } return clip(visible, clipLine, interpolate, smallRadius ? [0, -radius] : [-pi$3, radius - pi$3]); } function transform$2(prototype) { function T() {} var p = T.prototype = Object.create(Transform$1.prototype); for (var k in prototype) p[k] = prototype[k]; return function(stream) { var t = new T; t.stream = stream; return t; }; } function Transform$1() {} Transform$1.prototype = { point: function(x, y) { this.stream.point(x, y); }, sphere: function() { this.stream.sphere(); }, lineStart: function() { this.stream.lineStart(); }, lineEnd: function() { this.stream.lineEnd(); }, polygonStart: function() { this.stream.polygonStart(); }, polygonEnd: function() { this.stream.polygonEnd(); } }; function fit(project, extent, object) { var w = extent[1][0] - extent[0][0], h = extent[1][1] - extent[0][1], clip = project.clipExtent && project.clipExtent(); project .scale(150) .translate([0, 0]); if (clip != null) project.clipExtent(null); geoStream(object, project.stream(boundsStream$1)); var b = boundsStream$1.result(), k = Math.min(w / (b[1][0] - b[0][0]), h / (b[1][1] - b[0][1])), x = +extent[0][0] + (w - k * (b[1][0] + b[0][0])) / 2, y = +extent[0][1] + (h - k * (b[1][1] + b[0][1])) / 2; if (clip != null) project.clipExtent(clip); return project .scale(k * 150) .translate([x, y]); } function fitSize(project) { return function(size, object) { return fit(project, [[0, 0], size], object); }; } function fitExtent(project) { return function(extent, object) { return fit(project, extent, object); }; } var maxDepth = 16; var cosMinDistance = cos(30 * radians); // cos(minimum angular distance) function resample(project, delta2) { return +delta2 ? resample$1(project, delta2) : resampleNone(project); } function resampleNone(project) { return transform$2({ point: function(x, y) { x = project(x, y); this.stream.point(x[0], x[1]); } }); } function resample$1(project, delta2) { function resampleLineTo(x0, y0, lambda0, a0, b0, c0, x1, y1, lambda1, a1, b1, c1, depth, stream) { var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy; if (d2 > 4 * delta2 && depth--) { var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = sqrt$1(a * a + b * b + c * c), phi2 = asin$1(c /= m), lambda2 = abs(abs(c) - 1) < epsilon$2 || abs(lambda0 - lambda1) < epsilon$2 ? (lambda0 + lambda1) / 2 : atan2(b, a), p = project(lambda2, phi2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2; if (dz * dz / d2 > delta2 // perpendicular projected distance || abs((dx * dx2 + dy * dy2) / d2 - 0.5) > 0.3 // midpoint close to an end || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) { // angular distance resampleLineTo(x0, y0, lambda0, a0, b0, c0, x2, y2, lambda2, a /= m, b /= m, c, depth, stream); stream.point(x2, y2); resampleLineTo(x2, y2, lambda2, a, b, c, x1, y1, lambda1, a1, b1, c1, depth, stream); } } } return function(stream) { var lambda00, x00, y00, a00, b00, c00, // first point lambda0, x0, y0, a0, b0, c0; // previous point var resampleStream = { point: point, lineStart: lineStart, lineEnd: lineEnd, polygonStart: function() { stream.polygonStart(); resampleStream.lineStart = ringStart; }, polygonEnd: function() { stream.polygonEnd(); resampleStream.lineStart = lineStart; } }; function point(x, y) { x = project(x, y); stream.point(x[0], x[1]); } function lineStart() { x0 = NaN; resampleStream.point = linePoint; stream.lineStart(); } function linePoint(lambda, phi) { var c = cartesian([lambda, phi]), p = project(lambda, phi); resampleLineTo(x0, y0, lambda0, a0, b0, c0, x0 = p[0], y0 = p[1], lambda0 = lambda, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream); stream.point(x0, y0); } function lineEnd() { resampleStream.point = point; stream.lineEnd(); } function ringStart() { lineStart(); resampleStream.point = ringPoint; resampleStream.lineEnd = ringEnd; } function ringPoint(lambda, phi) { linePoint(lambda00 = lambda, phi), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0; resampleStream.point = linePoint; } function ringEnd() { resampleLineTo(x0, y0, lambda0, a0, b0, c0, x00, y00, lambda00, a00, b00, c00, maxDepth, stream); resampleStream.lineEnd = lineEnd; lineEnd(); } return resampleStream; }; } var transformRadians = transform$2({ point: function(x, y) { this.stream.point(x * radians, y * radians); } }); function projection(project) { return projectionMutator(function() { return project; })(); } function projectionMutator(projectAt) { var project, k = 150, // scale x = 480, y = 250, // translate dx, dy, lambda = 0, phi = 0, // center deltaLambda = 0, deltaPhi = 0, deltaGamma = 0, rotate, projectRotate, // rotate theta = null, preclip = clipAntimeridian, // clip angle x0 = null, y0, x1, y1, postclip = identity$6, // clip extent delta2 = 0.5, projectResample = resample(projectTransform, delta2), // precision cache, cacheStream; function projection(point) { point = projectRotate(point[0] * radians, point[1] * radians); return [point[0] * k + dx, dy - point[1] * k]; } function invert(point) { point = projectRotate.invert((point[0] - dx) / k, (dy - point[1]) / k); return point && [point[0] * degrees$1, point[1] * degrees$1]; } function projectTransform(x, y) { return x = project(x, y), [x[0] * k + dx, dy - x[1] * k]; } projection.stream = function(stream) { return cache && cacheStream === stream ? cache : cache = transformRadians(preclip(rotate, projectResample(postclip(cacheStream = stream)))); }; projection.clipAngle = function(_) { return arguments.length ? (preclip = +_ ? clipCircle(theta = _ * radians, 6 * radians) : (theta = null, clipAntimeridian), reset()) : theta * degrees$1; }; projection.clipExtent = function(_) { return arguments.length ? (postclip = _ == null ? (x0 = y0 = x1 = y1 = null, identity$6) : clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]), reset()) : x0 == null ? null : [[x0, y0], [x1, y1]]; }; projection.scale = function(_) { return arguments.length ? (k = +_, recenter()) : k; }; projection.translate = function(_) { return arguments.length ? (x = +_[0], y = +_[1], recenter()) : [x, y]; }; projection.center = function(_) { return arguments.length ? (lambda = _[0] % 360 * radians, phi = _[1] % 360 * radians, recenter()) : [lambda * degrees$1, phi * degrees$1]; }; projection.rotate = function(_) { return arguments.length ? (deltaLambda = _[0] % 360 * radians, deltaPhi = _[1] % 360 * radians, deltaGamma = _.length > 2 ? _[2] % 360 * radians : 0, recenter()) : [deltaLambda * degrees$1, deltaPhi * degrees$1, deltaGamma * degrees$1]; }; projection.precision = function(_) { return arguments.length ? (projectResample = resample(projectTransform, delta2 = _ * _), reset()) : sqrt$1(delta2); }; projection.fitExtent = fitExtent(projection); projection.fitSize = fitSize(projection); function recenter() { projectRotate = compose(rotate = rotateRadians(deltaLambda, deltaPhi, deltaGamma), project); var center = project(lambda, phi); dx = x - center[0] * k; dy = y + center[1] * k; return reset(); } function reset() { cache = cacheStream = null; return projection; } return function() { project = projectAt.apply(this, arguments); projection.invert = project.invert && invert; return recenter(); }; } function conicProjection(projectAt) { var phi0 = 0, phi1 = pi$3 / 3, m = projectionMutator(projectAt), p = m(phi0, phi1); p.parallels = function(_) { return arguments.length ? m(phi0 = _[0] * radians, phi1 = _[1] * radians) : [phi0 * degrees$1, phi1 * degrees$1]; }; return p; } function conicEqualAreaRaw(y0, y1) { var sy0 = sin(y0), n = (sy0 + sin(y1)) / 2, c = 1 + sy0 * (2 * n - sy0), r0 = sqrt$1(c) / n; function project(x, y) { var r = sqrt$1(c - 2 * n * sin(y)) / n; return [r * sin(x *= n), r0 - r * cos(x)]; } project.invert = function(x, y) { var r0y = r0 - y; return [atan2(x, r0y) / n, asin$1((c - (x * x + r0y * r0y) * n * n) / (2 * n))]; }; return project; } function geoConicEqualArea() { return conicProjection(conicEqualAreaRaw) .scale(155.424) .center([0, 33.6442]); } function geoAlbers() { return geoConicEqualArea() .parallels([29.5, 45.5]) .scale(1070) .translate([480, 250]) .rotate([96, 0]) .center([-0.6, 38.7]); } // The projections must have mutually exclusive clip regions on the sphere, // as this will avoid emitting interleaving lines and polygons. function multiplex(streams) { var n = streams.length; return { point: function(x, y) { var i = -1; while (++i < n) streams[i].point(x, y); }, sphere: function() { var i = -1; while (++i < n) streams[i].sphere(); }, lineStart: function() { var i = -1; while (++i < n) streams[i].lineStart(); }, lineEnd: function() { var i = -1; while (++i < n) streams[i].lineEnd(); }, polygonStart: function() { var i = -1; while (++i < n) streams[i].polygonStart(); }, polygonEnd: function() { var i = -1; while (++i < n) streams[i].polygonEnd(); } }; } // A composite projection for the United States, configured by default for // 960×500. The projection also works quite well at 960×600 if you change the // scale to 1285 and adjust the translate accordingly. The set of standard // parallels for each region comes from USGS, which is published here: // http://egsc.usgs.gov/isb/pubs/MapProjections/projections.html#albers function geoAlbersUsa() { var cache, cacheStream, lower48 = geoAlbers(), lower48Point, alaska = geoConicEqualArea().rotate([154, 0]).center([-2, 58.5]).parallels([55, 65]), alaskaPoint, // EPSG:3338 hawaii = geoConicEqualArea().rotate([157, 0]).center([-3, 19.9]).parallels([8, 18]), hawaiiPoint, // ESRI:102007 point, pointStream = {point: function(x, y) { point = [x, y]; }}; function albersUsa(coordinates) { var x = coordinates[0], y = coordinates[1]; return point = null, (lower48Point.point(x, y), point) || (alaskaPoint.point(x, y), point) || (hawaiiPoint.point(x, y), point); } albersUsa.invert = function(coordinates) { var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k; return (y >= 0.120 && y < 0.234 && x >= -0.425 && x < -0.214 ? alaska : y >= 0.166 && y < 0.234 && x >= -0.214 && x < -0.115 ? hawaii : lower48).invert(coordinates); }; albersUsa.stream = function(stream) { return cache && cacheStream === stream ? cache : cache = multiplex([lower48.stream(cacheStream = stream), alaska.stream(stream), hawaii.stream(stream)]); }; albersUsa.precision = function(_) { if (!arguments.length) return lower48.precision(); lower48.precision(_), alaska.precision(_), hawaii.precision(_); return reset(); }; albersUsa.scale = function(_) { if (!arguments.length) return lower48.scale(); lower48.scale(_), alaska.scale(_ * 0.35), hawaii.scale(_); return albersUsa.translate(lower48.translate()); }; albersUsa.translate = function(_) { if (!arguments.length) return lower48.translate(); var k = lower48.scale(), x = +_[0], y = +_[1]; lower48Point = lower48 .translate(_) .clipExtent([[x - 0.455 * k, y - 0.238 * k], [x + 0.455 * k, y + 0.238 * k]]) .stream(pointStream); alaskaPoint = alaska .translate([x - 0.307 * k, y + 0.201 * k]) .clipExtent([[x - 0.425 * k + epsilon$2, y + 0.120 * k + epsilon$2], [x - 0.214 * k - epsilon$2, y + 0.234 * k - epsilon$2]]) .stream(pointStream); hawaiiPoint = hawaii .translate([x - 0.205 * k, y + 0.212 * k]) .clipExtent([[x - 0.214 * k + epsilon$2, y + 0.166 * k + epsilon$2], [x - 0.115 * k - epsilon$2, y + 0.234 * k - epsilon$2]]) .stream(pointStream); return reset(); }; albersUsa.fitExtent = fitExtent(albersUsa); albersUsa.fitSize = fitSize(albersUsa); function reset() { cache = cacheStream = null; return albersUsa; } return albersUsa.scale(1070); } function azimuthalRaw(scale) { return function(x, y) { var cx = cos(x), cy = cos(y), k = scale(cx * cy); return [ k * cy * sin(x), k * sin(y) ]; } } function azimuthalInvert(angle) { return function(x, y) { var z = sqrt$1(x * x + y * y), c = angle(z), sc = sin(c), cc = cos(c); return [ atan2(x * sc, z * cc), asin$1(z && y * sc / z) ]; } } var azimuthalEqualAreaRaw = azimuthalRaw(function(cxcy) { return sqrt$1(2 / (1 + cxcy)); }); azimuthalEqualAreaRaw.invert = azimuthalInvert(function(z) { return 2 * asin$1(z / 2); }); function geoAzimuthalEqualArea() { return projection(azimuthalEqualAreaRaw) .scale(124.75) .clipAngle(180 - 1e-3); } var azimuthalEquidistantRaw = azimuthalRaw(function(c) { return (c = acos(c)) && c / sin(c); }); azimuthalEquidistantRaw.invert = azimuthalInvert(function(z) { return z; }); function geoAzimuthalEquidistant() { return projection(azimuthalEquidistantRaw) .scale(79.4188) .clipAngle(180 - 1e-3); } function mercatorRaw(lambda, phi) { return [lambda, log$2(tan((halfPi$2 + phi) / 2))]; } mercatorRaw.invert = function(x, y) { return [x, 2 * atan(exp(y)) - halfPi$2]; }; function geoMercator() { return mercatorProjection(mercatorRaw) .scale(961 / tau$4); } function mercatorProjection(project) { var m = projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto; m.scale = function(_) { return arguments.length ? (scale(_), clipAuto && m.clipExtent(null), m) : scale(); }; m.translate = function(_) { return arguments.length ? (translate(_), clipAuto && m.clipExtent(null), m) : translate(); }; m.clipExtent = function(_) { if (!arguments.length) return clipAuto ? null : clipExtent(); if (clipAuto = _ == null) { var k = pi$3 * scale(), t = translate(); _ = [[t[0] - k, t[1] - k], [t[0] + k, t[1] + k]]; } clipExtent(_); return m; }; return m.clipExtent(null); } function tany(y) { return tan((halfPi$2 + y) / 2); } function conicConformalRaw(y0, y1) { var cy0 = cos(y0), n = y0 === y1 ? sin(y0) : log$2(cy0 / cos(y1)) / log$2(tany(y1) / tany(y0)), f = cy0 * pow$1(tany(y0), n) / n; if (!n) return mercatorRaw; function project(x, y) { if (f > 0) { if (y < -halfPi$2 + epsilon$2) y = -halfPi$2 + epsilon$2; } else { if (y > halfPi$2 - epsilon$2) y = halfPi$2 - epsilon$2; } var r = f / pow$1(tany(y), n); return [r * sin(n * x), f - r * cos(n * x)]; } project.invert = function(x, y) { var fy = f - y, r = sign$1(n) * sqrt$1(x * x + fy * fy); return [atan2(x, fy) / n, 2 * atan(pow$1(f / r, 1 / n)) - halfPi$2]; }; return project; } function geoConicConformal() { return conicProjection(conicConformalRaw) .scale(109.5) .parallels([30, 30]); } function equirectangularRaw(lambda, phi) { return [lambda, phi]; } equirectangularRaw.invert = equirectangularRaw; function geoEquirectangular() { return projection(equirectangularRaw) .scale(152.63); } function conicEquidistantRaw(y0, y1) { var cy0 = cos(y0), n = y0 === y1 ? sin(y0) : (cy0 - cos(y1)) / (y1 - y0), g = cy0 / n + y0; if (abs(n) < epsilon$2) return equirectangularRaw; function project(x, y) { var gy = g - y, nx = n * x; return [gy * sin(nx), g - gy * cos(nx)]; } project.invert = function(x, y) { var gy = g - y; return [atan2(x, gy) / n, g - sign$1(n) * sqrt$1(x * x + gy * gy)]; }; return project; } function geoConicEquidistant() { return conicProjection(conicEquidistantRaw) .scale(131.154) .center([0, 13.9389]); } function gnomonicRaw(x, y) { var cy = cos(y), k = cos(x) * cy; return [cy * sin(x) / k, sin(y) / k]; } gnomonicRaw.invert = azimuthalInvert(atan); function geoGnomonic() { return projection(gnomonicRaw) .scale(144.049) .clipAngle(60); } function orthographicRaw(x, y) { return [cos(y) * sin(x), sin(y)]; } orthographicRaw.invert = azimuthalInvert(asin$1); function geoOrthographic() { return projection(orthographicRaw) .scale(249.5) .clipAngle(90 + epsilon$2); } function stereographicRaw(x, y) { var cy = cos(y), k = 1 + cos(x) * cy; return [cy * sin(x) / k, sin(y) / k]; } stereographicRaw.invert = azimuthalInvert(function(z) { return 2 * atan(z); }); function geoStereographic() { return projection(stereographicRaw) .scale(250) .clipAngle(142); } function transverseMercatorRaw(lambda, phi) { return [log$2(tan((halfPi$2 + phi) / 2)), -lambda]; } transverseMercatorRaw.invert = function(x, y) { return [-y, 2 * atan(exp(x)) - halfPi$2]; }; function geoTransverseMercator() { var m = mercatorProjection(transverseMercatorRaw), center = m.center, rotate = m.rotate; m.center = function(_) { return arguments.length ? center([-_[1], _[0]]) : (_ = center(), [_[1], -_[0]]); }; m.rotate = function(_) { return arguments.length ? rotate([_[0], _[1], _.length > 2 ? _[2] + 90 : 90]) : (_ = rotate(), [_[0], _[1], _[2] - 90]); }; return rotate([0, 0, 90]) .scale(159.155); } /** * Map GeoJSON data to an SVG path string. * @constructor * @param {object} params - The parameters for this operator. * @param {function(number, number): *} params.projection - The cartographic * projection to apply. * @param {number} params.pointRadius - The point radius for path points. * @param {function(object): *} [params.field] - The field with GeoJSON data, * or null if the tuple itself is a GeoJSON feature. * @param {string} [params.as='path'] - The output field in which to store * the generated path data (default 'path'). */ function GeoPath(params) { Transform.call(this, null, params); } var prototype$42 = inherits(GeoPath, Transform); prototype$42.transform = function(_, pulse) { var out = pulse.fork(pulse.ALL), path = this.value, field = _.field || identity$1, as = _.as || 'path', mod; function set(t) { t[as] = path(field(t)); } if (!path || _.modified()) { // parameters updated, reset and reflow this.value = path = geoPath() .pointRadius(_.pointRadius) .projection(_.projection); out.materialize().reflow().visit(out.SOURCE, set); } else { mod = field === identity$1 || pulse.modified(field.fields); out.visit(mod ? out.ADD_MOD : out.ADD, set); } return out.modifies(as); }; /** * Geo-code a longitude/latitude point to an x/y coordinate. * @constructor * @param {object} params - The parameters for this operator. * @param {function(number, number): *} params.projection - The cartographic * projection to apply. * @param {Array<function(object): *>} params.fields - A two-element array of * field accessors for the longitude and latitude values. * @param {Array<string>} [params.as] - A two-element array of field names * under which to store the result. Defaults to ['x','y']. */ function GeoPoint(params) { Transform.call(this, null, params); } var prototype$43 = inherits(GeoPoint, Transform); prototype$43.transform = function(_, pulse) { var proj = _.projection, lon = _.fields[0], lat = _.fields[1], as = _.as || ['x', 'y'], x = as[0], y = as[1], mod; function set(t) { var xy = proj([lon(t), lat(t)]); if (xy) t[x] = xy[0], t[y] = xy[1]; else t[x] = undefined, t[y] = undefined; } if (_.modified()) { // parameters updated, reflow pulse.materialize().reflow(true).visit(pulse.SOURCE, set); } else { mod = pulse.modified(lon.fields) || pulse.modified(lat.fields); pulse.visit(mod ? pulse.ADD_MOD : pulse.ADD, set); } return pulse.modifies(as); }; /** * Annotate items with a geopath shape generator. * @constructor * @param {object} params - The parameters for this operator. * @param {function(number, number): *} params.projection - The cartographic * projection to apply. * @param {number} params.pointRadius - The point radius for path points. * @param {function(object): *} [params.field] - The field with GeoJSON data, * or null if the tuple itself is a GeoJSON feature. * @param {string} [params.as='path'] - The output field in which to store * the generated path data (default 'path'). */ function GeoShape(params) { Transform.call(this, null, params); } var prototype$44 = inherits(GeoShape, Transform); prototype$44.transform = function(_, pulse) { var out = pulse.fork(pulse.ALL), shape = this.value, datum = _.field || field('datum'), as = _.as || 'shape', flag = out.ADD_MOD; if (!shape || _.modified()) { // parameters updated, reset and reflow this.value = shape = shapeGenerator( geoPath().pointRadius(_.pointRadius).projection(_.projection), datum ); out.materialize().reflow(); flag = out.SOURCE; } out.visit(flag, function(t) { t[as] = shape; }); return out.modifies(as); }; function shapeGenerator(path, field) { var shape = function(_) { return path(field(_)); }; shape.context = function(_) { return path.context(_), shape; }; return shape; } /** * GeoJSON feature generator for creating graticules. * @constructor */ function Graticule(params) { Transform.call(this, [], params); this.generator = geoGraticule(); } var prototype$45 = inherits(Graticule, Transform); prototype$45.transform = function(_, pulse) { var out = pulse.fork(), src = this.value, gen = this.generator, t; if (!src.length || _.modified()) { for (var prop in _) { if (isFunction(gen[prop])) { gen[prop](_[prop]); } } } t = gen(); if (src.length) { t._id = src[0]._id; out.mod.push(t); } else { out.add.push(ingest(t)); } src[0] = t; return out.source = src, out; }; var properties = [ // standard properties in d3-geo 'clipAngle', 'clipExtent', 'scale', 'translate', 'center', 'rotate', 'parallels', 'precision', // extended properties in d3-geo-projections 'coefficient', 'distance', 'fraction', 'lobes', 'parallel', 'radius', 'ratio', 'spacing', 'tilt' ]; /** * Augment projections with their type and a copy method. */ function create$3(type, constructor) { return function projection() { var p = constructor(); p.type = type; p.copy = p.copy || function() { var c = projection(); properties.forEach(function(prop) { if (p.hasOwnProperty(prop)) c[prop](p[prop]()); }); return c; }; return p; }; } function projection$1(type, proj) { return arguments.length > 1 ? (projections[type] = create$3(type, proj), this) : projections.hasOwnProperty(type) ? projections[type] : null; } var projections = { // base d3-geo projection types albers: geoAlbers, albersusa: geoAlbersUsa, azimuthalequalarea: geoAzimuthalEqualArea, azimuthalequidistant: geoAzimuthalEquidistant, conicconformal: geoConicConformal, conicequalarea: geoConicEqualArea, conicequidistant: geoConicEquidistant, equirectangular: geoEquirectangular, gnomonic: geoGnomonic, mercator: geoMercator, orthographic: geoOrthographic, stereographic: geoStereographic, transversemercator: geoTransverseMercator }; for (var key$3 in projections) { projection$1(key$3, projections[key$3]); } /** * Maintains a cartographic projection. * @constructor * @param {object} params - The parameters for this operator. */ function Projection(params) { Transform.call(this, null, params); this.modified(true); // always treat as modified } var prototype$46 = inherits(Projection, Transform); prototype$46.transform = function(_) { var proj = this.value; if (!proj || _.modified('type')) { this.value = (proj = create$2(_.type)); properties.forEach(function(prop) { if (_[prop] != null) set$2(proj, prop, _[prop]); }); } else { properties.forEach(function(prop) { if (_.modified(prop)) set$2(proj, prop, _[prop]); }); } }; function create$2(type) { var constructor = projection$1((type || 'mercator').toLowerCase()); if (!constructor) error('Unrecognized projection type: ' + type); return constructor(); } function set$2(proj, key, value) { if (isFunction(proj[key])) proj[key](value); } var GeoPathDefinition = { "type": "GeoPath", "metadata": {"modifies": true}, "params": [ { "name": "projection", "type": "projection", "required": true }, { "name": "pointRadius", "type": "number" }, { "name": "field", "type": "field" }, { "name": "as", "type": "string", "default": "path" } ] } var GeoPointDefinition = { "type": "GeoPoint", "metadata": {"modifies": true}, "params": [ { "name": "projection", "type": "projection", "required": true }, { "name": "fields", "type": "field", "array": true, "required": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["x", "y"] } ] } var GeoShapeDefinition = { "type": "GeoShape", "metadata": {"modifies": true}, "params": [ { "name": "projection", "type": "projection", "required": true }, { "name": "pointRadius", "type": "number" }, { "name": "field", "type": "field", "default": "datum" }, { "name": "as", "type": "string", "default": "shape" } ] } var GraticuleDefinition = { "type": "Graticule", "metadata": {"source": true, "generates": true, "changes": true}, "params": [ { "name": "extent", "type": "array", "array": true, "length": 2, "content": {"type": "number", "array": true, "length": 2} }, { "name": "extentMajor", "type": "array", "array": true, "length": 2, "content": {"type": "number", "array": true, "length": 2} }, { "name": "extentMinor", "type": "array", "array": true, "length": 2, "content": {"type": "number", "array": true, "length": 2} }, { "name": "step", "type": "number", "array": true, "length": 2 }, { "name": "stepMajor", "type": "number", "array": true, "length": 2, "default": [90, 360] }, { "name": "stepMinor", "type": "number", "array": true, "length": 2, "default": [10, 10] }, { "name": "precision", "type": "number", "default": 2.5 } ] }; register(GeoPathDefinition, GeoPath); register(GeoPointDefinition, GeoPoint); register(GeoShapeDefinition, GeoShape); register(GraticuleDefinition, Graticule); transform('Projection', Projection); /** * Generate tick values for the given scale and approximate tick count or * interval value. If the scale has a 'ticks' method, it will be used to * generate the ticks, with the count argument passed as a parameter. If the * scale lacks a 'ticks' method, the full scale domain will be returned. * @param {Scale} scale - The scale for which to generate tick values. * @param {*} [count] - The approximate number of desired ticks. * @return {Array<*>} - The generated tick values. */ function tickValues(scale, count) { return scale.ticks ? scale.ticks(count) : scale.domain(); } /** * Generate a label format function for a scale. If the scale has a * 'tickFormat' method, it will be used to generate the formatter, with the * count and specifier arguments passed as parameters. If the scale lacks a * 'tickFormat' method, the returned formatter performs simple string coercion. * If the input scale is a logarithmic scale and the format specifier does not * indicate a desired decimal precision, a special variable precision formatter * that automatically trims trailing zeroes will be generated. * @param {Scale} scale - The scale for which to generate the label formatter. * @param {*} [count] - The approximate number of desired ticks. * @param {string} [specifier] - The format specifier. Must be a legal d3 4.0 * specifier string (see https://github.com/d3/d3-format#formatSpecifier). * @return {function(*):string} - The generated label formatter. */ function tickFormat$1(scale, count, specifier) { var format = scale.tickFormat ? scale.tickFormat(count, specifier) : String; return (scale.type === 'log') ? filter$1(format, variablePrecision(specifier)) : format; } function filter$1(sourceFormat, targetFormat) { return function(_) { return sourceFormat(_) ? targetFormat(_) : ''; }; } function variablePrecision(specifier) { var s = formatSpecifier(specifier || ','); if (s.precision == null) { s.precision = 12; switch (s.type) { case '%': s.precision -= 2; break; case 'e': s.precision -= 1; break; } return trimZeroes( format(s), // number format format('.1f')(1)[1] // decimal point character ); } else { return format(s); } } function trimZeroes(format, decimalChar) { return function(x) { var str = format(x), dec = str.indexOf(decimalChar), idx, end; if (dec < 0) return str; idx = rightmostDigit(str, dec); end = idx < str.length ? str.slice(idx) : ''; while (--idx > dec) if (str[idx] !== '0') { ++idx; break; } return str.slice(0, idx) + end; }; } function rightmostDigit(str, dec) { var i = str.lastIndexOf('e'), c; if (i > 0) return i; for (i=str.length; --i > dec;) { c = str.charCodeAt(i); if (c >= 48 && c <= 57) return i + 1; // is digit } } /** * Generates axis ticks for visualizing a spatial scale. * @constructor * @param {object} params - The parameters for this operator. * @param {Scale} params.scale - The scale to generate ticks for. * @param {*} [params.count=10] - The approximate number of ticks, or * desired tick interval, to use. * @param {Array<*>} [params.values] - The exact tick values to use. * These must be legal domain values for the provided scale. * If provided, the count argument is ignored. * @param {function(*):string} [params.formatSpecifier] - A format specifier * to use in conjunction with scale.tickFormat. Legal values are * any valid d3 4.0 format specifier. * @param {function(*):string} [params.format] - The format function to use. * If provided, the formatSpecifier argument is ignored. */ function AxisTicks(params) { Transform.call(this, [], params); } var prototype$47 = inherits(AxisTicks, Transform); prototype$47.transform = function(_, pulse) { if (this.value != null && !_.modified()) { return pulse.StopPropagation; } var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), ticks = this.value, scale = _.scale, count = _.count == null ? 10 : _.count, format = _.format || tickFormat$1(scale, count, _.formatSpecifier), values = _.values || tickValues(scale, count); if (ticks) out.rem = ticks; ticks = values.map(function(value) { return ingest({value: value, label: format(value)}) }); if (_.extra) { // add an extra tick pegged to the initial domain value // this is used to generate axes with 'binned' domains ticks.push(ingest({ extra: {value: ticks[0].value}, label: '' })); } return (out.source = out.add = this.value = ticks), out; }; function get$2(map, key) { return map.hasOwnProperty(key) ? map[key] : null; } /** * Joins a set of data elements against a set of visual items. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): object} [params.item] - An item generator function. * @param {function(object): *} [params.key] - The key field associating data and visual items. */ function DataJoin(params) { Transform.call(this, null, params); } var prototype$48 = inherits(DataJoin, Transform); function defaultItemCreate() { return ingest({}); } prototype$48.transform = function(_, pulse) { var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), item = _.item || defaultItemCreate, key = _.key || tupleid, map = this.value || (pulse = pulse.addAll(), this.value = {}); if (_.modified('key') || pulse.modified(key)) { error('DataJoin does not support modified key function or fields.'); } pulse.visit(pulse.ADD, function(t) { var k = key(t), x = get$2(map, k); if (x) { (x.exit ? out.add : out.mod).push(x); } else { map[k] = (x = item(t)); out.add.push(x); } x.datum = t; x.exit = false; }); pulse.visit(pulse.MOD, function(t) { var k = key(t), x = get$2(map, k); if (x) { out.mod.push(x); } }); pulse.visit(pulse.REM, function(t) { var k = key(t), x = get$2(map, k); if (t === x.datum) { out.rem.push(x); x.exit = true; } }); return out; }; /** * Invokes encoding functions for visual items. * @constructor * @param {object} params - The parameters to the encoding functions. This * parameter object will be passed through to all invoked encoding functions. * @param {object} param.encoders - The encoding functions * @param {function(object, object): boolean} [param.encoders.update] - Update encoding set * @param {function(object, object): boolean} [param.encoders.enter] - Enter encoding set * @param {function(object, object): boolean} [param.encoders.exit] - Exit encoding set */ function Encode(params) { Transform.call(this, null, params); } var prototype$49 = inherits(Encode, Transform); prototype$49.transform = function(_, pulse) { var out = pulse.fork(pulse.ADD_REM), encode = pulse.encode, reenter = encode === 'enter', update = _.encoders.update || falsy, enter = _.encoders.enter || falsy, exit = _.encoders.exit || falsy, set = (encode && !reenter ? _.encoders[encode] : update) || falsy; if (pulse.changed(pulse.ADD)) { pulse.visit(pulse.ADD, function(t) { enter(t, _); update(t, _); if (set !== falsy && set !== update) set(t, _); }); out.modifies(enter.output); out.modifies(update.output); if (set !== falsy && set !== update) out.modifies(set.output); } if (pulse.changed(pulse.REM) && exit !== falsy) { pulse.visit(pulse.REM, function(t) { exit(t, _); }); out.modifies(exit.output); } if (reenter || set !== falsy) { var flag = pulse.MOD | (_.modified() ? pulse.REFLOW : 0); if (reenter) { pulse.visit(flag, function(t) { var mod = enter(t, _); if (set(t, _) || mod) out.mod.push(t); }); if (out.mod.length) out.modifies(enter.output); } else { pulse.visit(flag, function(t) { if (set(t, _)) out.mod.push(t); }); } if (out.mod.length) out.modifies(set.output); } return out; }; /** * Generates legend entries for visualizing a scale. * @constructor * @param {object} params - The parameters for this operator. * @param {Scale} params.scale - The scale to generate items for. * @param {*} [params.count=10] - The approximate number of items, or * desired tick interval, to use. * @param {Array<*>} [params.values] - The exact tick values to use. * These must be legal domain values for the provided scale. * If provided, the count argument is ignored. * @param {function(*):string} [params.formatSpecifier] - A format specifier * to use in conjunction with scale.tickFormat. Legal values are * any valid d3 4.0 format specifier. * @param {function(*):string} [params.format] - The format function to use. * If provided, the formatSpecifier argument is ignored. */ function LegendEntries(params) { Transform.call(this, [], params); } var prototype$50 = inherits(LegendEntries, Transform); prototype$50.transform = function(_, pulse) { if (this.value != null && !_.modified()) { return pulse.StopPropagation; } var out = pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS), total = 0, items = this.value, grad = _.type === 'gradient', scale = _.scale, count = _.count == null ? 5 : _.count, format = _.format || tickFormat$1(scale, count, _.formatSpecifier), values = _.values || (grad ? scale.domain() : tickValues(scale, count)); if (items) out.rem = items; if (grad) { var domain = _.values ? scale.domain() : values, min = domain[0], max = domain[domain.length - 1], fraction = scale.range ? scale.copy().domain([min, max]).range([0, 1]) : function(_) { return (_ - min) / (max - min); }; } else { var size = _.size, offset; if (isFunction(size)) { offset = values.reduce(function(max, value) { return Math.max(max, size(value, _)); }, 0); } else { size = constant$1(offset = size || 8); } } items = values.map(function(value, index) { var t = ingest({index: index, label: format(value), value: value}); if (grad) { t.perc = fraction(value); } else { t.offset = offset; t.size = size(value, _); t.total = Math.round(total); total += t.size; } return t; }); return (out.source = out.add = this.value = items), out; }; var Paths = { 'line': line$3, 'line-radial': lineR, 'curve': curve, 'curve-radial': curveR, 'orthogonal-horizontal': orthoX, 'orthogonal-vertical': orthoY, 'orthogonal-radial': orthoR, 'diagonal-horizontal': diagonalX, 'diagonal-vertical': diagonalY, 'diagonal-radial': diagonalR }; function sourceX(t) { return t.source.x; } function sourceY(t) { return t.source.y; } function targetX(t) { return t.target.x; } function targetY(t) { return t.target.y; } /** * Layout paths linking source and target elements. * @constructor * @param {object} params - The parameters for this operator. */ function LinkPath(params) { Transform.call(this, {}, params); } var prototype$51 = inherits(LinkPath, Transform); prototype$51.transform = function(_, pulse) { var sx = _.sourceX || sourceX, sy = _.sourceY || sourceY, tx = _.targetX || targetX, ty = _.targetY || targetY, as = _.as || 'path', orient = _.orient || 'vertical', shape = _.shape || 'line', path = get$2(Paths, shape + '-' + orient) || get$2(Paths, shape); if (!path) { error('LinkPath unsupported type: ' + _.shape + '-' + _.orient); } pulse.visit(pulse.SOURCE, function(t) { t[as] = path(sx(t), sy(t), tx(t), ty(t)); }); return pulse.reflow(_.modified()).modifies(as); }; // -- Link Path Generation Methods ----- function line$3(sx, sy, tx, ty) { return 'M' + sx + ',' + sy + 'L' + tx + ',' + ty; } function lineR(sa, sr, ta, tr) { return line$3( sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta) ); } function curve(sx, sy, tx, ty) { var dx = tx - sx, dy = ty - sy, ix = 0.2 * (dx + dy), iy = 0.2 * (dy - dx); return 'M' + sx + ',' + sy + 'C' + (sx+ix) + ',' + (sy+iy) + ' ' + (tx+iy) + ',' + (ty-ix) + ' ' + tx + ',' + ty; } function curveR(sa, sr, ta, tr) { return curve( sr * Math.cos(sa), sr * Math.sin(sa), tr * Math.cos(ta), tr * Math.sin(ta) ); } function orthoX(sx, sy, tx, ty) { return 'M' + sx + ',' + sy + 'V' + ty + 'H' + tx; } function orthoY(sx, sy, tx, ty) { return 'M' + sx + ',' + sy + 'H' + tx + 'V' + ty; } function orthoR(sa, sr, ta, tr) { var sc = Math.cos(sa), ss = Math.sin(sa), tc = Math.cos(ta), ts = Math.sin(ta), sf = Math.abs(ta - sa) > Math.PI ? ta <= sa : ta > sa; return 'M' + (sr*sc) + ',' + (sr*ss) + 'A' + sr + ',' + sr + ' 0 0,' + (sf?1:0) + ' ' + (sr*tc) + ',' + (sr*ts) + 'L' + (tr*tc) + ',' + (tr*ts); } function diagonalX(sx, sy, tx, ty) { var m = (sx + tx) / 2; return 'M' + sx + ',' + sy + 'C' + m + ',' + sy + ' ' + m + ',' + ty + ' ' + tx + ',' + ty; } function diagonalY(sx, sy, tx, ty) { var m = (sy + ty) / 2; return 'M' + sx + ',' + sy + 'C' + sx + ',' + m + ' ' + tx + ',' + m + ' ' + tx + ',' + ty; } function diagonalR(sa, sr, ta, tr) { var sc = Math.cos(sa), ss = Math.sin(sa), tc = Math.cos(ta), ts = Math.sin(ta), mr = (sr + tr) / 2; return 'M' + (sr*sc) + ',' + (sr*ss) + 'C' + (mr*sc) + ',' + (mr*ss) + ' ' + (mr*tc) + ',' + (mr*ts) + ' ' + (tr*tc) + ',' + (tr*ts); } /** * Pie and donut chart layout. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to size pie segments. * @param {number} [params.startAngle=0] - The start angle (in radians) of the layout. * @param {number} [params.endAngle=2π] - The end angle (in radians) of the layout. * @param {boolean} [params.sort] - Boolean flag for sorting sectors by value. */ function Pie(params) { Transform.call(this, null, params); } var prototype$52 = inherits(Pie, Transform); prototype$52.transform = function(_, pulse) { var as = _.as || ['startAngle', 'endAngle'], startAngle = as[0], endAngle = as[1], field = _.field || one, start = _.startAngle || 0, stop = _.endAngle != null ? _.endAngle : 2 * Math.PI, data = pulse.source, values = data.map(field), n = values.length, a = start, k = (stop - start) / sum(values), index = range(n), i, t, v; if (_.sort) { index.sort(function(a, b) { return values[a] - values[b]; }); } for (i=0; i<n; ++i) { v = values[index[i]]; t = data[index[i]]; t[startAngle] = a; t[endAngle] = (a += v * k); } this.value = values; return pulse.reflow(_.modified()).modifies(as); }; var SKIP$2 = { 'set': 1, 'modified': 1, 'clear': 1, 'type': 1, 'scheme': 1, 'domain': 1, 'domainMin': 1, 'domainMax': 1, 'nice': 1, 'zero': 1, 'range': 1, 'rangeStep': 1, 'round': 1, 'reverse': 1 }; var INCLUDE_ZERO = toSet(['linear', 'pow', 'sqrt']); /** * Maintains a scale function mapping data values to visual channels. * @constructor * @param {object} params - The parameters for this operator. */ function Scale(params) { Transform.call(this, null, params); this.modified(true); // always treat as modified } var prototype$53 = inherits(Scale, Transform); prototype$53.transform = function(_, pulse) { var scale = this.value, prop, create = !scale || _.modified('type') || _.modified('scheme') || _.scheme && _.modified('reverse'); if (create) { this.value = (scale = createScale(_.type, _.scheme, _.reverse)); } for (prop in _) if (!SKIP$2[prop]) { isFunction(scale[prop]) ? scale[prop](_[prop]) : pulse.dataflow.warn('Unsupported scale property: ' + prop); } configureRange(scale, _, configureDomain(scale, _)); return pulse.fork(pulse.NO_SOURCE | pulse.NO_FIELDS); }; function createScale(type, scheme, reverse) { var scale = scale$1((type || 'linear').toLowerCase()); return scale(scheme && scheme.toLowerCase(), reverse); } function configureDomain(scale, _) { var domain = _.domain, zero = _.zero || (_.zero === undefined && INCLUDE_ZERO[scale.type]), n; if (!domain) return 0; if (zero || _.domainMin != null || _.domainMax != null) { n = (domain = domain.slice()).length - 1; if (zero) { if (domain[0] > 0) domain[0] = 0; if (domain[n] < 0) domain[n] = 0; } if (_.domainMin != null) domain[0] = _.domainMin; if (_.domainMax != null) domain[n] = _.domainMax; } scale.domain(domain); if (_.nice && scale.nice) scale.nice((_.nice !== true && +_.nice) || null); return domain.length; } function configureRange(scale, _, count) { var type = scale.type, range = _.range; if (_.rangeStep != null) { if (type !== 'band' && type !== 'point') { error('Only band and point scales support rangeStep.'); } // calculate full range based on requested step size and padding // Mirrors https://github.com/d3/d3-scale/blob/master/src/band.js#L23 var inner = (_.paddingInner != null ? _.paddingInner : _.padding) || 0, outer = (_.paddingOuter != null ? _.paddingOuter : _.padding) || 0; range = [0, _.rangeStep * (count - (count > 1 ? inner : 0) + outer * 2)]; } if (range) { if (_.reverse) range = range.slice().reverse(); scale[_.round ? 'rangeRound' : 'range'](range); } } var Center = 'center'; var Normalize = 'normalize'; /** * Stack layout for visualization elements. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to stack. * @param {Array<function(object): *>} [params.groupby] - An array of accessors to groupby. * @param {function(object,object): number} [params.sort] - A comparator for stack sorting. * @param {string} [offset='zero'] - One of 'zero', 'center', 'normalize'. */ function Stack(params) { Transform.call(this, null, params); } var prototype$54 = inherits(Stack, Transform); prototype$54.transform = function(_, pulse) { var as = _.as || ['y0', 'y1'], y0 = as[0], y1 = as[1], field = _.field, offset = _.offset, groups, group, i, j, n, m, max, off, scale, t, a, b, v; // partition, sum, and sort the stack groups groups = partition$1(pulse.source, _.groupby, _.sort, field); // compute stack layouts per group for (i=0, n=groups.length, max=groups.max; i<n; ++i) { group = groups[i]; off = offset===Center ? (max - group.sum)/2 : 0; scale = offset===Normalize ? (1/group.sum) : 1; // set stack coordinates for each datum in group for (b=off, v=0, j=0, m=group.length; j<m; ++j) { t = group[j]; a = b; // use previous value for start point v += field(t); b = scale * v + off; // compute end point t[y0] = a; t[y1] = b; } } return pulse.reflow(_.modified()).modifies(as); }; function partition$1(data, groupby, sort, field) { var groups = [], get = function(f) { return f(t); }, map, i, n, m, t, k, g, s, max; // partition data points into stack groups if (groupby == null) { groups.push(data.slice()); } else { for (map={}, i=0, n=data.length; i<n; ++i) { t = data[i]; k = groupby.map(get); g = map[k] || (groups.push(map[k] = []), map[k]); g.push(t); } } // compute sums of groups, sort groups as needed for (k=0, max=0, m=groups.length; k<m; ++k) { g = groups[k]; for (i=0, s=0, n=g.length; i<n; ++i) { s += field(g[i]); } g.sum = s; if (s > max) max = s; if (sort) g.sort(sort); } groups.max = max; return groups; } var LinkPathDefinition = { "type": "LinkPath", "metadata": {"modifies": true}, "params": [ { "name": "sourceX", "type": "field", "default": "source.x" }, { "name": "sourceY", "type": "field", "default": "source.y" }, { "name": "targetX", "type": "field", "default": "target.x" }, { "name": "targetY", "type": "field", "default": "target.y" }, { "name": "orient", "type": "enum", "default": "vertical", "values": ["horizontal", "vertical", "radial"] }, { "name": "shape", "type": "enum", "default": "line", "values": ["line", "curve", "diagonal", "orthogonal"] }, { "name": "as", "type": "string", "default": "path" } ] }; var PieDefinition = { "type": "Pie", "metadata": {"modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "startAngle", "type": "number", "default": 0 }, { "name": "endAngle", "type": "number", "default": 6.283185307179586 }, { "name": "sort", "type": "boolean", "default": false }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["startAngle", "endAngle"] } ] }; var StackDefinition = { "type": "Stack", "metadata": {"modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "groupby", "type": "field", "array": true }, { "name": "sort", "type": "compare" }, { "name": "offset", "type": "enum", "default": "zero", "values": ["zero", "center", "normalize"] }, { "name": "as", "type": "string", "array": true, "length": 2, "default": ["y0", "y1"] } ] }; register(LinkPathDefinition, LinkPath); register(PieDefinition, Pie); register(StackDefinition, Stack); transform('AxisTicks', AxisTicks); transform('DataJoin', DataJoin); transform('Encode', Encode); transform('LegendEntries', LegendEntries); transform('Scale', Scale); function forceCenter(x, y) { var nodes; if (x == null) x = 0; if (y == null) y = 0; function force() { var i, n = nodes.length, node, sx = 0, sy = 0; for (i = 0; i < n; ++i) { node = nodes[i], sx += node.x, sy += node.y; } for (sx = sx / n - x, sy = sy / n - y, i = 0; i < n; ++i) { node = nodes[i], node.x -= sx, node.y -= sy; } } force.initialize = function(_) { nodes = _; }; force.x = function(_) { return arguments.length ? (x = +_, force) : x; }; force.y = function(_) { return arguments.length ? (y = +_, force) : y; }; return force; } function constant$7(x) { return function() { return x; }; } function jiggle() { return (Math.random() - 0.5) * 1e-6; } function tree_add(d) { var x = +this._x.call(null, d), y = +this._y.call(null, d); return add$3(this.cover(x, y), x, y, d); } function add$3(tree, x, y, d) { if (isNaN(x) || isNaN(y)) return tree; // ignore invalid points var parent, node = tree._root, leaf = {data: d}, x0 = tree._x0, y0 = tree._y0, x1 = tree._x1, y1 = tree._y1, xm, ym, xp, yp, right, bottom, i, j; // If the tree is empty, initialize the root as a leaf. if (!node) return tree._root = leaf, tree; // Find the existing leaf for the new point, or add it. while (node.length) { if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm; if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym; if (parent = node, !(node = node[i = bottom << 1 | right])) return parent[i] = leaf, tree; } // Is the new point is exactly coincident with the existing point? xp = +tree._x.call(null, node.data); yp = +tree._y.call(null, node.data); if (x === xp && y === yp) return leaf.next = node, parent ? parent[i] = leaf : tree._root = leaf, tree; // Otherwise, split the leaf node until the old and new point are separated. do { parent = parent ? parent[i] = new Array(4) : tree._root = new Array(4); if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm; if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym; } while ((i = bottom << 1 | right) === (j = (yp >= ym) << 1 | (xp >= xm))); return parent[j] = node, parent[i] = leaf, tree; } function addAll(data) { var d, i, n = data.length, x, y, xz = new Array(n), yz = new Array(n), x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity; // Compute the points and their extent. for (i = 0; i < n; ++i) { if (isNaN(x = +this._x.call(null, d = data[i])) || isNaN(y = +this._y.call(null, d))) continue; xz[i] = x; yz[i] = y; if (x < x0) x0 = x; if (x > x1) x1 = x; if (y < y0) y0 = y; if (y > y1) y1 = y; } // If there were no (valid) points, inherit the existing extent. if (x1 < x0) x0 = this._x0, x1 = this._x1; if (y1 < y0) y0 = this._y0, y1 = this._y1; // Expand the tree to cover the new points. this.cover(x0, y0).cover(x1, y1); // Add the new points. for (i = 0; i < n; ++i) { add$3(this, xz[i], yz[i], data[i]); } return this; } function tree_cover(x, y) { if (isNaN(x = +x) || isNaN(y = +y)) return this; // ignore invalid points var x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1; // If the quadtree has no extent, initialize them. // Integer extent are necessary so that if we later double the extent, // the existing quadrant boundaries don’t change due to floating point error! if (isNaN(x0)) { x1 = (x0 = Math.floor(x)) + 1; y1 = (y0 = Math.floor(y)) + 1; } // Otherwise, double repeatedly to cover. else if (x0 > x || x > x1 || y0 > y || y > y1) { var z = x1 - x0, node = this._root, parent, i; switch (i = (y < (y0 + y1) / 2) << 1 | (x < (x0 + x1) / 2)) { case 0: { do parent = new Array(4), parent[i] = node, node = parent; while (z *= 2, x1 = x0 + z, y1 = y0 + z, x > x1 || y > y1); break; } case 1: { do parent = new Array(4), parent[i] = node, node = parent; while (z *= 2, x0 = x1 - z, y1 = y0 + z, x0 > x || y > y1); break; } case 2: { do parent = new Array(4), parent[i] = node, node = parent; while (z *= 2, x1 = x0 + z, y0 = y1 - z, x > x1 || y0 > y); break; } case 3: { do parent = new Array(4), parent[i] = node, node = parent; while (z *= 2, x0 = x1 - z, y0 = y1 - z, x0 > x || y0 > y); break; } } if (this._root && this._root.length) this._root = node; } // If the quadtree covers the point already, just return. else return this; this._x0 = x0; this._y0 = y0; this._x1 = x1; this._y1 = y1; return this; } function tree_data() { var data = []; this.visit(function(node) { if (!node.length) do data.push(node.data); while (node = node.next) }); return data; } function tree_extent(_) { return arguments.length ? this.cover(+_[0][0], +_[0][1]).cover(+_[1][0], +_[1][1]) : isNaN(this._x0) ? undefined : [[this._x0, this._y0], [this._x1, this._y1]]; } function Quad(node, x0, y0, x1, y1) { this.node = node; this.x0 = x0; this.y0 = y0; this.x1 = x1; this.y1 = y1; } function tree_find(x, y, radius) { var data, x0 = this._x0, y0 = this._y0, x1, y1, x2, y2, x3 = this._x1, y3 = this._y1, quads = [], node = this._root, q, i; if (node) quads.push(new Quad(node, x0, y0, x3, y3)); if (radius == null) radius = Infinity; else { x0 = x - radius, y0 = y - radius; x3 = x + radius, y3 = y + radius; radius *= radius; } while (q = quads.pop()) { // Stop searching if this quadrant can’t contain a closer node. if (!(node = q.node) || (x1 = q.x0) > x3 || (y1 = q.y0) > y3 || (x2 = q.x1) < x0 || (y2 = q.y1) < y0) continue; // Bisect the current quadrant. if (node.length) { var xm = (x1 + x2) / 2, ym = (y1 + y2) / 2; quads.push( new Quad(node[3], xm, ym, x2, y2), new Quad(node[2], x1, ym, xm, y2), new Quad(node[1], xm, y1, x2, ym), new Quad(node[0], x1, y1, xm, ym) ); // Visit the closest quadrant first. if (i = (y >= ym) << 1 | (x >= xm)) { q = quads[quads.length - 1]; quads[quads.length - 1] = quads[quads.length - 1 - i]; quads[quads.length - 1 - i] = q; } } // Visit this point. (Visiting coincident points isn’t necessary!) else { var dx = x - +this._x.call(null, node.data), dy = y - +this._y.call(null, node.data), d2 = dx * dx + dy * dy; if (d2 < radius) { var d = Math.sqrt(radius = d2); x0 = x - d, y0 = y - d; x3 = x + d, y3 = y + d; data = node.data; } } } return data; } function tree_remove(d) { if (isNaN(x = +this._x.call(null, d)) || isNaN(y = +this._y.call(null, d))) return this; // ignore invalid points var parent, node = this._root, retainer, previous, next, x0 = this._x0, y0 = this._y0, x1 = this._x1, y1 = this._y1, x, y, xm, ym, right, bottom, i, j; // If the tree is empty, initialize the root as a leaf. if (!node) return this; // Find the leaf node for the point. // While descending, also retain the deepest parent with a non-removed sibling. if (node.length) while (true) { if (right = x >= (xm = (x0 + x1) / 2)) x0 = xm; else x1 = xm; if (bottom = y >= (ym = (y0 + y1) / 2)) y0 = ym; else y1 = ym; if (!(parent = node, node = node[i = bottom << 1 | right])) return this; if (!node.length) break; if (parent[(i + 1) & 3] || parent[(i + 2) & 3] || parent[(i + 3) & 3]) retainer = parent, j = i; } // Find the point to remove. while (node.data !== d) if (!(previous = node, node = node.next)) return this; if (next = node.next) delete node.next; // If there are multiple coincident points, remove just the point. if (previous) return (next ? previous.next = next : delete previous.next), this; // If this is the root point, remove it. if (!parent) return this._root = next, this; // Remove this leaf. next ? parent[i] = next : delete parent[i]; // If the parent now contains exactly one leaf, collapse superfluous parents. if ((node = parent[0] || parent[1] || parent[2] || parent[3]) && node === (parent[3] || parent[2] || parent[1] || parent[0]) && !node.length) { if (retainer) retainer[j] = node; else this._root = node; } return this; } function removeAll(data) { for (var i = 0, n = data.length; i < n; ++i) this.remove(data[i]); return this; } function tree_root() { return this._root; } function tree_size() { var size = 0; this.visit(function(node) { if (!node.length) do ++size; while (node = node.next) }); return size; } function tree_visit(callback) { var quads = [], q, node = this._root, child, x0, y0, x1, y1; if (node) quads.push(new Quad(node, this._x0, this._y0, this._x1, this._y1)); while (q = quads.pop()) { if (!callback(node = q.node, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1) && node.length) { var xm = (x0 + x1) / 2, ym = (y0 + y1) / 2; if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1)); if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1)); if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym)); if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym)); } } return this; } function tree_visitAfter(callback) { var quads = [], next = [], q; if (this._root) quads.push(new Quad(this._root, this._x0, this._y0, this._x1, this._y1)); while (q = quads.pop()) { var node = q.node; if (node.length) { var child, x0 = q.x0, y0 = q.y0, x1 = q.x1, y1 = q.y1, xm = (x0 + x1) / 2, ym = (y0 + y1) / 2; if (child = node[0]) quads.push(new Quad(child, x0, y0, xm, ym)); if (child = node[1]) quads.push(new Quad(child, xm, y0, x1, ym)); if (child = node[2]) quads.push(new Quad(child, x0, ym, xm, y1)); if (child = node[3]) quads.push(new Quad(child, xm, ym, x1, y1)); } next.push(q); } while (q = next.pop()) { callback(q.node, q.x0, q.y0, q.x1, q.y1); } return this; } function defaultX(d) { return d[0]; } function tree_x(_) { return arguments.length ? (this._x = _, this) : this._x; } function defaultY(d) { return d[1]; } function tree_y(_) { return arguments.length ? (this._y = _, this) : this._y; } function quadtree(nodes, x, y) { var tree = new Quadtree(x == null ? defaultX : x, y == null ? defaultY : y, NaN, NaN, NaN, NaN); return nodes == null ? tree : tree.addAll(nodes); } function Quadtree(x, y, x0, y0, x1, y1) { this._x = x; this._y = y; this._x0 = x0; this._y0 = y0; this._x1 = x1; this._y1 = y1; this._root = undefined; } function leaf_copy(leaf) { var copy = {data: leaf.data}, next = copy; while (leaf = leaf.next) next = next.next = {data: leaf.data}; return copy; } var treeProto = quadtree.prototype = Quadtree.prototype; treeProto.copy = function() { var copy = new Quadtree(this._x, this._y, this._x0, this._y0, this._x1, this._y1), node = this._root, nodes, child; if (!node) return copy; if (!node.length) return copy._root = leaf_copy(node), copy; nodes = [{source: node, target: copy._root = new Array(4)}]; while (node = nodes.pop()) { for (var i = 0; i < 4; ++i) { if (child = node.source[i]) { if (child.length) nodes.push({source: child, target: node.target[i] = new Array(4)}); else node.target[i] = leaf_copy(child); } } } return copy; }; treeProto.add = tree_add; treeProto.addAll = addAll; treeProto.cover = tree_cover; treeProto.data = tree_data; treeProto.extent = tree_extent; treeProto.find = tree_find; treeProto.remove = tree_remove; treeProto.removeAll = removeAll; treeProto.root = tree_root; treeProto.size = tree_size; treeProto.visit = tree_visit; treeProto.visitAfter = tree_visitAfter; treeProto.x = tree_x; treeProto.y = tree_y; function x$2(d) { return d.x + d.vx; } function y$2(d) { return d.y + d.vy; } function forceCollide(radius) { var nodes, radii, strength = 1, iterations = 1; if (typeof radius !== "function") radius = constant$7(radius == null ? 1 : +radius); function force() { var i, n = nodes.length, tree, node, xi, yi, ri, ri2; for (var k = 0; k < iterations; ++k) { tree = quadtree(nodes, x$2, y$2).visitAfter(prepare); for (i = 0; i < n; ++i) { node = nodes[i]; ri = radii[i], ri2 = ri * ri; xi = node.x + node.vx; yi = node.y + node.vy; tree.visit(apply); } } function apply(quad, x0, y0, x1, y1) { var data = quad.data, rj = quad.r, r = ri + rj; if (data) { if (data.index > i) { var x = xi - data.x - data.vx, y = yi - data.y - data.vy, l = x * x + y * y; if (l < r * r) { if (x === 0) x = jiggle(), l += x * x; if (y === 0) y = jiggle(), l += y * y; l = (r - (l = Math.sqrt(l))) / l * strength; node.vx += (x *= l) * (r = (rj *= rj) / (ri2 + rj)); node.vy += (y *= l) * r; data.vx -= x * (r = 1 - r); data.vy -= y * r; } } return; } return x0 > xi + r || x1 < xi - r || y0 > yi + r || y1 < yi - r; } } function prepare(quad) { if (quad.data) return quad.r = radii[quad.data.index]; for (var i = quad.r = 0; i < 4; ++i) { if (quad[i] && quad[i].r > quad.r) { quad.r = quad[i].r; } } } force.initialize = function(_) { var i, n = (nodes = _).length; radii = new Array(n); for (i = 0; i < n; ++i) radii[i] = +radius(nodes[i], i, nodes); }; force.iterations = function(_) { return arguments.length ? (iterations = +_, force) : iterations; }; force.strength = function(_) { return arguments.length ? (strength = +_, force) : strength; }; force.radius = function(_) { return arguments.length ? (radius = typeof _ === "function" ? _ : constant$7(+_), force) : radius; }; return force; } function index$1(d, i) { return i; } function forceLink(links) { var id = index$1, strength = defaultStrength, strengths, distance = constant$7(30), distances, nodes, count, bias, iterations = 1; if (links == null) links = []; function defaultStrength(link) { return 1 / Math.min(count[link.source.index], count[link.target.index]); } function force(alpha) { for (var k = 0, n = links.length; k < iterations; ++k) { for (var i = 0, link, source, target, x, y, l, b; i < n; ++i) { link = links[i], source = link.source, target = link.target; x = target.x + target.vx - source.x - source.vx || jiggle(); y = target.y + target.vy - source.y - source.vy || jiggle(); l = Math.sqrt(x * x + y * y); l = (l - distances[i]) / l * alpha * strengths[i]; x *= l, y *= l; target.vx -= x * (b = bias[i]); target.vy -= y * b; source.vx += x * (b = 1 - b); source.vy += y * b; } } } function initialize() { if (!nodes) return; var i, n = nodes.length, m = links.length, nodeById = map$1(nodes, id), link; for (i = 0, count = new Array(n); i < n; ++i) { count[i] = 0; } for (i = 0; i < m; ++i) { link = links[i], link.index = i; if (typeof link.source !== "object") link.source = nodeById.get(link.source); if (typeof link.target !== "object") link.target = nodeById.get(link.target); ++count[link.source.index], ++count[link.target.index]; } for (i = 0, bias = new Array(m); i < m; ++i) { link = links[i], bias[i] = count[link.source.index] / (count[link.source.index] + count[link.target.index]); } strengths = new Array(m), initializeStrength(); distances = new Array(m), initializeDistance(); } function initializeStrength() { if (!nodes) return; for (var i = 0, n = links.length; i < n; ++i) { strengths[i] = +strength(links[i], i, links); } } function initializeDistance() { if (!nodes) return; for (var i = 0, n = links.length; i < n; ++i) { distances[i] = +distance(links[i], i, links); } } force.initialize = function(_) { nodes = _; initialize(); }; force.links = function(_) { return arguments.length ? (links = _, initialize(), force) : links; }; force.id = function(_) { return arguments.length ? (id = _, force) : id; }; force.iterations = function(_) { return arguments.length ? (iterations = +_, force) : iterations; }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant$7(+_), initializeStrength(), force) : strength; }; force.distance = function(_) { return arguments.length ? (distance = typeof _ === "function" ? _ : constant$7(+_), initializeDistance(), force) : distance; }; return force; } var frame = 0; var timeout = 0; var interval = 0; var pokeDelay = 1000; var taskHead; var taskTail; var clockLast = 0; var clockNow = 0; var clockSkew = 0; var clock = typeof performance === "object" && performance.now ? performance : Date; var setFrame = typeof requestAnimationFrame === "function" ? requestAnimationFrame : function(f) { setTimeout(f, 17); }; function now() { return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew); } function clearNow() { clockNow = 0; } function Timer() { this._call = this._time = this._next = null; } Timer.prototype = timer.prototype = { constructor: Timer, restart: function(callback, delay, time) { if (typeof callback !== "function") throw new TypeError("callback is not a function"); time = (time == null ? now() : +time) + (delay == null ? 0 : +delay); if (!this._next && taskTail !== this) { if (taskTail) taskTail._next = this; else taskHead = this; taskTail = this; } this._call = callback; this._time = time; sleep(); }, stop: function() { if (this._call) { this._call = null; this._time = Infinity; sleep(); } } }; function timer(callback, delay, time) { var t = new Timer; t.restart(callback, delay, time); return t; } function timerFlush() { now(); // Get the current time, if not already set. ++frame; // Pretend we’ve set an alarm, if we haven’t already. var t = taskHead, e; while (t) { if ((e = clockNow - t._time) >= 0) t._call.call(null, e); t = t._next; } --frame; } function wake() { clockNow = (clockLast = clock.now()) + clockSkew; frame = timeout = 0; try { timerFlush(); } finally { frame = 0; nap(); clockNow = 0; } } function poke() { var now = clock.now(), delay = now - clockLast; if (delay > pokeDelay) clockSkew -= delay, clockLast = now; } function nap() { var t0, t1 = taskHead, t2, time = Infinity; while (t1) { if (t1._call) { if (time > t1._time) time = t1._time; t0 = t1, t1 = t1._next; } else { t2 = t1._next, t1._next = null; t1 = t0 ? t0._next = t2 : taskHead = t2; } } taskTail = t0; sleep(time); } function sleep(time) { if (frame) return; // Soonest alarm already set, or will be. if (timeout) timeout = clearTimeout(timeout); var delay = time - clockNow; if (delay > 24) { if (time < Infinity) timeout = setTimeout(wake, delay); if (interval) interval = clearInterval(interval); } else { if (!interval) interval = setInterval(poke, pokeDelay); frame = 1, setFrame(wake); } } function x$3(d) { return d.x; } function y$3(d) { return d.y; } var initialRadius = 10; var initialAngle = Math.PI * (3 - Math.sqrt(5)); function forceSimulation(nodes) { var simulation, alpha = 1, alphaMin = 0.001, alphaDecay = 1 - Math.pow(alphaMin, 1 / 300), alphaTarget = 0, velocityDecay = 0.6, forces = map$1(), stepper = timer(step), event = dispatch("tick", "end"); if (nodes == null) nodes = []; function step() { tick(); event.call("tick", simulation); if (alpha < alphaMin) { stepper.stop(); event.call("end", simulation); } } function tick() { var i, n = nodes.length, node; alpha += (alphaTarget - alpha) * alphaDecay; forces.each(function(force) { force(alpha); }); for (i = 0; i < n; ++i) { node = nodes[i]; if (node.fx == null) node.x += node.vx *= velocityDecay; else node.x = node.fx, node.vx = 0; if (node.fy == null) node.y += node.vy *= velocityDecay; else node.y = node.fy, node.vy = 0; } } function initializeNodes() { for (var i = 0, n = nodes.length, node; i < n; ++i) { node = nodes[i], node.index = i; if (isNaN(node.x) || isNaN(node.y)) { var radius = initialRadius * Math.sqrt(i), angle = i * initialAngle; node.x = radius * Math.cos(angle); node.y = radius * Math.sin(angle); } if (isNaN(node.vx) || isNaN(node.vy)) { node.vx = node.vy = 0; } } } function initializeForce(force) { if (force.initialize) force.initialize(nodes); return force; } initializeNodes(); return simulation = { tick: tick, restart: function() { return stepper.restart(step), simulation; }, stop: function() { return stepper.stop(), simulation; }, nodes: function(_) { return arguments.length ? (nodes = _, initializeNodes(), forces.each(initializeForce), simulation) : nodes; }, alpha: function(_) { return arguments.length ? (alpha = +_, simulation) : alpha; }, alphaMin: function(_) { return arguments.length ? (alphaMin = +_, simulation) : alphaMin; }, alphaDecay: function(_) { return arguments.length ? (alphaDecay = +_, simulation) : +alphaDecay; }, alphaTarget: function(_) { return arguments.length ? (alphaTarget = +_, simulation) : alphaTarget; }, velocityDecay: function(_) { return arguments.length ? (velocityDecay = 1 - _, simulation) : 1 - velocityDecay; }, force: function(name, _) { return arguments.length > 1 ? ((_ == null ? forces.remove(name) : forces.set(name, initializeForce(_))), simulation) : forces.get(name); }, find: function(x, y, radius) { var i = 0, n = nodes.length, dx, dy, d2, node, closest; if (radius == null) radius = Infinity; else radius *= radius; for (i = 0; i < n; ++i) { node = nodes[i]; dx = x - node.x; dy = y - node.y; d2 = dx * dx + dy * dy; if (d2 < radius) closest = node, radius = d2; } return closest; }, on: function(name, _) { return arguments.length > 1 ? (event.on(name, _), simulation) : event.on(name); } }; } function forceManyBody() { var nodes, node, alpha, strength = constant$7(-30), strengths, distanceMin2 = 1, distanceMax2 = Infinity, theta2 = 0.81; function force(_) { var i, n = nodes.length, tree = quadtree(nodes, x$3, y$3).visitAfter(accumulate); for (alpha = _, i = 0; i < n; ++i) node = nodes[i], tree.visit(apply); } function initialize() { if (!nodes) return; var i, n = nodes.length; strengths = new Array(n); for (i = 0; i < n; ++i) strengths[i] = +strength(nodes[i], i, nodes); } function accumulate(quad) { var strength = 0, q, c, x, y, i; // For internal nodes, accumulate forces from child quadrants. if (quad.length) { for (x = y = i = 0; i < 4; ++i) { if ((q = quad[i]) && (c = q.value)) { strength += c, x += c * q.x, y += c * q.y; } } quad.x = x / strength; quad.y = y / strength; } // For leaf nodes, accumulate forces from coincident quadrants. else { q = quad; q.x = q.data.x; q.y = q.data.y; do strength += strengths[q.data.index]; while (q = q.next); } quad.value = strength; } function apply(quad, x1, _, x2) { if (!quad.value) return true; var x = quad.x - node.x, y = quad.y - node.y, w = x2 - x1, l = x * x + y * y; // Apply the Barnes-Hut approximation if possible. // Limit forces for very close nodes; randomize direction if coincident. if (w * w / theta2 < l) { if (l < distanceMax2) { if (x === 0) x = jiggle(), l += x * x; if (y === 0) y = jiggle(), l += y * y; if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l); node.vx += x * quad.value * alpha / l; node.vy += y * quad.value * alpha / l; } return true; } // Otherwise, process points directly. else if (quad.length || l >= distanceMax2) return; // Limit forces for very close nodes; randomize direction if coincident. if (quad.data !== node || quad.next) { if (x === 0) x = jiggle(), l += x * x; if (y === 0) y = jiggle(), l += y * y; if (l < distanceMin2) l = Math.sqrt(distanceMin2 * l); } do if (quad.data !== node) { w = strengths[quad.data.index] * alpha / l; node.vx += x * w; node.vy += y * w; } while (quad = quad.next); } force.initialize = function(_) { nodes = _; initialize(); }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant$7(+_), initialize(), force) : strength; }; force.distanceMin = function(_) { return arguments.length ? (distanceMin2 = _ * _, force) : Math.sqrt(distanceMin2); }; force.distanceMax = function(_) { return arguments.length ? (distanceMax2 = _ * _, force) : Math.sqrt(distanceMax2); }; force.theta = function(_) { return arguments.length ? (theta2 = _ * _, force) : Math.sqrt(theta2); }; return force; } function forceX(x) { var strength = constant$7(0.1), nodes, strengths, xz; if (typeof x !== "function") x = constant$7(x == null ? 0 : +x); function force(alpha) { for (var i = 0, n = nodes.length, node; i < n; ++i) { node = nodes[i], node.vx += (xz[i] - node.x) * strengths[i] * alpha; } } function initialize() { if (!nodes) return; var i, n = nodes.length; strengths = new Array(n); xz = new Array(n); for (i = 0; i < n; ++i) { strengths[i] = isNaN(xz[i] = +x(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes); } } force.initialize = function(_) { nodes = _; initialize(); }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant$7(+_), initialize(), force) : strength; }; force.x = function(_) { return arguments.length ? (x = typeof _ === "function" ? _ : constant$7(+_), initialize(), force) : x; }; return force; } function forceY(y) { var strength = constant$7(0.1), nodes, strengths, yz; if (typeof y !== "function") y = constant$7(y == null ? 0 : +y); function force(alpha) { for (var i = 0, n = nodes.length, node; i < n; ++i) { node = nodes[i], node.vy += (yz[i] - node.y) * strengths[i] * alpha; } } function initialize() { if (!nodes) return; var i, n = nodes.length; strengths = new Array(n); yz = new Array(n); for (i = 0; i < n; ++i) { strengths[i] = isNaN(yz[i] = +y(nodes[i], i, nodes)) ? 0 : +strength(nodes[i], i, nodes); } } force.initialize = function(_) { nodes = _; initialize(); }; force.strength = function(_) { return arguments.length ? (strength = typeof _ === "function" ? _ : constant$7(+_), initialize(), force) : strength; }; force.y = function(_) { return arguments.length ? (y = typeof _ === "function" ? _ : constant$7(+_), initialize(), force) : y; }; return force; } var ForceMap = { center: forceCenter, collide: forceCollide, nbody: forceManyBody, link: forceLink, x: forceX, y: forceY }; var Forces = 'forces'; var ForceParams = [ 'alpha', 'alphaMin', 'alphaTarget', 'velocityDecay', 'drag', 'forces' ]; var ForceConfig = ['static', 'iterations']; var ForceOutput = ['x', 'y', 'vx', 'vy']; /** * Force simulation layout. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<object>} params.forces - The forces to apply. */ function Force(params) { Transform.call(this, null, params); } var prototype$55 = inherits(Force, Transform); prototype$55.transform = function(_, pulse) { var sim = this.value, change = pulse.changed(pulse.ADD_REM), params = _.modified(ForceParams), iters = _.iterations || 300; // configure simulation if (!sim) { this.value = sim = simulation(pulse.source, _); sim.on('tick', rerun(pulse.dataflow, this)); if (!_.static) change = true, sim.tick(); // ensure we run on init pulse.modifies('index'); } else { if (change) pulse.modifies('index'), sim.nodes(pulse.source); if (params) setup(sim, _); } // run simulation if (params || change || _.modified(ForceConfig) || (pulse.changed() && _.restart)) { sim.alpha(Math.max(sim.alpha(), _.alpha || 1)) .alphaDecay(1 - Math.pow(sim.alphaMin(), 1 / iters)); if (_.static) { for (sim.stop(); --iters >= 0;) sim.tick(); } else { if (sim.stopped()) sim.restart(); if (!change) return pulse.StopPropagation; // defer to sim ticks } } return this.finish(_, pulse); }; prototype$55.finish = function(_, pulse) { var dataflow = pulse.dataflow; // inspect dependencies, touch link source data for (var args=this._argops, j=0, m=args.length, arg; j<m; ++j) { arg = args[j]; if (arg.name !== Forces || arg.op._argval.force !== 'link') { continue; } for (var ops=arg.op._argops, i=0, n=ops.length, op; i<n; ++i) { if (ops[i].name === 'links' && (op = ops[i].op.source)) { dataflow.touch(op); break; } } } // reflow all nodes return pulse.reflow(_.modified()).modifies(ForceOutput); }; function rerun(df, op) { return function() { df.touch(op).run(); } } function simulation(nodes, _) { var sim = forceSimulation(nodes), stopped = false, stop = sim.stop, restart = sim.restart; sim.stopped = function() { return stopped; }; sim.restart = function() { return stopped = false, restart(); }; sim.stop = function() { return stopped = true, stop(); }; return setup(sim, _, true).on('end', function() { stopped = true; }); } function setup(sim, _, init) { var f = array$1(_.forces), i, n, p; for (i=0, n=ForceParams.length; i<n; ++i) { p = ForceParams[i]; if (p !== Forces && _.modified(p)) sim[p](_[p]); } for (i=0, n=f.length; i<n; ++i) { if (init || _.modified(Forces, i)) { sim.force(Forces + i, getForce(f[i])); } } for (n=(sim.numForces || 0); i<n; ++i) { sim.force(Forces + i, null); // remove } return sim.numForces = f.length, sim; } function getForce(_) { var f, p; if (!ForceMap.hasOwnProperty(_.force)) { error('Unrecognized force: ' + _.force); } f = ForceMap[_.force](); for (p in _) if (isFunction(f[p])) f[p](_[p]); return f; } var ForceDefinition = { "type": "Force", "metadata": {"modifies": true}, "params": [ { "name": "static", "type": "boolean", "default": false }, { "name": "restart", "type": "boolean", "default": false }, { "name": "iterations", "type": "number", "default": 300 }, { "name": "alpha", "type": "number", "default": 1 }, { "name": "alphaMin", "type": "number", "default": 0.001 }, { "name": "alphaTarget", "type": "number", "default": 0 }, { "name": "drag", "type": "number", "default": 0.6 }, { "name": "forces", "type": "param", "array": true, "params": [ { "key": {"force": "center"}, "params": [ { "name": "x", "type": "number", "default": 0 }, { "name": "y", "type": "number", "default": 0 } ] }, { "key": {"force": "collide"}, "params": [ { "name": "radius", "type": "number", "expr": true }, { "name": "strength", "type": "number", "default": 0.7 }, { "name": "iterations", "type": "number", "default": 1 } ] }, { "key": {"force": "nbody"}, "params": [ { "name": "strength", "type": "number", "default": -30 }, { "name": "theta", "type": "number", "default": 0.9 }, { "name": "distanceMin", "type": "number", "default": 1 }, { "name": "distanceMax", "type": "number" } ] }, { "key": {"force": "link"}, "params": [ { "name": "links", "type": "data" }, { "name": "id", "type": "field" }, { "name": "distance", "type": "number", "default": 30, "expr": true }, { "name": "strength", "type": "number", "expr": true }, { "name": "iterations", "type": "number", "default": 1 } ] }, { "key": {"force": "x"}, "params": [ { "name": "strength", "type": "number", "default": 0.1 }, { "name": "x", "type": "field" } ] }, { "key": {"force": "y"}, "params": [ { "name": "strength", "type": "number", "default": 0.1 }, { "name": "y", "type": "field" } ] } ] }, { "name": "as", "type": "string", "array": true, "modify": false, "default": ["x", "y", "vx", "vy"] } ] }; register(ForceDefinition, Force); function defaultSeparation(a, b) { return a.parent === b.parent ? 1 : 2; } function meanX(children) { return children.reduce(meanXReduce, 0) / children.length; } function meanXReduce(x, c) { return x + c.x; } function maxY(children) { return 1 + children.reduce(maxYReduce, 0); } function maxYReduce(y, c) { return Math.max(y, c.y); } function leafLeft(node) { var children; while (children = node.children) node = children[0]; return node; } function leafRight(node) { var children; while (children = node.children) node = children[children.length - 1]; return node; } function cluster() { var separation = defaultSeparation, dx = 1, dy = 1, nodeSize = false; function cluster(root) { var previousNode, x = 0; // First walk, computing the initial x & y values. root.eachAfter(function(node) { var children = node.children; if (children) { node.x = meanX(children); node.y = maxY(children); } else { node.x = previousNode ? x += separation(node, previousNode) : 0; node.y = 0; previousNode = node; } }); var left = leafLeft(root), right = leafRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; // Second walk, normalizing x & y to the desired size. return root.eachAfter(nodeSize ? function(node) { node.x = (node.x - root.x) * dx; node.y = (root.y - node.y) * dy; } : function(node) { node.x = (node.x - x0) / (x1 - x0) * dx; node.y = (1 - (root.y ? node.y / root.y : 1)) * dy; }); } cluster.separation = function(x) { return arguments.length ? (separation = x, cluster) : separation; }; cluster.size = function(x) { return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? null : [dx, dy]); }; cluster.nodeSize = function(x) { return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster) : (nodeSize ? [dx, dy] : null); }; return cluster; } function node_each(callback) { var node = this, current, next = [node], children, i, n; do { current = next.reverse(), next = []; while (node = current.pop()) { callback(node), children = node.children; if (children) for (i = 0, n = children.length; i < n; ++i) { next.push(children[i]); } } } while (next.length); return this; } function node_eachBefore(callback) { var node = this, nodes = [node], children, i; while (node = nodes.pop()) { callback(node), children = node.children; if (children) for (i = children.length - 1; i >= 0; --i) { nodes.push(children[i]); } } return this; } function node_eachAfter(callback) { var node = this, nodes = [node], next = [], children, i, n; while (node = nodes.pop()) { next.push(node), children = node.children; if (children) for (i = 0, n = children.length; i < n; ++i) { nodes.push(children[i]); } } while (node = next.pop()) { callback(node); } return this; } function node_sum(value) { return this.eachAfter(function(node) { var sum = +value(node.data) || 0, children = node.children, i = children && children.length; while (--i >= 0) sum += children[i].value; node.value = sum; }); } function node_sort(compare) { return this.eachBefore(function(node) { if (node.children) { node.children.sort(compare); } }); } function node_path(end) { var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start]; while (start !== ancestor) { start = start.parent; nodes.push(start); } var k = nodes.length; while (end !== ancestor) { nodes.splice(k, 0, end); end = end.parent; } return nodes; } function leastCommonAncestor(a, b) { if (a === b) return a; var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null; a = aNodes.pop(); b = bNodes.pop(); while (a === b) { c = a; a = aNodes.pop(); b = bNodes.pop(); } return c; } function node_ancestors() { var node = this, nodes = [node]; while (node = node.parent) { nodes.push(node); } return nodes; } function node_descendants() { var nodes = []; this.each(function(node) { nodes.push(node); }); return nodes; } function node_leaves() { var leaves = []; this.eachBefore(function(node) { if (!node.children) { leaves.push(node); } }); return leaves; } function node_links() { var root = this, links = []; root.each(function(node) { if (node !== root) { // Don’t include the root’s parent, if any. links.push({source: node.parent, target: node}); } }); return links; } function hierarchy(data, children) { var root = new Node(data), valued = +data.value && (root.value = data.value), node, nodes = [root], child, childs, i, n; if (children == null) children = defaultChildren; while (node = nodes.pop()) { if (valued) node.value = +node.data.value; if ((childs = children(node.data)) && (n = childs.length)) { node.children = new Array(n); for (i = n - 1; i >= 0; --i) { nodes.push(child = node.children[i] = new Node(childs[i])); child.parent = node; child.depth = node.depth + 1; } } } return root.eachBefore(computeHeight); } function node_copy() { return hierarchy(this).eachBefore(copyData); } function defaultChildren(d) { return d.children; } function copyData(node) { node.data = node.data.data; } function computeHeight(node) { var height = 0; do node.height = height; while ((node = node.parent) && (node.height < ++height)); } function Node(data) { this.data = data; this.depth = this.height = 0; this.parent = null; } Node.prototype = hierarchy.prototype = { constructor: Node, each: node_each, eachAfter: node_eachAfter, eachBefore: node_eachBefore, sum: node_sum, sort: node_sort, path: node_path, ancestors: node_ancestors, descendants: node_descendants, leaves: node_leaves, links: node_links, copy: node_copy }; function Node$2(value) { this._ = value; this.next = null; } function shuffle$1(array) { var i, n = (array = array.slice()).length, head = null, node = head; while (n) { var next = new Node$2(array[n - 1]); if (node) node = node.next = next; else node = head = next; array[i] = array[--n]; } return { head: head, tail: node }; } function enclose(circles) { return encloseN(shuffle$1(circles), []); } function encloses(a, b) { var dx = b.x - a.x, dy = b.y - a.y, dr = a.r - b.r; return dr * dr + 1e-6 > dx * dx + dy * dy; } // Returns the smallest circle that contains circles L and intersects circles B. function encloseN(L, B) { var circle, l0 = null, l1 = L.head, l2, p1; switch (B.length) { case 1: circle = enclose1(B[0]); break; case 2: circle = enclose2(B[0], B[1]); break; case 3: circle = enclose3(B[0], B[1], B[2]); break; } while (l1) { p1 = l1._, l2 = l1.next; if (!circle || !encloses(circle, p1)) { // Temporarily truncate L before l1. if (l0) L.tail = l0, l0.next = null; else L.head = L.tail = null; B.push(p1); circle = encloseN(L, B); // Note: reorders L! B.pop(); // Move l1 to the front of L and reconnect the truncated list L. if (L.head) l1.next = L.head, L.head = l1; else l1.next = null, L.head = L.tail = l1; l0 = L.tail, l0.next = l2; } else { l0 = l1; } l1 = l2; } L.tail = l0; return circle; } function enclose1(a) { return { x: a.x, y: a.y, r: a.r }; } function enclose2(a, b) { var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1, l = Math.sqrt(x21 * x21 + y21 * y21); return { x: (x1 + x2 + x21 / l * r21) / 2, y: (y1 + y2 + y21 / l * r21) / 2, r: (l + r1 + r2) / 2 }; } function enclose3(a, b, c) { var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x3 = c.x, y3 = c.y, r3 = c.r, a2 = 2 * (x1 - x2), b2 = 2 * (y1 - y2), c2 = 2 * (r2 - r1), d2 = x1 * x1 + y1 * y1 - r1 * r1 - x2 * x2 - y2 * y2 + r2 * r2, a3 = 2 * (x1 - x3), b3 = 2 * (y1 - y3), c3 = 2 * (r3 - r1), d3 = x1 * x1 + y1 * y1 - r1 * r1 - x3 * x3 - y3 * y3 + r3 * r3, ab = a3 * b2 - a2 * b3, xa = (b2 * d3 - b3 * d2) / ab - x1, xb = (b3 * c2 - b2 * c3) / ab, ya = (a3 * d2 - a2 * d3) / ab - y1, yb = (a2 * c3 - a3 * c2) / ab, A = xb * xb + yb * yb - 1, B = 2 * (xa * xb + ya * yb + r1), C = xa * xa + ya * ya - r1 * r1, r = (-B - Math.sqrt(B * B - 4 * A * C)) / (2 * A); return { x: xa + xb * r + x1, y: ya + yb * r + y1, r: r }; } function place(a, b, c) { var ax = a.x, ay = a.y, da = b.r + c.r, db = a.r + c.r, dx = b.x - ax, dy = b.y - ay, dc = dx * dx + dy * dy; if (dc) { var x = 0.5 + ((db *= db) - (da *= da)) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); c.x = ax + x * dx + y * dy; c.y = ay + x * dy - y * dx; } else { c.x = ax + db; c.y = ay; } } function intersects(a, b) { var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; return dr * dr > dx * dx + dy * dy; } function distance2(circle, x, y) { var dx = circle.x - x, dy = circle.y - y; return dx * dx + dy * dy; } function Node$1(circle) { this._ = circle; this.next = null; this.previous = null; } function packEnclose(circles) { if (!(n = circles.length)) return 0; var a, b, c, n; // Place the first circle. a = circles[0], a.x = 0, a.y = 0; if (!(n > 1)) return a.r; // Place the second circle. b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0; if (!(n > 2)) return a.r + b.r; // Place the third circle. place(b, a, c = circles[2]); // Initialize the weighted centroid. var aa = a.r * a.r, ba = b.r * b.r, ca = c.r * c.r, oa = aa + ba + ca, ox = aa * a.x + ba * b.x + ca * c.x, oy = aa * a.y + ba * b.y + ca * c.y, cx, cy, i, j, k, sj, sk; // Initialize the front-chain using the first three circles a, b and c. a = new Node$1(a), b = new Node$1(b), c = new Node$1(c); a.next = c.previous = b; b.next = a.previous = c; c.next = b.previous = a; // Attempt to place each remaining circle… pack: for (i = 3; i < n; ++i) { place(a._, b._, c = circles[i]), c = new Node$1(c); // If there are only three elements in the front-chain… if ((k = a.previous) === (j = b.next)) { // If the new circle intersects the third circle, // rotate the front chain to try the next position. if (intersects(j._, c._)) { a = b, b = j, --i; continue pack; } } // Find the closest intersecting circle on the front-chain, if any. else { sj = j._.r, sk = k._.r; do { if (sj <= sk) { if (intersects(j._, c._)) { b = j, a.next = b, b.previous = a, --i; continue pack; } j = j.next, sj += j._.r; } else { if (intersects(k._, c._)) { a = k, a.next = b, b.previous = a, --i; continue pack; } k = k.previous, sk += k._.r; } } while (j !== k.next); } // Success! Insert the new circle c between a and b. c.previous = a, c.next = b, a.next = b.previous = b = c; // Update the weighted centroid. oa += ca = c._.r * c._.r; ox += ca * c._.x; oy += ca * c._.y; // Compute the new closest circle a to centroid. aa = distance2(a._, cx = ox / oa, cy = oy / oa); while ((c = c.next) !== b) { if ((ca = distance2(c._, cx, cy)) < aa) { a = c, aa = ca; } } b = a.next; } // Compute the enclosing circle of the front chain. a = [b._], c = b; while ((c = c.next) !== b) a.push(c._); c = enclose(a); // Translate the circles to put the enclosing circle around the origin. for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y; return c.r; } function optional(f) { return f == null ? null : required(f); } function required(f) { if (typeof f !== "function") throw new Error; return f; } function constantZero() { return 0; } function constant$8(x) { return function() { return x; }; } function defaultRadius(d) { return Math.sqrt(d.value); } function pack$1() { var radius = null, dx = 1, dy = 1, padding = constantZero; function pack(root) { root.x = dx / 2, root.y = dy / 2; if (radius) { root.eachBefore(radiusLeaf(radius)) .eachAfter(packChildren(padding, 0.5)) .eachBefore(translateChild(1)); } else { root.eachBefore(radiusLeaf(defaultRadius)) .eachAfter(packChildren(constantZero, 1)) .eachAfter(packChildren(padding, root.r / Math.min(dx, dy))) .eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r))); } return root; } pack.radius = function(x) { return arguments.length ? (radius = optional(x), pack) : radius; }; pack.size = function(x) { return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy]; }; pack.padding = function(x) { return arguments.length ? (padding = typeof x === "function" ? x : constant$8(+x), pack) : padding; }; return pack; } function radiusLeaf(radius) { return function(node) { if (!node.children) { node.r = Math.max(0, +radius(node) || 0); } }; } function packChildren(padding, k) { return function(node) { if (children = node.children) { var children, i, n = children.length, r = padding(node) * k || 0, e; if (r) for (i = 0; i < n; ++i) children[i].r += r; e = packEnclose(children); if (r) for (i = 0; i < n; ++i) children[i].r -= r; node.r = e + r; } }; } function translateChild(k) { return function(node) { var parent = node.parent; node.r *= k; if (parent) { node.x = parent.x + k * node.x; node.y = parent.y + k * node.y; } }; } function roundNode(node) { node.x0 = Math.round(node.x0); node.y0 = Math.round(node.y0); node.x1 = Math.round(node.x1); node.y1 = Math.round(node.y1); } function treemapDice(parent, x0, y0, x1, y1) { var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value; while (++i < n) { node = nodes[i], node.y0 = y0, node.y1 = y1; node.x0 = x0, node.x1 = x0 += node.value * k; } } function partition$2() { var dx = 1, dy = 1, padding = 0, round = false; function partition(root) { var n = root.height + 1; root.x0 = root.y0 = padding; root.x1 = dx; root.y1 = dy / n; root.eachBefore(positionNode(dy, n)); if (round) root.eachBefore(roundNode); return root; } function positionNode(dy, n) { return function(node) { if (node.children) { treemapDice(node, node.x0, dy * (node.depth + 1) / n, node.x1, dy * (node.depth + 2) / n); } var x0 = node.x0, y0 = node.y0, x1 = node.x1 - padding, y1 = node.y1 - padding; if (x1 < x0) x0 = x1 = (x0 + x1) / 2; if (y1 < y0) y0 = y1 = (y0 + y1) / 2; node.x0 = x0; node.y0 = y0; node.x1 = x1; node.y1 = y1; }; } partition.round = function(x) { return arguments.length ? (round = !!x, partition) : round; }; partition.size = function(x) { return arguments.length ? (dx = +x[0], dy = +x[1], partition) : [dx, dy]; }; partition.padding = function(x) { return arguments.length ? (padding = +x, partition) : padding; }; return partition; } var keyPrefix = "$"; var preroot = {depth: -1}; var ambiguous = {}; function defaultId(d) { return d.id; } function defaultParentId(d) { return d.parentId; } function stratify() { var id = defaultId, parentId = defaultParentId; function stratify(data) { var d, i, n = data.length, root, parent, node, nodes = new Array(n), nodeId, nodeKey, nodeByKey = {}; for (i = 0; i < n; ++i) { d = data[i], node = nodes[i] = new Node(d); if ((nodeId = id(d, i, data)) != null && (nodeId += "")) { nodeKey = keyPrefix + (node.id = nodeId); nodeByKey[nodeKey] = nodeKey in nodeByKey ? ambiguous : node; } } for (i = 0; i < n; ++i) { node = nodes[i], nodeId = parentId(data[i], i, data); if (nodeId == null || !(nodeId += "")) { if (root) throw new Error("multiple roots"); root = node; } else { parent = nodeByKey[keyPrefix + nodeId]; if (!parent) throw new Error("missing: " + nodeId); if (parent === ambiguous) throw new Error("ambiguous: " + nodeId); if (parent.children) parent.children.push(node); else parent.children = [node]; node.parent = parent; } } if (!root) throw new Error("no root"); root.parent = preroot; root.eachBefore(function(node) { node.depth = node.parent.depth + 1; --n; }).eachBefore(computeHeight); root.parent = null; if (n > 0) throw new Error("cycle"); return root; } stratify.id = function(x) { return arguments.length ? (id = required(x), stratify) : id; }; stratify.parentId = function(x) { return arguments.length ? (parentId = required(x), stratify) : parentId; }; return stratify; } function defaultSeparation$1(a, b) { return a.parent === b.parent ? 1 : 2; } // function radialSeparation(a, b) { // return (a.parent === b.parent ? 1 : 2) / a.depth; // } // This function is used to traverse the left contour of a subtree (or // subforest). It returns the successor of v on this contour. This successor is // either given by the leftmost child of v or by the thread of v. The function // returns null if and only if v is on the highest level of its subtree. function nextLeft(v) { var children = v.children; return children ? children[0] : v.t; } // This function works analogously to nextLeft. function nextRight(v) { var children = v.children; return children ? children[children.length - 1] : v.t; } // Shifts the current subtree rooted at w+. This is done by increasing // prelim(w+) and mod(w+) by shift. function moveSubtree(wm, wp, shift) { var change = shift / (wp.i - wm.i); wp.c -= change; wp.s += shift; wm.c += change; wp.z += shift; wp.m += shift; } // All other shifts, applied to the smaller subtrees between w- and w+, are // performed by this function. To prepare the shifts, we have to adjust // change(w+), shift(w+), and change(w-). function executeShifts(v) { var shift = 0, change = 0, children = v.children, i = children.length, w; while (--i >= 0) { w = children[i]; w.z += shift; w.m += shift; shift += w.s + (change += w.c); } } // If vi-’s ancestor is a sibling of v, returns vi-’s ancestor. Otherwise, // returns the specified (default) ancestor. function nextAncestor(vim, v, ancestor) { return vim.a.parent === v.parent ? vim.a : ancestor; } function TreeNode(node, i) { this._ = node; this.parent = null; this.children = null; this.A = null; // default ancestor this.a = this; // ancestor this.z = 0; // prelim this.m = 0; // mod this.c = 0; // change this.s = 0; // shift this.t = null; // thread this.i = i; // number } TreeNode.prototype = Object.create(Node.prototype); function treeRoot(root) { var tree = new TreeNode(root, 0), node, nodes = [tree], child, children, i, n; while (node = nodes.pop()) { if (children = node._.children) { node.children = new Array(n = children.length); for (i = n - 1; i >= 0; --i) { nodes.push(child = node.children[i] = new TreeNode(children[i], i)); child.parent = node; } } } (tree.parent = new TreeNode(null, 0)).children = [tree]; return tree; } // Node-link tree diagram using the Reingold-Tilford "tidy" algorithm function tree() { var separation = defaultSeparation$1, dx = 1, dy = 1, nodeSize = null; function tree(root) { var t = treeRoot(root); // Compute the layout using Buchheim et al.’s algorithm. t.eachAfter(firstWalk), t.parent.m = -t.z; t.eachBefore(secondWalk); // If a fixed node size is specified, scale x and y. if (nodeSize) root.eachBefore(sizeNode); // If a fixed tree size is specified, scale x and y based on the extent. // Compute the left-most, right-most, and depth-most nodes for extents. else { var left = root, right = root, bottom = root; root.eachBefore(function(node) { if (node.x < left.x) left = node; if (node.x > right.x) right = node; if (node.depth > bottom.depth) bottom = node; }); var s = left === right ? 1 : separation(left, right) / 2, tx = s - left.x, kx = dx / (right.x + s + tx), ky = dy / (bottom.depth || 1); root.eachBefore(function(node) { node.x = (node.x + tx) * kx; node.y = node.depth * ky; }); } return root; } // Computes a preliminary x-coordinate for v. Before that, FIRST WALK is // applied recursively to the children of v, as well as the function // APPORTION. After spacing out the children by calling EXECUTE SHIFTS, the // node v is placed to the midpoint of its outermost children. function firstWalk(v) { var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null; if (children) { executeShifts(v); var midpoint = (children[0].z + children[children.length - 1].z) / 2; if (w) { v.z = w.z + separation(v._, w._); v.m = v.z - midpoint; } else { v.z = midpoint; } } else if (w) { v.z = w.z + separation(v._, w._); } v.parent.A = apportion(v, w, v.parent.A || siblings[0]); } // Computes all real x-coordinates by summing up the modifiers recursively. function secondWalk(v) { v._.x = v.z + v.parent.m; v.m += v.parent.m; } // The core of the algorithm. Here, a new subtree is combined with the // previous subtrees. Threads are used to traverse the inside and outside // contours of the left and right subtree up to the highest common level. The // vertices used for the traversals are vi+, vi-, vo-, and vo+, where the // superscript o means outside and i means inside, the subscript - means left // subtree and + means right subtree. For summing up the modifiers along the // contour, we use respective variables si+, si-, so-, and so+. Whenever two // nodes of the inside contours conflict, we compute the left one of the // greatest uncommon ancestors using the function ANCESTOR and call MOVE // SUBTREE to shift the subtree and prepare the shifts of smaller subtrees. // Finally, we add a new thread (if necessary). function apportion(v, w, ancestor) { if (w) { var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) { vom = nextLeft(vom); vop = nextRight(vop); vop.a = v; shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); if (shift > 0) { moveSubtree(nextAncestor(vim, v, ancestor), v, shift); sip += shift; sop += shift; } sim += vim.m; sip += vip.m; som += vom.m; sop += vop.m; } if (vim && !nextRight(vop)) { vop.t = vim; vop.m += sim - sop; } if (vip && !nextLeft(vom)) { vom.t = vip; vom.m += sip - som; ancestor = v; } } return ancestor; } function sizeNode(node) { node.x *= dx; node.y = node.depth * dy; } tree.separation = function(x) { return arguments.length ? (separation = x, tree) : separation; }; tree.size = function(x) { return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree) : (nodeSize ? null : [dx, dy]); }; tree.nodeSize = function(x) { return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree) : (nodeSize ? [dx, dy] : null); }; return tree; } function treemapSlice(parent, x0, y0, x1, y1) { var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value; while (++i < n) { node = nodes[i], node.x0 = x0, node.x1 = x1; node.y0 = y0, node.y1 = y0 += node.value * k; } } var phi = (1 + Math.sqrt(5)) / 2; function squarifyRatio(ratio, parent, x0, y0, x1, y1) { var rows = [], nodes = parent.children, row, nodeValue, i0 = 0, i1, n = nodes.length, dx, dy, value = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta; while (i0 < n) { dx = x1 - x0, dy = y1 - y0; minValue = maxValue = sumValue = nodes[i0].value; alpha = Math.max(dy / dx, dx / dy) / (value * ratio); beta = sumValue * sumValue * alpha; minRatio = Math.max(maxValue / beta, beta / minValue); // Keep adding nodes while the aspect ratio maintains or improves. for (i1 = i0 + 1; i1 < n; ++i1) { sumValue += nodeValue = nodes[i1].value; if (nodeValue < minValue) minValue = nodeValue; if (nodeValue > maxValue) maxValue = nodeValue; beta = sumValue * sumValue * alpha; newRatio = Math.max(maxValue / beta, beta / minValue); if (newRatio > minRatio) { sumValue -= nodeValue; break; } minRatio = newRatio; } // Position and record the row orientation. rows.push(row = {value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1)}); if (row.dice) treemapDice(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1); else treemapSlice(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1); value -= sumValue, i0 = i1; } return rows; } var treemapSquarify = (function custom(ratio) { function squarify(parent, x0, y0, x1, y1) { squarifyRatio(ratio, parent, x0, y0, x1, y1); } squarify.ratio = function(x) { return custom((x = +x) > 1 ? x : 1); }; return squarify; })(phi); function treemap() { var tile = treemapSquarify, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero; function treemap(root) { root.x0 = root.y0 = 0; root.x1 = dx; root.y1 = dy; root.eachBefore(positionNode); paddingStack = [0]; if (round) root.eachBefore(roundNode); return root; } function positionNode(node) { var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p; if (x1 < x0) x0 = x1 = (x0 + x1) / 2; if (y1 < y0) y0 = y1 = (y0 + y1) / 2; node.x0 = x0; node.y0 = y0; node.x1 = x1; node.y1 = y1; if (node.children) { p = paddingStack[node.depth + 1] = paddingInner(node) / 2; x0 += paddingLeft(node) - p; y0 += paddingTop(node) - p; x1 -= paddingRight(node) - p; y1 -= paddingBottom(node) - p; if (x1 < x0) x0 = x1 = (x0 + x1) / 2; if (y1 < y0) y0 = y1 = (y0 + y1) / 2; tile(node, x0, y0, x1, y1); } } treemap.round = function(x) { return arguments.length ? (round = !!x, treemap) : round; }; treemap.size = function(x) { return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy]; }; treemap.tile = function(x) { return arguments.length ? (tile = required(x), treemap) : tile; }; treemap.padding = function(x) { return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner(); }; treemap.paddingInner = function(x) { return arguments.length ? (paddingInner = typeof x === "function" ? x : constant$8(+x), treemap) : paddingInner; }; treemap.paddingOuter = function(x) { return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop(); }; treemap.paddingTop = function(x) { return arguments.length ? (paddingTop = typeof x === "function" ? x : constant$8(+x), treemap) : paddingTop; }; treemap.paddingRight = function(x) { return arguments.length ? (paddingRight = typeof x === "function" ? x : constant$8(+x), treemap) : paddingRight; }; treemap.paddingBottom = function(x) { return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant$8(+x), treemap) : paddingBottom; }; treemap.paddingLeft = function(x) { return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant$8(+x), treemap) : paddingLeft; }; return treemap; } function treemapBinary(parent, x0, y0, x1, y1) { var nodes = parent.children, i, n = nodes.length, sum, sums = new Array(n + 1); for (sums[0] = sum = i = 0; i < n; ++i) { sums[i + 1] = sum += nodes[i].value; } partition(0, n, parent.value, x0, y0, x1, y1); function partition(i, j, value, x0, y0, x1, y1) { if (i >= j - 1) { var node = nodes[i]; node.x0 = x0, node.y0 = y0; node.x1 = x1, node.y1 = y1; return; } var valueOffset = sums[i], valueTarget = (value / 2) + valueOffset, k = i + 1, hi = j - 1; while (k < hi) { var mid = k + hi >>> 1; if (sums[mid] < valueTarget) k = mid + 1; else hi = mid; } var valueLeft = sums[k] - valueOffset, valueRight = value - valueLeft; if ((y1 - y0) > (x1 - x0)) { var yk = (y0 * valueRight + y1 * valueLeft) / value; partition(i, k, valueLeft, x0, y0, x1, yk); partition(k, j, valueRight, x0, yk, x1, y1); } else { var xk = (x0 * valueRight + x1 * valueLeft) / value; partition(i, k, valueLeft, x0, y0, xk, y1); partition(k, j, valueRight, xk, y0, x1, y1); } } } function treemapSliceDice(parent, x0, y0, x1, y1) { (parent.depth & 1 ? treemapSlice : treemapDice)(parent, x0, y0, x1, y1); } var treemapResquarify = (function custom(ratio) { function resquarify(parent, x0, y0, x1, y1) { if ((rows = parent._squarify) && (rows.ratio === ratio)) { var rows, row, nodes, i, j = -1, n, m = rows.length, value = parent.value; while (++j < m) { row = rows[j], nodes = row.children; for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value; if (row.dice) treemapDice(row, x0, y0, x1, y0 += (y1 - y0) * row.value / value); else treemapSlice(row, x0, y0, x0 += (x1 - x0) * row.value / value, y1); value -= row.value; } } else { parent._squarify = rows = squarifyRatio(ratio, parent, x0, y0, x1, y1); rows.ratio = ratio; } } resquarify.ratio = function(x) { return custom((x = +x) > 1 ? x : 1); }; return resquarify; })(phi); /** * Nest tuples into a tree structure, grouped by key values. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<function(object): *>} params.keys - The key fields to nest by, in order. */ function Nest(params) { Transform.call(this, null, params); } var prototype$56 = inherits(Nest, Transform); function children(n) { return n.values; } prototype$56.transform = function(_, pulse) { if (!pulse.source) { error('Nest transform requires an upstream data source.'); } var root, tree, map, mod; if (!this.value || (mod = _.modified()) || pulse.changed()) { root = array$1(_.keys) .reduce(function(n, k) { return (n.key(k), n)}, nest()) .entries(pulse.source); tree = hierarchy({values: root}, children); map = tree.lookup = {}; tree.each(function(node) { if ('_id' in node.data) map[node.data._id] = node; }); this.value = tree; } pulse.source.root = this.value; return mod ? pulse.fork(pulse.ALL) : pulse; }; /** * Stratify a collection of tuples into a tree structure based on * id and parent id fields. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.key - Unique key field for each tuple. * @param {function(object): *} params.parentKey - Field with key for parent tuple. */ function Stratify(params) { Transform.call(this, null, params); } var prototype$57 = inherits(Stratify, Transform); prototype$57.transform = function(_, pulse) { if (!pulse.source) { error('Stratify transform requires an upstream data source.'); } var mod = _.modified(), tree, map, run = !this.value || mod || pulse.changed(pulse.ADD_REM) || pulse.modified(_.key.fields) || pulse.modified(_.parentKey.fields); if (run) { tree = stratify().id(_.key).parentId(_.parentKey)(pulse.source); map = tree.lookup = {}; tree.each(function(node) { map[node.data._id] = node; }); this.value = tree; } pulse.source.root = this.value; return mod ? pulse.fork(pulse.ALL) : pulse; }; /** * Generate tuples representing links between tree nodes. * The resulting tuples will contain 'source' and 'target' fields, * which point to parent and child node tuples, respectively. * @constructor * @param {object} params - The parameters for this operator. */ function TreeLinks(params) { Transform.call(this, {}, params); } var prototype$58 = inherits(TreeLinks, Transform); function parentTuple(node) { var p; return node.parent && (p=node.parent.data) && '_id' in p && p; } prototype$58.transform = function(_, pulse) { if (!pulse.source || !pulse.source.root) { error('TreeLinks transform requires a backing tree data source.'); } var root = pulse.source.root, nodes = root.lookup, links = this.value, mods = {}, out = pulse.fork(); function modify(id) { var link = links[id]; if (link) mods[id] = 1, out.mod.push(link); } // process removed tuples // assumes that if a parent node is removed the child will be, too. pulse.visit(pulse.REM, function(t) { var link = links[t._id]; if (link) delete links[t._id], out.rem.push(link); }); // create new link instances for added nodes with valid parents pulse.visit(pulse.ADD, function(t) { var id = t._id, p; if (p = parentTuple(nodes[id])) { out.add.push(links[id] = ingest({source: p, target: t})); mods[id] = 1; } }); // process modified nodes and their children pulse.visit(pulse.MOD, function(t) { var id = t._id, node = nodes[id], kids = node.children; modify(id); if (kids) for (var i=0, n=kids.length; i<n; ++i) { if (!mods[(id=kids[i].data._id)]) modify(id); } }); return out; }; var Tiles = { binary: treemapBinary, dice: treemapDice, slice: treemapSlice, slicedice: treemapSliceDice, squarify: treemapSquarify, resquarify: treemapResquarify }; var Layouts = { tidy: tree, cluster: cluster }; /** * Tree layout generator. Supports both 'tidy' and 'cluster' layouts. */ function treeLayout(method) { var m = method || 'tidy'; if (Layouts.hasOwnProperty(m)) return Layouts[m](); else error('Unrecognized Tree layout method: ' + m); } /** * Treemap layout generator. Adds 'method' and 'ratio' parameters * to configure the underlying tile method. */ function treemapLayout() { var x = treemap(); x.ratio = function(_) { var t = x.tile(); if (t.ratio) x.tile(t.ratio(_)); }; x.method = function(_) { if (Tiles.hasOwnProperty(_)) x.tile(Tiles[_]); else error('Unrecognized Treemap layout method: ' + _); }; return x; } /** * Abstract class for tree layout. * @constructor * @param {object} params - The parameters for this operator. */ function HierarchyLayout(params) { Transform.call(this, null, params); } var prototype$59 = inherits(HierarchyLayout, Transform); prototype$59.transform = function(_, pulse) { if (!pulse.source || !pulse.source.root) { error(this.constructor.name + ' transform requires a backing tree data source.'); } var layout = this.layout(_.method), fields = this.fields, root = pulse.source.root, as = _.as || fields; if (_.field) root.sum(_.field); if (_.sort) root.sort(_.sort); setParams(layout, this.params, _); try { this.value = layout(root); } catch (err) { error(err); } root.each(function(node) { setFields(node, fields, as); }); return pulse.reflow(_.modified()).modifies(as).modifies('leaf'); }; function setParams(layout, params, _) { for (var p, i=0, n=params.length; i<n; ++i) { p = params[i]; if (p in _) layout[p](_[p]); } } function setFields(node, fields, as) { var t = node.data; for (var i=0, n=fields.length-1; i<n; ++i) { t[as[i]] = node[fields[i]]; } t[as[n]] = node.children ? node.children.length : 0; } /** * Tree layout. Depending on the method parameter, performs either * Reingold-Tilford 'tidy' layout or dendrogram 'cluster' layout. * @constructor * @param {object} params - The parameters for this operator. */ function Tree(params) { HierarchyLayout.call(this, params); } inherits(Tree, HierarchyLayout); Tree.prototype.layout = treeLayout; Tree.prototype.params = ['size', 'nodeSize', 'separation']; Tree.prototype.fields = ['x', 'y', 'depth', 'children']; /** * Treemap layout. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to size nodes. */ function Treemap(params) { HierarchyLayout.call(this, params); } inherits(Treemap, HierarchyLayout); Treemap.prototype.layout = treemapLayout; Treemap.prototype.params = [ 'method', 'ratio', 'size', 'round', 'padding', 'paddingInner', 'paddingOuter', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft' ]; Treemap.prototype.fields = ['x0', 'y0', 'x1', 'y1', 'depth', 'children']; /** * Partition tree layout. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to size nodes. */ function Partition(params) { HierarchyLayout.call(this, params); } inherits(Partition, HierarchyLayout); Partition.prototype.layout = partition$2; Partition.prototype.params = ['size', 'round', 'padding']; Partition.prototype.fields = Treemap.prototype.fields; /** * Packed circle tree layout. * @constructor * @param {object} params - The parameters for this operator. * @param {function(object): *} params.field - The value field to size nodes. */ function Pack(params) { HierarchyLayout.call(this, params); } inherits(Pack, HierarchyLayout); Pack.prototype.layout = pack$1; Pack.prototype.params = ['size', 'padding']; Pack.prototype.fields = ['x', 'y', 'r', 'depth', 'children']; var NestDefinition = { "type": "Nest", "metadata": {"treesource": true}, "params": [ { "name": "keys", "type": "field", "array": true } ] }; var StratifyDefinition = { "type": "Stratify", "metadata": {"treesource": true}, "params": [ { "name": "key", "type": "field", "required": true }, { "name": "parentKey", "type": "field", "required": true } ] }; var TreeLinksDefinition = { "type": "TreeLinks", "metadata": {"tree": true, "generates": true, "changes": true}, "params": [] } var PackDefinition = { "type": "Pack", "metadata": {"tree": true, "modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "sort", "type": "compare" }, { "name": "padding", "type": "number", "default": 0 }, { "name": "radius", "type": "field", "default": null }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 3, "default": ["x", "y", "r", "depth", "children"] } ] }; var PartitionDefinition = { "type": "Partition", "metadata": {"tree": true, "modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "sort", "type": "compare" }, { "name": "padding", "type": "number", "default": 0 }, { "name": "round", "type": "boolean", "default": false }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 4, "default": ["x0", "y0", "x1", "y1", "depth", "children"] } ] }; var TreeDefinition = { "type": "Tree", "metadata": {"tree": true, "modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "sort", "type": "compare" }, { "name": "method", "type": "enum", "default": "tidy", "values": ["tidy", "cluster"] }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "nodeSize", "type": "number", "array": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 4, "default": ["x", "y", "depth", "children"] } ] }; var TreemapDefinition = { "type": "Treemap", "metadata": {"tree": true, "modifies": true}, "params": [ { "name": "field", "type": "field" }, { "name": "sort", "type": "compare" }, { "name": "method", "type": "enum", "default": "squarify", "values": ["squarify", "resquarify", "binary", "dice", "slice", "slicedice"] }, { "name": "padding", "type": "number", "default": 0 }, { "name": "paddingInner", "type": "number", "default": 0 }, { "name": "paddingOuter", "type": "number", "default": 0 }, { "name": "paddingTop", "type": "number", "default": 0 }, { "name": "paddingRight", "type": "number", "default": 0 }, { "name": "paddingBottom", "type": "number", "default": 0 }, { "name": "paddingLeft", "type": "number", "default": 0 }, { "name": "ratio", "type": "number", "default": 1.618033988749895 }, { "name": "round", "type": "boolean", "default": false }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "as", "type": "string", "array": true, "length": 4, "default": ["x0", "y0", "x1", "y1", "depth", "children"] } ] }; register(NestDefinition, Nest); register(StratifyDefinition, Stratify); register(TreeLinksDefinition, TreeLinks); register(PackDefinition, Pack); register(PartitionDefinition, Partition); register(TreeDefinition, Tree); register(TreemapDefinition, Treemap); function constant$9(x) { return function() { return x; }; } function x$4(d) { return d[0]; } function y$4(d) { return d[1]; } function RedBlackTree() { this._ = null; // root node } function RedBlackNode(node) { node.U = // parent node node.C = // color - true for red, false for black node.L = // left node node.R = // right node node.P = // previous node node.N = null; // next node } RedBlackTree.prototype = { constructor: RedBlackTree, insert: function(after, node) { var parent, grandpa, uncle; if (after) { node.P = after; node.N = after.N; if (after.N) after.N.P = node; after.N = node; if (after.R) { after = after.R; while (after.L) after = after.L; after.L = node; } else { after.R = node; } parent = after; } else if (this._) { after = RedBlackFirst(this._); node.P = null; node.N = after; after.P = after.L = node; parent = after; } else { node.P = node.N = null; this._ = node; parent = null; } node.L = node.R = null; node.U = parent; node.C = true; after = node; while (parent && parent.C) { grandpa = parent.U; if (parent === grandpa.L) { uncle = grandpa.R; if (uncle && uncle.C) { parent.C = uncle.C = false; grandpa.C = true; after = grandpa; } else { if (after === parent.R) { RedBlackRotateLeft(this, parent); after = parent; parent = after.U; } parent.C = false; grandpa.C = true; RedBlackRotateRight(this, grandpa); } } else { uncle = grandpa.L; if (uncle && uncle.C) { parent.C = uncle.C = false; grandpa.C = true; after = grandpa; } else { if (after === parent.L) { RedBlackRotateRight(this, parent); after = parent; parent = after.U; } parent.C = false; grandpa.C = true; RedBlackRotateLeft(this, grandpa); } } parent = after.U; } this._.C = false; }, remove: function(node) { if (node.N) node.N.P = node.P; if (node.P) node.P.N = node.N; node.N = node.P = null; var parent = node.U, sibling, left = node.L, right = node.R, next, red; if (!left) next = right; else if (!right) next = left; else next = RedBlackFirst(right); if (parent) { if (parent.L === node) parent.L = next; else parent.R = next; } else { this._ = next; } if (left && right) { red = next.C; next.C = node.C; next.L = left; left.U = next; if (next !== right) { parent = next.U; next.U = node.U; node = next.R; parent.L = node; next.R = right; right.U = next; } else { next.U = parent; parent = next; node = next.R; } } else { red = node.C; node = next; } if (node) node.U = parent; if (red) return; if (node && node.C) { node.C = false; return; } do { if (node === this._) break; if (node === parent.L) { sibling = parent.R; if (sibling.C) { sibling.C = false; parent.C = true; RedBlackRotateLeft(this, parent); sibling = parent.R; } if ((sibling.L && sibling.L.C) || (sibling.R && sibling.R.C)) { if (!sibling.R || !sibling.R.C) { sibling.L.C = false; sibling.C = true; RedBlackRotateRight(this, sibling); sibling = parent.R; } sibling.C = parent.C; parent.C = sibling.R.C = false; RedBlackRotateLeft(this, parent); node = this._; break; } } else { sibling = parent.L; if (sibling.C) { sibling.C = false; parent.C = true; RedBlackRotateRight(this, parent); sibling = parent.L; } if ((sibling.L && sibling.L.C) || (sibling.R && sibling.R.C)) { if (!sibling.L || !sibling.L.C) { sibling.R.C = false; sibling.C = true; RedBlackRotateLeft(this, sibling); sibling = parent.L; } sibling.C = parent.C; parent.C = sibling.L.C = false; RedBlackRotateRight(this, parent); node = this._; break; } } sibling.C = true; node = parent; parent = parent.U; } while (!node.C); if (node) node.C = false; } }; function RedBlackRotateLeft(tree, node) { var p = node, q = node.R, parent = p.U; if (parent) { if (parent.L === p) parent.L = q; else parent.R = q; } else { tree._ = q; } q.U = parent; p.U = q; p.R = q.L; if (p.R) p.R.U = p; q.L = p; } function RedBlackRotateRight(tree, node) { var p = node, q = node.L, parent = p.U; if (parent) { if (parent.L === p) parent.L = q; else parent.R = q; } else { tree._ = q; } q.U = parent; p.U = q; p.L = q.R; if (p.L) p.L.U = p; q.R = p; } function RedBlackFirst(node) { while (node.L) node = node.L; return node; } function createEdge(left, right, v0, v1) { var edge = [null, null], index = edges.push(edge) - 1; edge.left = left; edge.right = right; if (v0) setEdgeEnd(edge, left, right, v0); if (v1) setEdgeEnd(edge, right, left, v1); cells[left.index].halfedges.push(index); cells[right.index].halfedges.push(index); return edge; } function createBorderEdge(left, v0, v1) { var edge = [v0, v1]; edge.left = left; return edge; } function setEdgeEnd(edge, left, right, vertex) { if (!edge[0] && !edge[1]) { edge[0] = vertex; edge.left = left; edge.right = right; } else if (edge.left === right) { edge[1] = vertex; } else { edge[0] = vertex; } } // Liang–Barsky line clipping. function clipEdge(edge, x0, y0, x1, y1) { var a = edge[0], b = edge[1], ax = a[0], ay = a[1], bx = b[0], by = b[1], t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r; r = x0 - ax; if (!dx && r > 0) return; r /= dx; if (dx < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dx > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = x1 - ax; if (!dx && r < 0) return; r /= dx; if (dx < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dx > 0) { if (r < t0) return; if (r < t1) t1 = r; } r = y0 - ay; if (!dy && r > 0) return; r /= dy; if (dy < 0) { if (r < t0) return; if (r < t1) t1 = r; } else if (dy > 0) { if (r > t1) return; if (r > t0) t0 = r; } r = y1 - ay; if (!dy && r < 0) return; r /= dy; if (dy < 0) { if (r > t1) return; if (r > t0) t0 = r; } else if (dy > 0) { if (r < t0) return; if (r < t1) t1 = r; } if (!(t0 > 0) && !(t1 < 1)) return true; // TODO Better check? if (t0 > 0) edge[0] = [ax + t0 * dx, ay + t0 * dy]; if (t1 < 1) edge[1] = [ax + t1 * dx, ay + t1 * dy]; return true; } function connectEdge(edge, x0, y0, x1, y1) { var v1 = edge[1]; if (v1) return true; var v0 = edge[0], left = edge.left, right = edge.right, lx = left[0], ly = left[1], rx = right[0], ry = right[1], fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; if (ry === ly) { if (fx < x0 || fx >= x1) return; if (lx > rx) { if (!v0) v0 = [fx, y0]; else if (v0[1] >= y1) return; v1 = [fx, y1]; } else { if (!v0) v0 = [fx, y1]; else if (v0[1] < y0) return; v1 = [fx, y0]; } } else { fm = (lx - rx) / (ry - ly); fb = fy - fm * fx; if (fm < -1 || fm > 1) { if (lx > rx) { if (!v0) v0 = [(y0 - fb) / fm, y0]; else if (v0[1] >= y1) return; v1 = [(y1 - fb) / fm, y1]; } else { if (!v0) v0 = [(y1 - fb) / fm, y1]; else if (v0[1] < y0) return; v1 = [(y0 - fb) / fm, y0]; } } else { if (ly < ry) { if (!v0) v0 = [x0, fm * x0 + fb]; else if (v0[0] >= x1) return; v1 = [x1, fm * x1 + fb]; } else { if (!v0) v0 = [x1, fm * x1 + fb]; else if (v0[0] < x0) return; v1 = [x0, fm * x0 + fb]; } } } edge[0] = v0; edge[1] = v1; return true; } function clipEdges(x0, y0, x1, y1) { var i = edges.length, edge; while (i--) { if (!connectEdge(edge = edges[i], x0, y0, x1, y1) || !clipEdge(edge, x0, y0, x1, y1) || !(Math.abs(edge[0][0] - edge[1][0]) > epsilon$3 || Math.abs(edge[0][1] - edge[1][1]) > epsilon$3)) { delete edges[i]; } } } function createCell(site) { return cells[site.index] = { site: site, halfedges: [] }; } function cellHalfedgeAngle(cell, edge) { var site = cell.site, va = edge.left, vb = edge.right; if (site === vb) vb = va, va = site; if (vb) return Math.atan2(vb[1] - va[1], vb[0] - va[0]); if (site === va) va = edge[1], vb = edge[0]; else va = edge[0], vb = edge[1]; return Math.atan2(va[0] - vb[0], vb[1] - va[1]); } function cellHalfedgeStart(cell, edge) { return edge[+(edge.left !== cell.site)]; } function cellHalfedgeEnd(cell, edge) { return edge[+(edge.left === cell.site)]; } function sortCellHalfedges() { for (var i = 0, n = cells.length, cell, halfedges, j, m; i < n; ++i) { if ((cell = cells[i]) && (m = (halfedges = cell.halfedges).length)) { var index = new Array(m), array = new Array(m); for (j = 0; j < m; ++j) index[j] = j, array[j] = cellHalfedgeAngle(cell, edges[halfedges[j]]); index.sort(function(i, j) { return array[j] - array[i]; }); for (j = 0; j < m; ++j) array[j] = halfedges[index[j]]; for (j = 0; j < m; ++j) halfedges[j] = array[j]; } } } function clipCells(x0, y0, x1, y1) { var nCells = cells.length, iCell, cell, site, iHalfedge, halfedges, nHalfedges, start, startX, startY, end, endX, endY, cover = true; for (iCell = 0; iCell < nCells; ++iCell) { if (cell = cells[iCell]) { site = cell.site; halfedges = cell.halfedges; iHalfedge = halfedges.length; // Remove any dangling clipped edges. while (iHalfedge--) { if (!edges[halfedges[iHalfedge]]) { halfedges.splice(iHalfedge, 1); } } // Insert any border edges as necessary. iHalfedge = 0, nHalfedges = halfedges.length; while (iHalfedge < nHalfedges) { end = cellHalfedgeEnd(cell, edges[halfedges[iHalfedge]]), endX = end[0], endY = end[1]; start = cellHalfedgeStart(cell, edges[halfedges[++iHalfedge % nHalfedges]]), startX = start[0], startY = start[1]; if (Math.abs(endX - startX) > epsilon$3 || Math.abs(endY - startY) > epsilon$3) { halfedges.splice(iHalfedge, 0, edges.push(createBorderEdge(site, end, Math.abs(endX - x0) < epsilon$3 && y1 - endY > epsilon$3 ? [x0, Math.abs(startX - x0) < epsilon$3 ? startY : y1] : Math.abs(endY - y1) < epsilon$3 && x1 - endX > epsilon$3 ? [Math.abs(startY - y1) < epsilon$3 ? startX : x1, y1] : Math.abs(endX - x1) < epsilon$3 && endY - y0 > epsilon$3 ? [x1, Math.abs(startX - x1) < epsilon$3 ? startY : y0] : Math.abs(endY - y0) < epsilon$3 && endX - x0 > epsilon$3 ? [Math.abs(startY - y0) < epsilon$3 ? startX : x0, y0] : null)) - 1); ++nHalfedges; } } if (nHalfedges) cover = false; } } // If there weren’t any edges, have the closest site cover the extent. // It doesn’t matter which corner of the extent we measure! if (cover) { var dx, dy, d2, dc = Infinity; for (iCell = 0, cover = null; iCell < nCells; ++iCell) { if (cell = cells[iCell]) { site = cell.site; dx = site[0] - x0; dy = site[1] - y0; d2 = dx * dx + dy * dy; if (d2 < dc) dc = d2, cover = cell; } } if (cover) { var v00 = [x0, y0], v01 = [x0, y1], v11 = [x1, y1], v10 = [x1, y0]; cover.halfedges.push( edges.push(createBorderEdge(site = cover.site, v00, v01)) - 1, edges.push(createBorderEdge(site, v01, v11)) - 1, edges.push(createBorderEdge(site, v11, v10)) - 1, edges.push(createBorderEdge(site, v10, v00)) - 1 ); } } // Lastly delete any cells with no edges; these were entirely clipped. for (iCell = 0; iCell < nCells; ++iCell) { if (cell = cells[iCell]) { if (!cell.halfedges.length) { delete cells[iCell]; } } } } var circlePool = []; var firstCircle; function Circle() { RedBlackNode(this); this.x = this.y = this.arc = this.site = this.cy = null; } function attachCircle(arc) { var lArc = arc.P, rArc = arc.N; if (!lArc || !rArc) return; var lSite = lArc.site, cSite = arc.site, rSite = rArc.site; if (lSite === rSite) return; var bx = cSite[0], by = cSite[1], ax = lSite[0] - bx, ay = lSite[1] - by, cx = rSite[0] - bx, cy = rSite[1] - by; var d = 2 * (ax * cy - ay * cx); if (d >= -epsilon2$2) return; var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d; var circle = circlePool.pop() || new Circle; circle.arc = arc; circle.site = cSite; circle.x = x + bx; circle.y = (circle.cy = y + by) + Math.sqrt(x * x + y * y); // y bottom arc.circle = circle; var before = null, node = circles._; while (node) { if (circle.y < node.y || (circle.y === node.y && circle.x <= node.x)) { if (node.L) node = node.L; else { before = node.P; break; } } else { if (node.R) node = node.R; else { before = node; break; } } } circles.insert(before, circle); if (!before) firstCircle = circle; } function detachCircle(arc) { var circle = arc.circle; if (circle) { if (!circle.P) firstCircle = circle.N; circles.remove(circle); circlePool.push(circle); RedBlackNode(circle); arc.circle = null; } } var beachPool = []; function Beach() { RedBlackNode(this); this.edge = this.site = this.circle = null; } function createBeach(site) { var beach = beachPool.pop() || new Beach; beach.site = site; return beach; } function detachBeach(beach) { detachCircle(beach); beaches.remove(beach); beachPool.push(beach); RedBlackNode(beach); } function removeBeach(beach) { var circle = beach.circle, x = circle.x, y = circle.cy, vertex = [x, y], previous = beach.P, next = beach.N, disappearing = [beach]; detachBeach(beach); var lArc = previous; while (lArc.circle && Math.abs(x - lArc.circle.x) < epsilon$3 && Math.abs(y - lArc.circle.cy) < epsilon$3) { previous = lArc.P; disappearing.unshift(lArc); detachBeach(lArc); lArc = previous; } disappearing.unshift(lArc); detachCircle(lArc); var rArc = next; while (rArc.circle && Math.abs(x - rArc.circle.x) < epsilon$3 && Math.abs(y - rArc.circle.cy) < epsilon$3) { next = rArc.N; disappearing.push(rArc); detachBeach(rArc); rArc = next; } disappearing.push(rArc); detachCircle(rArc); var nArcs = disappearing.length, iArc; for (iArc = 1; iArc < nArcs; ++iArc) { rArc = disappearing[iArc]; lArc = disappearing[iArc - 1]; setEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); } lArc = disappearing[0]; rArc = disappearing[nArcs - 1]; rArc.edge = createEdge(lArc.site, rArc.site, null, vertex); attachCircle(lArc); attachCircle(rArc); } function addBeach(site) { var x = site[0], directrix = site[1], lArc, rArc, dxl, dxr, node = beaches._; while (node) { dxl = leftBreakPoint(node, directrix) - x; if (dxl > epsilon$3) node = node.L; else { dxr = x - rightBreakPoint(node, directrix); if (dxr > epsilon$3) { if (!node.R) { lArc = node; break; } node = node.R; } else { if (dxl > -epsilon$3) { lArc = node.P; rArc = node; } else if (dxr > -epsilon$3) { lArc = node; rArc = node.N; } else { lArc = rArc = node; } break; } } } createCell(site); var newArc = createBeach(site); beaches.insert(lArc, newArc); if (!lArc && !rArc) return; if (lArc === rArc) { detachCircle(lArc); rArc = createBeach(lArc.site); beaches.insert(newArc, rArc); newArc.edge = rArc.edge = createEdge(lArc.site, newArc.site); attachCircle(lArc); attachCircle(rArc); return; } if (!rArc) { // && lArc newArc.edge = createEdge(lArc.site, newArc.site); return; } // else lArc !== rArc detachCircle(lArc); detachCircle(rArc); var lSite = lArc.site, ax = lSite[0], ay = lSite[1], bx = site[0] - ax, by = site[1] - ay, rSite = rArc.site, cx = rSite[0] - ax, cy = rSite[1] - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = [(cy * hb - by * hc) / d + ax, (bx * hc - cx * hb) / d + ay]; setEdgeEnd(rArc.edge, lSite, rSite, vertex); newArc.edge = createEdge(lSite, site, null, vertex); rArc.edge = createEdge(site, rSite, null, vertex); attachCircle(lArc); attachCircle(rArc); } function leftBreakPoint(arc, directrix) { var site = arc.site, rfocx = site[0], rfocy = site[1], pby2 = rfocy - directrix; if (!pby2) return rfocx; var lArc = arc.P; if (!lArc) return -Infinity; site = lArc.site; var lfocx = site[0], lfocy = site[1], plby2 = lfocy - directrix; if (!plby2) return lfocx; var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; return (rfocx + lfocx) / 2; } function rightBreakPoint(arc, directrix) { var rArc = arc.N; if (rArc) return leftBreakPoint(rArc, directrix); var site = arc.site; return site[1] === directrix ? site[0] : Infinity; } var epsilon$3 = 1e-6; var epsilon2$2 = 1e-12; var beaches; var cells; var circles; var edges; function triangleArea(a, b, c) { return (a[0] - c[0]) * (b[1] - a[1]) - (a[0] - b[0]) * (c[1] - a[1]); } function lexicographic(a, b) { return b[1] - a[1] || b[0] - a[0]; } function Diagram(sites, extent) { var site = sites.sort(lexicographic).pop(), x, y, circle; edges = []; cells = new Array(sites.length); beaches = new RedBlackTree; circles = new RedBlackTree; while (true) { circle = firstCircle; if (site && (!circle || site[1] < circle.y || (site[1] === circle.y && site[0] < circle.x))) { if (site[0] !== x || site[1] !== y) { addBeach(site); x = site[0], y = site[1]; } site = sites.pop(); } else if (circle) { removeBeach(circle.arc); } else { break; } } sortCellHalfedges(); if (extent) { var x0 = +extent[0][0], y0 = +extent[0][1], x1 = +extent[1][0], y1 = +extent[1][1]; clipEdges(x0, y0, x1, y1); clipCells(x0, y0, x1, y1); } this.edges = edges; this.cells = cells; beaches = circles = edges = cells = null; } Diagram.prototype = { constructor: Diagram, polygons: function() { var edges = this.edges; return this.cells.map(function(cell) { var polygon = cell.halfedges.map(function(i) { return cellHalfedgeStart(cell, edges[i]); }); polygon.data = cell.site.data; return polygon; }); }, triangles: function() { var triangles = [], edges = this.edges; this.cells.forEach(function(cell, i) { var site = cell.site, halfedges = cell.halfedges, j = -1, m = halfedges.length, s0, e1 = edges[halfedges[m - 1]], s1 = e1.left === site ? e1.right : e1.left; while (++j < m) { s0 = s1; e1 = edges[halfedges[j]]; s1 = e1.left === site ? e1.right : e1.left; if (i < s0.index && i < s1.index && triangleArea(site, s0, s1) < 0) { triangles.push([site.data, s0.data, s1.data]); } } }); return triangles; }, links: function() { return this.edges.filter(function(edge) { return edge.right; }).map(function(edge) { return { source: edge.left.data, target: edge.right.data }; }); } } function voronoi() { var x = x$4, y = y$4, extent = null; function voronoi(data) { return new Diagram(data.map(function(d, i) { var s = [Math.round(x(d, i, data) / epsilon$3) * epsilon$3, Math.round(y(d, i, data) / epsilon$3) * epsilon$3]; s.index = i; s.data = d; return s; }), extent); } voronoi.polygons = function(data) { return voronoi(data).polygons(); }; voronoi.links = function(data) { return voronoi(data).links(); }; voronoi.triangles = function(data) { return voronoi(data).triangles(); }; voronoi.x = function(_) { return arguments.length ? (x = typeof _ === "function" ? _ : constant$9(+_), voronoi) : x; }; voronoi.y = function(_) { return arguments.length ? (y = typeof _ === "function" ? _ : constant$9(+_), voronoi) : y; }; voronoi.extent = function(_) { return arguments.length ? (extent = _ == null ? null : [[+_[0][0], +_[0][1]], [+_[1][0], +_[1][1]]], voronoi) : extent && [[extent[0][0], extent[0][1]], [extent[1][0], extent[1][1]]]; }; voronoi.size = function(_) { return arguments.length ? (extent = _ == null ? null : [[0, 0], [+_[0], +_[1]]], voronoi) : extent && [extent[1][0] - extent[0][0], extent[1][1] - extent[0][1]]; }; return voronoi; } function Voronoi(params) { Transform.call(this, null, params); } var prototype$60 = inherits(Voronoi, Transform); var defaultExtent = [[-1e5, -1e5], [1e5, 1e5]]; prototype$60.transform = function(_, pulse) { var as = _.as || 'path', data = pulse.source, diagram, polygons, i, n; // configure and construct voronoi diagram diagram = voronoi().x(_.x).y(_.y); if (_.size) diagram.size(_.size); else diagram.extent(_.extent || defaultExtent); this.value = (diagram = diagram(data)); // map polygons to paths polygons = diagram.polygons(); for (i=0, n=data.length; i<n; ++i) { data[i][as] = polygons[i] ? 'M' + polygons[i].join('L') + 'Z' : null; } return pulse.reflow(_.modified()).modifies(as); }; var VoronoiDefinition = { "type": "Voronoi", "metadata": {"modifies": true}, "params": [ { "name": "x", "type": "field", "required": true }, { "name": "y", "type": "field", "required": true }, { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "extent", "type": "array", "array": true, "length": 2, "default": [[-1e5, -1e5], [1e5, 1e5]], "content": {"type": "number", "array": true, "length": 2} }, { "name": "as", "type": "string", "default": "path" } ] }; register(VoronoiDefinition, Voronoi); var cloudRadians = Math.PI / 180; var cw = 1 << 11 >> 5; var ch = 1 << 11; function cloud() { var size = [256, 256], text, font, fontSize, fontStyle, fontWeight, rotate, padding, spiral = archimedeanSpiral, words = [], random = Math.random, cloud = {}, canvas = cloudCanvas; cloud.layout = function() { var contextAndRatio = getContext(canvas()), board = zeroArray((size[0] >> 5) * size[1]), bounds = null, n = words.length, i = -1, tags = [], data = words.map(function(d) { return { text: text(d), font: font(d), style: fontStyle(d), weight: fontWeight(d), rotate: rotate(d), size: ~~fontSize(d), padding: padding(d), xoff: 0, yoff: 0, x1: 0, y1: 0, x0: 0, y0: 0, hasText: false, sprite: null, datum: d }; }).sort(function(a, b) { return b.size - a.size; }); while (++i < n) { var d = data[i]; d.x = (size[0] * (random() + .5)) >> 1; d.y = (size[1] * (random() + .5)) >> 1; cloudSprite(contextAndRatio, d, data, i); if (d.hasText && place(board, d, bounds)) { tags.push(d); if (bounds) cloudBounds(bounds, d); else bounds = [{x: d.x + d.x0, y: d.y + d.y0}, {x: d.x + d.x1, y: d.y + d.y1}]; // Temporary hack d.x -= size[0] >> 1; d.y -= size[1] >> 1; } } return tags; } function getContext(canvas) { canvas.width = canvas.height = 1; var ratio = Math.sqrt(canvas.getContext("2d").getImageData(0, 0, 1, 1).data.length >> 2); canvas.width = (cw << 5) / ratio; canvas.height = ch / ratio; var context = canvas.getContext("2d"); context.fillStyle = context.strokeStyle = "red"; context.textAlign = "center"; return {context: context, ratio: ratio}; } function place(board, tag, bounds) { var startX = tag.x, startY = tag.y, maxDelta = Math.sqrt(size[0] * size[0] + size[1] * size[1]), s = spiral(size), dt = random() < .5 ? 1 : -1, t = -dt, dxdy, dx, dy; while (dxdy = s(t += dt)) { dx = ~~dxdy[0]; dy = ~~dxdy[1]; if (Math.min(Math.abs(dx), Math.abs(dy)) >= maxDelta) break; tag.x = startX + dx; tag.y = startY + dy; if (tag.x + tag.x0 < 0 || tag.y + tag.y0 < 0 || tag.x + tag.x1 > size[0] || tag.y + tag.y1 > size[1]) continue; // TODO only check for collisions within current bounds. if (!bounds || !cloudCollide(tag, board, size[0])) { if (!bounds || collideRects(tag, bounds)) { var sprite = tag.sprite, w = tag.width >> 5, sw = size[0] >> 5, lx = tag.x - (w << 4), sx = lx & 0x7f, msx = 32 - sx, h = tag.y1 - tag.y0, x = (tag.y + tag.y0) * sw + (lx >> 5), last; for (var j = 0; j < h; j++) { last = 0; for (var i = 0; i <= w; i++) { board[x + i] |= (last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0); } x += sw; } tag.sprite = null; return true; } } } return false; } cloud.words = function(_) { return arguments.length ? (words = _, cloud) : words; }; cloud.size = function(_) { return arguments.length ? (size = [+_[0], +_[1]], cloud) : size; }; cloud.font = function(_) { return arguments.length ? (font = functor(_), cloud) : font; }; cloud.fontStyle = function(_) { return arguments.length ? (fontStyle = functor(_), cloud) : fontStyle; }; cloud.fontWeight = function(_) { return arguments.length ? (fontWeight = functor(_), cloud) : fontWeight; }; cloud.rotate = function(_) { return arguments.length ? (rotate = functor(_), cloud) : rotate; }; cloud.text = function(_) { return arguments.length ? (text = functor(_), cloud) : text; }; cloud.spiral = function(_) { return arguments.length ? (spiral = spirals[_] || _, cloud) : spiral; }; cloud.fontSize = function(_) { return arguments.length ? (fontSize = functor(_), cloud) : fontSize; }; cloud.padding = function(_) { return arguments.length ? (padding = functor(_), cloud) : padding; }; cloud.random = function(_) { return arguments.length ? (random = _, cloud) : random; }; return cloud; } // Fetches a monochrome sprite bitmap for the specified text. // Load in batches for speed. function cloudSprite(contextAndRatio, d, data, di) { if (d.sprite) return; var c = contextAndRatio.context, ratio = contextAndRatio.ratio; c.clearRect(0, 0, (cw << 5) / ratio, ch / ratio); var x = 0, y = 0, maxh = 0, n = data.length, w, w32, h, i, j; --di; while (++di < n) { d = data[di]; c.save(); c.font = d.style + " " + d.weight + " " + ~~((d.size + 1) / ratio) + "px " + d.font; w = c.measureText(d.text + "m").width * ratio; h = d.size << 1; if (d.rotate) { var sr = Math.sin(d.rotate * cloudRadians), cr = Math.cos(d.rotate * cloudRadians), wcr = w * cr, wsr = w * sr, hcr = h * cr, hsr = h * sr; w = (Math.max(Math.abs(wcr + hsr), Math.abs(wcr - hsr)) + 0x1f) >> 5 << 5; h = ~~Math.max(Math.abs(wsr + hcr), Math.abs(wsr - hcr)); } else { w = (w + 0x1f) >> 5 << 5; } if (h > maxh) maxh = h; if (x + w >= (cw << 5)) { x = 0; y += maxh; maxh = 0; } if (y + h >= ch) break; c.translate((x + (w >> 1)) / ratio, (y + (h >> 1)) / ratio); if (d.rotate) c.rotate(d.rotate * cloudRadians); c.fillText(d.text, 0, 0); if (d.padding) c.lineWidth = 2 * d.padding, c.strokeText(d.text, 0, 0); c.restore(); d.width = w; d.height = h; d.xoff = x; d.yoff = y; d.x1 = w >> 1; d.y1 = h >> 1; d.x0 = -d.x1; d.y0 = -d.y1; d.hasText = true; x += w; } var pixels = c.getImageData(0, 0, (cw << 5) / ratio, ch / ratio).data, sprite = []; while (--di >= 0) { d = data[di]; if (!d.hasText) continue; w = d.width; w32 = w >> 5; h = d.y1 - d.y0; // Zero the buffer for (i = 0; i < h * w32; i++) sprite[i] = 0; x = d.xoff; if (x == null) return; y = d.yoff; var seen = 0, seenRow = -1; for (j = 0; j < h; j++) { for (i = 0; i < w; i++) { var k = w32 * j + (i >> 5), m = pixels[((y + j) * (cw << 5) + (x + i)) << 2] ? 1 << (31 - (i % 32)) : 0; sprite[k] |= m; seen |= m; } if (seen) seenRow = j; else { d.y0++; h--; j--; y++; } } d.y1 = d.y0 + seenRow; d.sprite = sprite.slice(0, (d.y1 - d.y0) * w32); } } // Use mask-based collision detection. function cloudCollide(tag, board, sw) { sw >>= 5; var sprite = tag.sprite, w = tag.width >> 5, lx = tag.x - (w << 4), sx = lx & 0x7f, msx = 32 - sx, h = tag.y1 - tag.y0, x = (tag.y + tag.y0) * sw + (lx >> 5), last; for (var j = 0; j < h; j++) { last = 0; for (var i = 0; i <= w; i++) { if (((last << msx) | (i < w ? (last = sprite[j * w + i]) >>> sx : 0)) & board[x + i]) return true; } x += sw; } return false; } function cloudBounds(bounds, d) { var b0 = bounds[0], b1 = bounds[1]; if (d.x + d.x0 < b0.x) b0.x = d.x + d.x0; if (d.y + d.y0 < b0.y) b0.y = d.y + d.y0; if (d.x + d.x1 > b1.x) b1.x = d.x + d.x1; if (d.y + d.y1 > b1.y) b1.y = d.y + d.y1; } function collideRects(a, b) { return a.x + a.x1 > b[0].x && a.x + a.x0 < b[1].x && a.y + a.y1 > b[0].y && a.y + a.y0 < b[1].y; } function archimedeanSpiral(size) { var e = size[0] / size[1]; return function(t) { return [e * (t *= .1) * Math.cos(t), t * Math.sin(t)]; }; } function rectangularSpiral(size) { var dy = 4, dx = dy * size[0] / size[1], x = 0, y = 0; return function(t) { var sign = t < 0 ? -1 : 1; // See triangular numbers: T_n = n * (n + 1) / 2. switch ((Math.sqrt(1 + 4 * sign * t) - sign) & 3) { case 0: x += dx; break; case 1: y += dy; break; case 2: x -= dx; break; default: y -= dy; break; } return [x, y]; }; } // TODO reuse arrays? function zeroArray(n) { var a = [], i = -1; while (++i < n) a[i] = 0; return a; } function cloudCanvas() { try { return typeof document !== 'undefined' && document.createElement ? document.createElement('canvas') : new (require('canvas'))(); } catch (e) { error('Canvas unavailable. Run in browser or install node-canvas.'); } } function functor(d) { return typeof d === "function" ? d : function() { return d; }; } var spirals = { archimedean: archimedeanSpiral, rectangular: rectangularSpiral }; var output = ['x', 'y', 'font', 'fontSize', 'fontStyle', 'fontWeight', 'angle']; function Wordcloud(params) { Transform.call(this, cloud(), params); } var prototype$61 = inherits(Wordcloud, Transform); prototype$61.transform = function(_, pulse) { var mod = _.modified(), run = mod || pulse.changed(pulse.ADD_REM) || isFunction(_.text) && pulse.modified(_.text.fields) || isFunction(_.font) && pulse.modified(_.font.fields) || isFunction(_.rotate) && pulse.modified(_.rotate.fields) || isFunction(_.fontSize) && pulse.modified(_.fontSize.fields) || isFunction(_.fontStyle) && pulse.modified(_.fontStyle.fields) || isFunction(_.fontWeight) && pulse.modified(_.fontWeight.fields); if (!run) return; var layout = this.value, as = _.as || output, fontSize = _.fontSize || 14, range, fsize, sizeScale, words; isFunction(fontSize) ? (range = _.fontSizeRange) : (fontSize = constant$1(fontSize)); // create font size scaling function as needed if (range) { fsize = fontSize; sizeScale = scale$1('sqrt')().domain(extent$2(fsize, pulse)).range(range); fontSize = function(x) { return sizeScale(fsize(x)); }; } var data = pulse.materialize(pulse.SOURCE).source; data.forEach(function(t) { t[as[0]] = NaN; t[as[1]] = NaN; t[as[3]] = 0; }); // configure layout words = layout .words(data) .text(_.text) .size(_.size || [500, 500]) .padding(_.padding || 1) .spiral(_.spiral || 'archimedean') .rotate(_.rotate || 0) .font(_.font || 'sans-serif') .fontStyle(_.fontStyle || 'normal') .fontWeight(_.fontWeight || 'normal') .fontSize(fontSize) .layout(); var size = layout.size(), dx = size[0] >> 1, dy = size[1] >> 1, i = 0, n = words.length, w, t; for (; i<n; ++i) { w = words[i]; t = w.datum; t[as[0]] = w.x + dx; t[as[1]] = w.y + dy; t[as[2]] = w.font; t[as[3]] = w.size; t[as[4]] = w.style; t[as[5]] = w.weight; t[as[6]] = w.rotate; } return pulse.reflow(mod).modifies(as); }; function extent$2(size, pulse) { var e = new transforms.Extent(); e.transform({field: size, modified: truthy}, pulse); return e.value; } var WordcloudDefinition = { "type": "Wordcloud", "metadata": {"modifies": true}, "params": [ { "name": "size", "type": "number", "array": true, "length": 2 }, { "name": "font", "type": "string", "expr": true, "default": "sans-serif" }, { "name": "fontStyle", "type": "string", "expr": true, "default": "normal" }, { "name": "fontWeight", "type": "string", "expr": true, "default": "normal" }, { "name": "fontSize", "type": "number", "expr": true, "default": 14 }, { "name": "fontSizeRange", "type": "number", "array": true, "null": true, "default": [10, 50] }, { "name": "rotate", "type": "number", "expr": true, "default": 0 }, { "name": "text", "type": "field" }, { "name": "spiral", "type": "string", "values": ["archimedean", "rectangular"] }, { "name": "padding", "type": "number", "expr": true }, { "name": "as", "type": "string", "array": true, "length": 7, "default": ["x", "y", "font", "fontSize", "fontStyle", "fontWeight", "angle"] } ] }; register(WordcloudDefinition, Wordcloud); function array8(n) { return new Uint8Array(n); } function array16(n) { return new Uint16Array(n); } function array32(n) { return new Uint32Array(n); } /** * Maintains CrossFilter state. */ function Bitmaps() { var width = 8, data = [], seen = array32(0), curr = array$4(0, width), prev = array$4(0, width); return { data: function() { return data; }, seen: function() { return (seen = lengthen(seen, data.length)); }, add: function(array) { for (var i=0, j=data.length, n=array.length, t; i<n; ++i) { t = array[i]; t._index = j++; data.push(t); } }, remove: function(num, map) { // map: index -> boolean (true => remove) var n = data.length, copy = Array(n - num), reindex = data, // reuse old data array for index map t, i, j; // seek forward to first removal for (i=0; !map[i] && i<n; ++i) { copy[i] = data[i]; reindex[i] = i; } // condense arrays for (j=i; i<n; ++i) { t = data[i]; if (!map[i]) { reindex[i] = j; curr[j] = curr[i]; prev[j] = prev[i]; copy[j] = t; t._index = j++; } else { reindex[i] = -1; } curr[i] = 0; // clear unused bits } return (data = copy, reindex); }, size: function() { return data.length; }, curr: function() { return curr; }, prev: function() { return prev; }, reset: function(k) { prev[k] = curr[k]; }, all: function() { return width < 0x101 ? 0xff : width < 0x10001 ? 0xffff : 0xffffffff; }, set: function(k, one) { curr[k] |= one; }, clear: function(k, one) { curr[k] &= ~one; }, resize: function(n, m) { var k = curr.length; if (n > k || m > width) { width = Math.max(m, width); curr = array$4(n, width, curr); prev = array$4(n, width); } } }; } function lengthen(array, length, copy) { if (array.length >= length) return array; copy = copy || new array.constructor(length); copy.set(array); return copy; } function array$4(n, m, array) { var copy = (m < 0x101 ? array8 : m < 0x10001 ? array16 : array32)(n); if (array) copy.set(array); return copy; } function Dimension(index, i, query) { var bit = (1 << i); return { one: bit, zero: ~bit, range: query.slice(), bisect: index.bisect, index: index.index, size: index.size, onAdd: function(added, curr) { var dim = this, range = dim.bisect(dim.range, added.value), idx = added.index, lo = range[0], hi = range[1], n1 = idx.length, i; for (i=0; i<lo; ++i) curr[idx[i]] |= bit; for (i=hi; i<n1; ++i) curr[idx[i]] |= bit; return dim; } }; } /** * Maintains a list of values, sorted by key. */ function SortedIndex() { var index = array32(0), value = [], size = 0; function insert(key, data, base) { if (!data.length) return []; var n0 = size, n1 = data.length, addv = Array(n1), addi = array32(n1), oldv, oldi, i; for (i=0; i<n1; ++i) { addv[i] = key(data[i]); addi[i] = i; } addv = sort(addv, addi); if (n0) { oldv = value; oldi = index; value = Array(n0 + n1); index = array32(n0 + n1); merge$3(base, oldv, oldi, n0, addv, addi, n1, value, index); } else { if (base > 0) for (i=0; i<n1; ++i) { addi[i] += base; } value = addv; index = addi; } size = n0 + n1; return {index: addi, value: addv}; } function remove(num, map) { // map: index -> remove var n = size, idx, i, j; // seek forward to first removal for (i=0; !map[index[i]] && i<n; ++i); // condense index and value arrays for (j=i; i<n; ++i) { if (!map[idx=index[i]]) { index[j] = idx; value[j] = value[i]; ++j; } } size = n - num; } function reindex(map) { for (var i=0, n=size; i<n; ++i) { index[i] = map[index[i]]; } } function bisect(range, array) { var n = array ? array.length : (array = value, size); return [ bisectLeft(array, range[0], 0, n), bisectRight(array, range[1], 0, n) ]; } return { insert: insert, remove: remove, bisect: bisect, reindex: reindex, index: function() { return index; }, size: function() { return size; } }; } function sort(values, index) { values.sort.call(index, function(a, b) { var x = values[a], y = values[b]; return x < y ? -1 : x > y ? 1 : 0; }); return permute(values, index); } function merge$3(base, value0, index0, n0, value1, index1, n1, value, index) { var i0 = 0, i1 = 0, i; for (i=0; i0 < n0 && i1 < n1; ++i) { if (value0[i0] < value1[i1]) { value[i] = value0[i0]; index[i] = index0[i0++]; } else { value[i] = value1[i1]; index[i] = index1[i1++] + base; } } for (; i0 < n0; ++i0, ++i) { value[i] = value0[i0]; index[i] = index0[i0]; } for (; i1 < n1; ++i1, ++i) { value[i] = value1[i1]; index[i] = index1[i1] + base; } } /** * An indexed multi-dimensional filter. * @constructor * @param {object} params - The parameters for this operator. * @param {Array<function(object): *>} params.fields - An array of dimension accessors to filter. * @param {Array} params.query - An array of per-dimension range queries. */ function CrossFilter(params) { Transform.call(this, Bitmaps(), params); this._indices = null; this._dims = null; } var prototype$62 = inherits(CrossFilter, Transform); prototype$62.transform = function(_, pulse) { if (!this._dims) { return this.init(_, pulse); } else { var init = _.modified('fields') || _.fields.some(function(f) { return pulse.modified(f.fields); }); return init ? this.reinit(_, pulse) : this.eval(_, pulse); } }; prototype$62.init = function(_, pulse) { var fields = _.fields, query = _.query, indices = this._indices = {}, dims = this._dims = [], m = query.length, i = 0, key, index; // instantiate indices and dimensions for (; i<m; ++i) { key = fields[i].fname; index = indices[key] || (indices[key] = SortedIndex()); dims.push(Dimension(index, i, query[i])); } return this.eval(_, pulse); }; prototype$62.reinit = function(_, pulse) { var output = pulse.materialize().fork(), fields = _.fields, query = _.query, indices = this._indices, dims = this._dims, bits = this.value, curr = bits.curr(), prev = bits.prev(), all = bits.all(), out = (output.rem = output.add), mod = output.mod, m = query.length, adds = {}, add, index, key, mods, remMap, modMap, i, n, f; // set prev to current state prev.set(curr); // if pulse has remove tuples, process them first if (pulse.rem.length) { remMap = this.remove(_, pulse, output); } // if pulse has added tuples, add them to state if (pulse.add.length) { bits.add(pulse.add); } // if pulse has modified tuples, create an index map if (pulse.mod.length) { modMap = {}; for (mods=pulse.mod, i=0, n=mods.length; i<n; ++i) { modMap[mods[i]._index] = 1; } } // re-initialize indices as needed, update curr bitmap for (i=0; i<m; ++i) { f = fields[i]; if (!dims[i] || _.modified('fields', i) || pulse.modified(f.fields)) { key = f.fname; if (!(add = adds[key])) { indices[key] = index = SortedIndex(); adds[key] = add = index.insert(f, pulse.source, 0); } dims[i] = Dimension(index, i, query[i]).onAdd(add, curr); } } // visit each tuple // if filter state changed, push index to add/rem // else if in mod and passes a filter, push index to mod for (i=0, n=bits.data().length; i<n; ++i) { if (remMap[i]) { // skip if removed tuple continue; } else if (prev[i] !== curr[i]) { // add if state changed out.push(i); } else if (modMap[i] && curr[i] !== all) { // otherwise, pass mods through mod.push(i); } } bits.mask = (1 << m) - 1; return output; }; prototype$62.eval = function(_, pulse) { var output = pulse.materialize().fork(), m = this._dims.length, mask = 0; if (pulse.rem.length) { this.remove(_, pulse, output); mask |= (1 << m) - 1; } if (_.modified('query') && !_.modified('fields')) { mask |= this.update(_, pulse, output); } if (pulse.add.length) { this.insert(_, pulse, output); mask |= (1 << m) - 1; } if (pulse.mod.length) { this.modify(pulse, output); mask |= (1 << m) - 1; } this.value.mask = mask; return output; }; prototype$62.insert = function(_, pulse, output) { var tuples = pulse.add, bits = this.value, dims = this._dims, indices = this._indices, fields = _.fields, adds = {}, out = output.add, k = bits.size(), n = k + tuples.length, m = dims.length, j, key, add; // resize bitmaps and add tuples as needed bits.resize(n, m); bits.add(tuples); var curr = bits.curr(), prev = bits.prev(), all = bits.all(); // add to dimensional indices for (j=0; j<m; ++j) { key = fields[j].fname; add = adds[key] || (adds[key] = indices[key].insert(fields[j], tuples, k)); dims[j].onAdd(add, curr); } // set previous filters, output if passes at least one filter for (; k<n; ++k) { prev[k] = all; if (curr[k] !== all) out.push(k); } }; prototype$62.modify = function(pulse, output) { var out = output.mod, bits = this.value, curr = bits.curr(), all = bits.all(), tuples = pulse.mod, i, n, k; for (i=0, n=tuples.length; i<n; ++i) { k = tuples[i]._index; if (curr[k] !== all) out.push(k); } }; prototype$62.remove = function(_, pulse, output) { var indices = this._indices, bits = this.value, curr = bits.curr(), prev = bits.prev(), all = bits.all(), map = {}, out = output.rem, tuples = pulse.rem, i, n, k, f; // process tuples, output if passes at least one filter for (i=0, n=tuples.length; i<n; ++i) { k = tuples[i]._index; map[k] = 1; // build index map prev[k] = (f = curr[k]); curr[k] = all; if (f !== all) out.push(k); } // remove from dimensional indices for (k in indices) { indices[k].remove(n, map); } return (this.reindex(pulse, n, map), map); }; // reindex filters and indices after propagation completes prototype$62.reindex = function(pulse, num, map) { var indices = this._indices, bits = this.value; pulse.runAfter(function() { var indexMap = bits.remove(num, map); for (var key in indices) indices[key].reindex(indexMap); }); }; prototype$62.update = function(_, pulse, output) { var dims = this._dims, query = _.query, stamp = pulse.stamp, m = dims.length, mask = 0, i, q; // survey how many queries have changed output.filters = 0; for (q=0; q<m; ++q) { if (_.modified('query', q)) { i = q; ++mask; } } if (mask === 1) { // only one query changed, use more efficient update mask = dims[i].one; this.incrementOne(dims[i], query[i], output.add, output.rem); } else { // multiple queries changed, perform full record keeping for (q=0, mask=0; q<m; ++q) { if (!_.modified('query', q)) continue; mask |= dims[q].one; this.incrementAll(dims[q], query[q], stamp, output.add); output.rem = output.add; // duplicate add/rem for downstream resolve } } return mask; }; prototype$62.incrementAll = function(dim, query, stamp, out) { var bits = this.value, seen = bits.seen(), curr = bits.curr(), prev = bits.prev(), index = dim.index(), old = dim.bisect(dim.range), range = dim.bisect(query), lo1 = range[0], hi1 = range[1], lo0 = old[0], hi0 = old[1], one = dim.one, i, j, k; // Fast incremental update based on previous lo index. if (lo1 < lo0) { for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) { k = index[i]; if (seen[k] !== stamp) { prev[k] = curr[k]; seen[k] = stamp; out.push(k); } curr[k] ^= one; } } else if (lo1 > lo0) { for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) { k = index[i]; if (seen[k] !== stamp) { prev[k] = curr[k]; seen[k] = stamp; out.push(k); } curr[k] ^= one; } } // Fast incremental update based on previous hi index. if (hi1 > hi0) { for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) { k = index[i]; if (seen[k] !== stamp) { prev[k] = curr[k]; seen[k] = stamp; out.push(k); } curr[k] ^= one; } } else if (hi1 < hi0) { for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) { k = index[i]; if (seen[k] !== stamp) { prev[k] = curr[k]; seen[k] = stamp; out.push(k); } curr[k] ^= one; } } dim.range = query.slice(); }; prototype$62.incrementOne = function(dim, query, add, rem) { var bits = this.value, curr = bits.curr(), index = dim.index(), old = dim.bisect(dim.range), range = dim.bisect(query), lo1 = range[0], hi1 = range[1], lo0 = old[0], hi0 = old[1], one = dim.one, i, j, k; // Fast incremental update based on previous lo index. if (lo1 < lo0) { for (i = lo1, j = Math.min(lo0, hi1); i < j; ++i) { k = index[i]; curr[k] ^= one; add.push(k); } } else if (lo1 > lo0) { for (i = lo0, j = Math.min(lo1, hi0); i < j; ++i) { k = index[i]; curr[k] ^= one; rem.push(k); } } // Fast incremental update based on previous hi index. if (hi1 > hi0) { for (i = Math.max(lo1, hi0), j = hi1; i < j; ++i) { k = index[i]; curr[k] ^= one; add.push(k); } } else if (hi1 < hi0) { for (i = Math.max(lo0, hi1), j = hi0; i < j; ++i) { k = index[i]; curr[k] ^= one; rem.push(k); } } dim.range = query.slice(); }; var CrossFilterDefinition = { "type": "CrossFilter", "metadata": {}, "params": [ { "name": "fields", "type": "field", "array": true, "required": true }, { "name": "query", "type": "array", "array": true, "required": true, "content": {"type": "number", "array": true, "length": 2} } ] }; /** * Selectively filters tuples by resolving against a filter bitmap. * Useful for processing the output of a cross-filter transform. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.ignore - A bit mask indicating which filters to ignore. * @param {object} params.filter - The per-tuple filter bitmaps. Typically this * parameter value is a reference to a {@link CrossFilter} transform. */ function ResolveFilter(params) { Transform.call(this, null, params); } var prototype$63 = inherits(ResolveFilter, Transform); prototype$63.transform = function(_, pulse) { var ignore = ~(_.ignore || 0), // bit mask where zeros -> dims to ignore bitmap = _.filter, mask = bitmap.mask; // exit early if no relevant filter changes if ((mask & ignore) === 0) return pulse.StopPropagation; var output = pulse.fork(pulse.ALL), data = bitmap.data(), curr = bitmap.curr(), prev = bitmap.prev(), pass = function(k) { return !(curr[k] & ignore) ? data[k] : null; }; // propagate all mod tuples that pass the filter output.filter(output.MOD, pass); // determine add & rem tuples via filter functions // for efficiency, we do *not* populate new arrays, // instead we add filter functions applied downstream if (!(mask & (mask-1))) { // only one filter changed output.filter(output.ADD, pass); output.filter(output.REM, function(k) { return (curr[k] & ignore) === mask ? data[k] : null; }); } else { // multiple filters changed output.filter(output.ADD, function(k) { var c = curr[k] & ignore, f = !c && (c ^ (prev[k] & ignore)); return f ? data[k] : null; }); output.filter(output.REM, function(k) { var c = curr[k] & ignore, f = c && !(c ^ (c ^ (prev[k] & ignore))); return f ? data[k] : null; }); } // add filter to source data in case of reflow... return output.filter(output.SOURCE, function(t) { return pass(t._index); }); }; var ResolveFilterDefinition = { "type": "ResolveFilter", "metadata": {}, "params": [ { "name": "ignore", "type": "number", "required": true, "description": "A bit mask indicating which filters to ignore." }, { "name": "filter", "type": "object", "required": true, "description": "Per-tuple filter bitmaps from a CrossFilter transform." } ] }; register(CrossFilterDefinition, CrossFilter); register(ResolveFilterDefinition, ResolveFilter); /** * Calculate bounding boxes for scenegraph items. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.mark - The scenegraph mark instance to bound. */ function Bound(params) { Transform.call(this, null, params); } var prototype$64 = inherits(Bound, Transform); prototype$64.transform = function(_, pulse) { var mark = _.mark, type = Marks[mark.marktype], bound = type.bound, markBounds = mark.bounds, rebound; mark.bounds_prev.clear().union(markBounds); if (type.nested) { // multi-item marks have a single bounds instance boundItem$1(mark, bound); } else if (_.modified()) { // operator parameters modified -> re-bound all items // updates group bounds in response to modified group content markBounds.clear(); mark.items.forEach(function(item) { markBounds.union(boundItem$1(item, bound)); }); } else { // incrementally update bounds, re-bound mark as needed rebound = pulse.changed(pulse.REM); pulse.visit(pulse.ADD, function(item) { markBounds.union(boundItem$1(item, bound)); }); pulse.visit(pulse.MOD, function(item) { rebound = rebound || markBounds.alignsWith(item.bounds); markBounds.union(boundItem$1(item, bound)); }); if (rebound) { markBounds.clear(); mark.items.forEach(function(item) { markBounds.union(item.bounds); }); } } return pulse.modifies('bounds'); }; function boundItem$1(item, bound, opt) { item.bounds_prev.clear().union(item.bounds); return bound(item.bounds.clear(), item, opt); } /** * Bind scenegraph items to a scenegraph mark instance. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.markdef - The mark definition for creating the mark. * This is an object of legal scenegraph mark properties which *must* include * the 'marktype' property. * @param {Array<number>} params.scenepath - Scenegraph tree coordinates for the mark. * The path is an array of integers, each indicating the index into * a successive chain of items arrays. */ function Mark(params) { Transform.call(this, null, params); } var prototype$65 = inherits(Mark, Transform); prototype$65.transform = function(_, pulse) { var mark = this.value, group, context; // acquire mark on first invocation, bind context and group if (!mark) { mark = pulse.dataflow.scenegraph().mark(_.scenepath, _.markdef); mark.source = this; this.value = mark; context = _.scenepath.context; group = mark.group; group.context = context; if (!context.group) context.group = group; } // initialize entering items var Init = mark.marktype === 'group' ? GroupItem : Item; pulse.visit(pulse.ADD, function(item) { Init.call(item, mark); }); // bind items array to scenegraph mark return (mark.items = pulse.source, pulse); }; /** * Queue modified scenegraph items for rendering. * @constructor */ function Render(params) { Transform.call(this, null, params); } var prototype$66 = inherits(Render, Transform); prototype$66.transform = function(_, pulse) { var view = pulse.dataflow; if (pulse.changed(pulse.REM)) { view.enqueue(pulse.materialize(pulse.REM).rem); } if (pulse.changed(pulse.ADD)) { view.enqueue(pulse.materialize(pulse.ADD).add); } if (pulse.changed(pulse.MOD)) { view.enqueue(pulse.materialize(pulse.MOD).mod); } // set z-index dirty flag as needed if (pulse.fields && pulse.fields['zindex']) { var item = pulse.source && pulse.source[0]; if (item) item.mark.zdirty = true; } }; var Fit = 'fit'; var Pad = 'pad'; var None$1 = 'none'; var AxisRole = 'axis'; var FrameRole = 'frame'; var LegendRole = 'legend'; var ScopeRole = 'scope'; /** * Layout view elements such as axes and legends. * Also performs size adjustments. * @constructor * @param {object} params - The parameters for this operator. * @param {object} params.mark - Scenegraph mark of groups to layout. */ function ViewLayout(params) { Transform.call(this, null, params); } var prototype$67 = inherits(ViewLayout, Transform); prototype$67.transform = function(_, pulse) { // TODO incremental update, output? var view = pulse.dataflow; _.mark.items.forEach(function(group) { layoutGroup(view, group, _); }); return pulse; }; function layoutGroup(view, group, _) { var items = group.items, width = Math.max(0, group.width || 0), height = Math.max(0, group.height || 0), viewBounds = new Bounds().set(0, 0, width, height), markBounds = viewBounds.clone(), axisBounds = markBounds.clone(), legends = [], mark, flow, b, i, n; // layout axes, gather legends, collect bounds for (i=0, n=items.length; i<n; ++i) { mark = items[i]; switch (mark.role) { case AxisRole: axisBounds.union(layoutAxis(mark, width, height)); break; case LegendRole: legends.push(mark); break; case FrameRole: case ScopeRole: viewBounds.union(mark.bounds); // break omitted default: markBounds.union(mark.bounds); } } viewBounds.union(axisBounds); // layout legends, extending viewBounds if (legends.length) { flow = {left: 0, right: 0, margin: _.legendMargin || 8}; axisBounds.union(markBounds); for (i=0, n=legends.length; i<n; ++i) { b = layoutLegend(legends[i], flow, axisBounds, width, height); (_.autosize === Fit) ? viewBounds.add(b.x1, 0).add(b.x2, 0) : viewBounds.union(b); } } // perform size adjustment layoutSize(view, group, markBounds, viewBounds.union(markBounds), _); } function axisIndices(datum) { var index = +datum.grid; return [ datum.tick ? index++ : -1, // tick index datum.label ? index++ : -1, // label index index + (+datum.domain) // title index ]; } function layoutAxis(axis, width, height) { var item = axis.items[0], datum = item.datum, orient = datum.orient, indices = axisIndices(datum), range = item.range, offset = item.offset, position = item.position, minExtent = item.minExtent, maxExtent = item.maxExtent, title = datum.title && item.items[indices[2]].items[0], titlePadding = item.titlePadding, titleSize = title ? title.fontSize + titlePadding : 0, bounds = item.bounds, x = 0, y = 0, i, s; bounds.clear(); if ((i=indices[0]) > -1) bounds.union(item.items[i].bounds); if ((i=indices[1]) > -1) bounds.union(item.items[i].bounds); // position axis group and title switch (orient) { case 'top': { x = position || 0; y = -offset; s = Math.max(minExtent, Math.min(maxExtent, -bounds.y1)); if (title) title.auto ? (title.y = -(titlePadding + s), s += titleSize) : bounds.union(title.bounds); bounds.add(0, -s).add(range, 0); break; } case 'left': { x = -offset; y = position || 0; s = Math.max(minExtent, Math.min(maxExtent, -bounds.x1)); if (title) title.auto ? (title.x = -(titlePadding + s), s += titleSize) : bounds.union(title.bounds); bounds.add(-s, 0).add(0, range); break; } case 'right': { x = width + offset; y = position || 0; s = Math.max(minExtent, Math.min(maxExtent, bounds.x2)); if (title) title.auto ? (title.x = titlePadding + s, s += titleSize) : bounds.union(title.bounds); bounds.add(0, 0).add(s, range); break; } case 'bottom': { x = position || 0; y = height + offset; s = Math.max(minExtent, Math.min(maxExtent, bounds.y2)); if (title) title.auto ? (title.y = titlePadding + s, s += titleSize) : bounds.union(title.bounds); bounds.add(0, 0).add(range, s); break; } } item.x = x + 0.5; item.y = y + 0.5; // update bounds boundStroke(bounds.translate(x, y), item); item.mark.bounds.clear().union(bounds); return bounds; } function layoutLegend(legend, flow, axisBounds, width, height) { var item = legend.items[0], datum = item.datum, orient = datum.orient, offset = item.offset, bounds = item.bounds.clear(), x = 0, y = (flow[orient] || 0), w, h; // aggregate bounds to determine size // shave off 1 pixel because it looks better... item.items.forEach(function(_) { bounds.union(_.bounds); }); w = Math.round(bounds.width()) + 2 * item.padding - 1; h = Math.round(bounds.height()) + 2 * item.padding - 1; switch (orient) { case 'left': x -= w + offset - Math.floor(axisBounds.x1); flow.left += h + flow.margin; break; case 'right': x += offset + Math.ceil(axisBounds.x2); flow.right += h + flow.margin; break; case 'top-left': x += offset; y += offset; break; case 'top-right': x += width - w - offset; y += offset; break; case 'bottom-left': x += offset; y += height - h - offset; break; case 'bottom-right': x += width - w - offset; y += height - h - offset; break; } // update legend layout item.x = x; item.y = y; item.width = w; item.height = h; // update bounds boundStroke(bounds.set(x, y, x + w, y + h), item); item.mark.bounds.clear().union(bounds); return bounds; } function layoutSize(view, group, markBounds, viewBounds, _) { var type = _.autosize, viewWidth = view._width, viewHeight = view._height; if (view._autosize < 1 || !type) return; var width = Math.max(0, group.width || 0), left = Math.max(0, Math.ceil(-viewBounds.x1)), right = Math.max(0, Math.ceil(viewBounds.x2 - width)), height = Math.max(0, group.height || 0), top = Math.max(0, Math.ceil(-viewBounds.y1)), bottom = Math.max(0, Math.ceil(viewBounds.y2 - height)); if (type === None$1) { viewWidth = width; viewHeight = height; left = 0; top = 0; } else if (type === Fit) { width = Math.max(0, viewWidth - left - right); height = Math.max(0, viewHeight - top - bottom); } else if (type === Pad) { viewWidth = width + left + right; viewHeight = height + top + bottom; if (group.width < 0) width = markBounds.width(); if (group.height < 0) height = markBounds.height(); } view.autosize(viewWidth, viewHeight, width, height, [left, top]); } var BindClass = 'vega-bind'; var NameClass = 'vega-bind-name'; var RadioClass = 'vega-bind-radio'; var OptionClass = 'vega-option-'; /** * Bind a signal to an external HTML input element. The resulting two-way * binding will propagate input changes to signals, and propagate signal * changes to the input element state. If this view instance has no parent * element, we assume the view is headless and no bindings are created. * @param {Element|string} el - The parent DOM element to which the input * element should be appended as a child. If string-valued, this argument * will be treated as a CSS selector. If null or undefined, the parent * element of this view will be used as the element. * @param {object} param - The binding parameters which specify the signal * to bind to, the input element type, and type-specific configuration. * @return {View} - This view instance. */ function bind$1(el, param) { if (this._el) bind$2(this, el || this._el, param); else this.warn('Bind not supported for headless views.'); return this; } function bind$2(view, el, param) { var bind = { elements: null, set: null, update: function(value) { view.signal(param.signal, value).run(); } }; if (isString(el)) el = document.querySelector(el); generate(bind, el, param, view.signal(param.signal)); view.on(view._signals[param.signal], null, function() { bind.set(view.signal(param.signal)); }); return bind; } /** * Generate an HTML input form element and bind it to a signal. */ function generate(bind, el, param, value) { var div = element$1('div', {'class': BindClass}); div.appendChild(element$1('span', {'class': NameClass}, (param.name || param.signal) )); el.appendChild(div); var input = form; switch (param.type) { case 'checkbox': input = checkbox; break; case 'select': input = select; break; case 'radio': input = radio; break; case 'range': input = range$2; break; } input(bind, div, param, value); } /** * Generates an arbitrary input form element. * The input type is controlled via user-provided parameters. */ function form(bind, el, param, value) { var node = element$1('input'); for (var key in param) if (key !== 'signal' && key !== 'element') { node.setAttribute(key, param[key]); } node.setAttribute('name', param.signal); node.setAttribute('value', value); el.appendChild(node); node.addEventListener('input', function() { bind.update(node.value); }); bind.elements = [node]; bind.set = function(value) { node.value = value; }; } /** * Generates a checkbox input element. */ function checkbox(bind, el, param, value) { var attr = {type: 'checkbox', name: param.signal}; if (value) attr.checked = true; var node = element$1('input', attr); el.appendChild(node); node.addEventListener('change', function() { bind.update(node.checked); }); bind.elements = [node]; bind.set = function(value) { node.checked = !!value || null; } } /** * Generates a selection list input element. */ function select(bind, el, param, value) { var node = element$1('select', {name: param.signal}); param.options.forEach(function(option) { var attr = {value: option}; if (option === value) attr.selected = true; node.appendChild(element$1('option', attr, option)); }); el.appendChild(node); node.addEventListener('change', function() { bind.update(param.options[node.selectedIndex]); }); bind.elements = [node]; bind.set = function(value) { node.selectedIndex = param.options.indexOf(value); }; } /** * Generates a radio button group. */ function radio(bind, el, param, value) { var group = element$1('span', {'class': RadioClass}); el.appendChild(group); bind.elements = param.options.map(function(option) { var id = OptionClass + param.signal + '-' + option; var attr = { id: id, type: 'radio', name: param.signal, value: option }; if (option === value) attr.checked = true; var input = element$1('input', attr); input.addEventListener('change', function() { bind.update(option); }); group.appendChild(input); group.appendChild(element$1('label', {'for': id}, option)); return input; }); bind.set = function(value) { var nodes = bind.elements, i = 0, n = nodes.length; for (; i<n; ++i) { if (nodes[i].value === value) nodes[i].checked = true; } }; } /** * Generates a slider input element. */ function range$2(bind, el, param, value) { value = value !== undefined ? value : ((+param.max) + (+param.min)) / 2; var min = param.min || Math.min(0, +value) || 0, max = param.max || Math.max(100, +value) || 100, step = param.step || tickStep(min, max, 100); var node = element$1('input', { type: 'range', value: value, name: param.signal, min: min, max: max, step: step }); var label = element$1('label', {}, +value); el.appendChild(node); el.appendChild(label); node.addEventListener('input', function() { label.textContent = node.value; bind.update(+node.value); }); bind.elements = [node]; bind.set = function(value) { node.value = value; label.textContent = value; }; } function element$1(tag, attr, text) { var el = document.createElement(tag); for (var key in attr) el.setAttribute(key, attr[key]); if (text != null) el.textContent = text; return el; } var Default = 'default'; function cursor(view) { var cursor = view._signals.cursor; // add cursor signal to dataflow, if needed if (!cursor) { view._signals.cursor = (cursor = view.add({user: Default, item: null})); } // evaluate cursor on each mousemove event view.on(view.events('view', 'mousemove'), cursor, function(_, event) { var value = cursor.value, user = value ? (isString(value) ? value : value.user) : Default, item = event.item && event.item.cursor || null; return (value && user === value.user && item == value.item) ? value : {user: user, item: item}; } ); // when cursor signal updates, set visible cursor view.add(null, function(_) { var user = _.cursor, item = this.value; if (!isString(user)) { item = user.item; user = user.user; } setCursor(user && user !== Default ? user : (item || user)); return item; }, {cursor: cursor}); } function setCursor(cursor) { // set cursor on document body // this ensures cursor applies even if dragging out of view if (typeof document !== 'undefined' && document.body) { document.body.style.cursor = cursor; } } function dataref(view, name) { var data = view._runtime.data; if (!data.hasOwnProperty(name)) { view.error('Unrecognized data set: ' + name); } return data[name]; } function data(name) { return dataref(this, name).values.value; } function insert(name, _) { return this.pulse( dataref(this, name).input, changeset().insert(_) ); } function remove(name, _) { return this.pulse( dataref(this, name).input, changeset().remove(_) ); } function width(view) { var padding = view.padding(); return Math.max(0, view._width + padding.left + padding.right); } function height$1(view) { var padding = view.padding(); return Math.max(0, view._height + padding.top + padding.bottom); } function offset$1(view) { var padding = view.padding(), origin = view._origin; return [ padding.left + origin[0], padding.top + origin[1] ]; } function resizeRenderer(view) { var origin = offset$1(view); view._renderer.background(view._background); view._renderer.resize(width(view), height$1(view), origin); view._handler.origin(origin); } /** * Extend an event with additional view-specific methods. * Adds a new property ('vega') to an event that provides a number * of methods for querying information about the current interaction. * The vega object provides the following methods: * view - Returns the backing View instance. * item - Returns the currently active scenegraph item (if any). * group - Returns the currently active scenegraph group (if any). * This method accepts a single string-typed argument indicating the name * of the desired parent group. The scenegraph will be traversed from * the item up towards the root to search for a matching group. If no * argument is provided the enclosing group for the active item is * returned, unless the item it itself a group, in which case it is * returned directly. * xy - Returns a two-element array containing the x and y coordinates for * mouse or touch events. For touch events, this is based on the first * elements in the changedTouches array. This method accepts a single * argument: either an item instance or mark name that should serve as * the reference coordinate system. If no argument is provided the * top-level view coordinate system is assumed. * x - Returns the current x-coordinate, accepts the same arguments as xy. * y - Returns the current y-coordinate, accepts the same arguments as xy. * @param {Event} event - The input event to extend. * @param {Item} item - The currently active scenegraph item (if any). * @return {Event} - The extended input event. */ function eventExtend(view, event, item) { var el = view._renderer.element(), p, e, translate; if (el) { translate = offset$1(view); e = event.changedTouches ? event.changedTouches[0] : event; p = point$4(e, el); p[0] -= translate[0]; p[1] -= translate[1]; } return event.vega = extension(view, item, p), event.item = item, event; } function extension(view, item, point) { var itemGroup = item ? item.mark.marktype === 'group' ? item : item.mark.group : null; function group(name) { var g = itemGroup, i; if (name) for (i = item; i; i = i.mark.group) { if (i.mark.name === name) { g = i; break; } } return g && g.mark && g.mark.interactive ? g : {}; } function xy(item) { if (!item) return point; if (isString(item)) item = group(item); var p = point.slice(); while (item) { p[0] -= item.x || 0; p[1] -= item.y || 0; item = item.mark && item.mark.group; } return p; } return { view: constant$1(view), item: constant$1(item || {}), group: group, xy: xy, x: function(item) { return xy(item)[0]; }, y: function(item) { return xy(item)[1]; } }; } /** * Create a new event stream from an event source. * @param {object} source - The event source to monitor. * @param {string} type - The event type. * @param {function(object): boolean} [filter] - Event filter function. * @return {EventStream} */ function events$1(source, type, filter) { var view = this, s = new EventStream(filter), send = function(e, item) { s.receive(eventExtend(view, e, item)); view.run(); }, sources; if (source === 'view') { view._handler.on(type, send); return s; } if (source === 'window') { if (typeof window !== 'undefined') sources = [window]; } else if (typeof document !== 'undefined') { sources = document.querySelectorAll(source); } if (!sources) { view.warn('Can not resolve event source: ' + source); return s; } for (var i=0, n=sources.length; i<n; ++i) { sources[i].addEventListener(type, send); } view._eventListeners.push({ type: type, sources: sources, handler: send }); return s; } function itemFilter(event) { return event.item; } function markTarget(event) { // grab upstream collector feeding the mark operator var source = event.item.mark.source; return source.source || source; } function invoke(name) { return function(_, event) { return event.vega.view() .changeset() .encode(event.item, name); }; } function hover(hoverSet, leaveSet) { // invoke hover set upon mouseover this.on( this.events('view', 'mouseover', itemFilter), markTarget, invoke(hoverSet || 'hover') ); // invoke leave set upon mouseout this.on( this.events('view', 'mouseout', itemFilter), markTarget, invoke(leaveSet || 'update') ); return this; } /** * Remove all external event listeners. */ function finalize() { var listeners = this._eventListeners, n = listeners.length, m, e; while (--n >= 0) { e = listeners[n]; m = e.sources.length; while (--m >= 0) { e.sources[m].removeEventListener(e.type, e.handler); } } } function initializeRenderer(view, r, el, constructor) { r = r || new constructor(view.loader()); return r .initialize(el, width(view), height$1(view), offset$1(view)) .background(view._background); } function initializeHandler(view, prevHandler, el, constructor) { var handler = new constructor() .scene(view.scenegraph().root) .initialize(el, offset$1(view), view); if (prevHandler) { prevHandler.handlers().forEach(function(h) { handler.on(h.type, h.handler); }); } return handler; } var Canvas$2 = 'canvas'; var PNG = 'png'; var SVG = 'svg'; var None$2 = 'none'; function initialize$1(el) { var view = this, type = view._renderType, Handler = CanvasHandler, Renderer = CanvasRenderer; // select appropriate renderer/handler types if (type === SVG) { Handler = SVGHandler; Renderer = (el ? SVGRenderer : SVGStringRenderer); } // containing dom element if (el) { if (typeof el === 'string' && typeof document !== 'undefined') { el = document.querySelector(el); } el.innerHTML = ''; // clear view._el = el; } else { view._el = null; // headless } // initialize renderer and input handler view._renderer = (type === None$2) ? null : initializeRenderer(view, view._renderer, el, Renderer); view._handler = initializeHandler(view, view._handler, el, Handler); // initialize view bindings if (el && view._bind) view._bind.forEach(function(binding) { view.bind(binding.element || el, binding); }); return view; } /** * Render the current scene in a headless fashion. * This method is asynchronous, returning a Promise instance. * @return {Promise} - A Promise that resolves to a renderer. */ function renderHeadless(view, type) { return view.runAsync().then(function() { var renderClass = (type === SVG) ? SVGStringRenderer : CanvasRenderer; return initializeRenderer(view, null, null, renderClass) .renderAsync(view._scenegraph.root); }); } /** * Produce an image URL for the visualization. Depending on the type * parameter, the generated URL contains data for either a PNG or SVG image. * The URL can be used (for example) to download images of the visualization. * This method is asynchronous, returning a Promise instance. * @param {string} type - The image type. One of 'svg', 'png' or 'canvas'. * The 'canvas' and 'png' types are synonyms for a PNG image. * @return {Promise} - A promise that resolves to an image URL. */ function renderToImageURL(type) { if (type === PNG) type = Canvas$2; if (type !== SVG && type !== Canvas$2) { return Promise.reject('Unrecognized image type: ' + type); } else { return renderHeadless(this, type).then(function(renderer) { return type === Canvas$2 ? renderer.canvas().toDataURL('image/png') : window.URL.createObjectURL( new Blob([renderer.svg()], {type: 'image/svg+xml'}) ); }); } } /** * Produce a Canvas instance containing a rendered visualization. * This method is asynchronous, returning a Promise instance. * @return {Promise} - A promise that resolves to a Canvas instance. */ function renderToCanvas() { return renderHeadless(this, Canvas$2) .then(function(renderer) { return renderer.canvas(); }); } /** * Produce a rendered SVG string of the visualization. * This method is asynchronous, returning a Promise instance. * @return {Promise} - A promise that resolves to an SVG string. */ function renderToSVG() { return renderHeadless(this, SVG) .then(function(renderer) { return renderer.svg(); }); } function parsePadding(spec) { return isObject(spec) ? spec : isNumber(spec) ? {top:spec, bottom:spec, left:spec, right:spec} : {top: 0, left: 0, bottom: 0, right: 0}; // TODO defaults } function parseSignal(signal, scope) { var op = scope.addSignal(signal.name, signal.value); if (signal.react === false) op.react = false; if (signal.bind) scope.addBinding(signal.name, signal.bind); } function ASTNode(type) { this.type = type; } ASTNode.prototype.visit = function(visitor) { var node = this, c, i, n; if (visitor(node)) return 1; for (c=children$1(node), i=0, n=c.length; i<n; ++i) { if (c[i].visit(visitor)) return 1; } } function children$1(node) { switch (node.type) { case 'ArrayExpression': return node.elements; case 'BinaryExpression': case 'LogicalExpression': return [node.left, node.right]; case 'CallExpression': var args = node.arguments.slice(); args.unshift(node.callee); return args; case 'ConditionalExpression': return [node.test, node.consequent, node.alternate]; case 'MemberExpression': return [node.object, node.property]; case 'ObjectExpression': return node.properties; case 'Property': return [node.key, node.value]; case 'UnaryExpression': return [node.argument]; case 'Identifier': case 'Literal': case 'RawCode': default: return []; } } /* The following expression parser is based on Esprima (http://esprima.org/). Original header comment and license for Esprima is included here: Copyright (C) 2013 Ariya Hidayat <[email protected]> Copyright (C) 2013 Thaddee Tyl <[email protected]> Copyright (C) 2013 Mathias Bynens <[email protected]> Copyright (C) 2012 Ariya Hidayat <[email protected]> Copyright (C) 2012 Mathias Bynens <[email protected]> Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]> Copyright (C) 2012 Kris Kowal <[email protected]> Copyright (C) 2012 Yusuke Suzuki <[email protected]> Copyright (C) 2012 Arpad Borsos <[email protected]> Copyright (C) 2011 Ariya Hidayat <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 <COPYRIGHT HOLDER> 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 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ var source$1; var index$2; var length$2; var lookahead; var TokenBooleanLiteral = 1; var TokenEOF = 2; var TokenIdentifier = 3; var TokenKeyword = 4; var TokenNullLiteral = 5; var TokenNumericLiteral = 6; var TokenPunctuator = 7; var TokenStringLiteral = 8; var SyntaxArrayExpression = 'ArrayExpression'; var SyntaxBinaryExpression = 'BinaryExpression'; var SyntaxCallExpression = 'CallExpression'; var SyntaxConditionalExpression = 'ConditionalExpression'; var SyntaxIdentifier = 'Identifier'; var SyntaxLiteral = 'Literal'; var SyntaxLogicalExpression = 'LogicalExpression'; var SyntaxMemberExpression = 'MemberExpression'; var SyntaxObjectExpression = 'ObjectExpression'; var SyntaxProperty = 'Property'; var SyntaxUnaryExpression = 'UnaryExpression'; var MessageUnexpectedToken = 'Unexpected token %0'; var MessageUnexpectedNumber = 'Unexpected number'; var MessageUnexpectedString = 'Unexpected string'; var MessageUnexpectedIdentifier = 'Unexpected identifier'; var MessageUnexpectedReserved = 'Unexpected reserved word'; var MessageUnexpectedEOS = 'Unexpected end of input'; var MessageInvalidRegExp = 'Invalid regular expression'; var MessageUnterminatedRegExp = 'Invalid regular expression: missing /'; var MessageStrictOctalLiteral = 'Octal literals are not allowed in strict mode.'; var MessageStrictDuplicateProperty = 'Duplicate data property in object literal not allowed in strict mode'; var ILLEGAL = 'ILLEGAL'; var DISABLED = 'Disabled.'; var RegexNonAsciiIdentifierStart = new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'); var RegexNonAsciiIdentifierPart = new RegExp('[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]'); // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { /* istanbul ignore next */ if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 0x30 && ch <= 0x39); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 0x20) || (ch === 0x09) || (ch === 0x0B) || (ch === 0x0C) || (ch === 0xA0) || (ch >= 0x1680 && [0x1680, 0x180E, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(ch) >= 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 0x0A) || (ch === 0x0D) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) (ch >= 0x41 && ch <= 0x5A) || // A..Z (ch >= 0x61 && ch <= 0x7A) || // a..z (ch === 0x5C) || // \ (backslash) ((ch >= 0x80) && RegexNonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 0x24) || (ch === 0x5F) || // $ (dollar) and _ (underscore) (ch >= 0x41 && ch <= 0x5A) || // A..Z (ch >= 0x61 && ch <= 0x7A) || // a..z (ch >= 0x30 && ch <= 0x39) || // 0..9 (ch === 0x5C) || // \ (backslash) ((ch >= 0x80) && RegexNonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.1 Keywords var keywords$1 = { 'if':1, 'in':1, 'do':1, 'var':1, 'for':1, 'new':1, 'try':1, 'let':1, 'this':1, 'else':1, 'case':1, 'void':1, 'with':1, 'enum':1, 'while':1, 'break':1, 'catch':1, 'throw':1, 'const':1, 'yield':1, 'class':1, 'super':1, 'return':1, 'typeof':1, 'delete':1, 'switch':1, 'export':1, 'import':1, 'public':1, 'static':1, 'default':1, 'finally':1, 'extends':1, 'package':1, 'private':1, 'function':1, 'continue':1, 'debugger':1, 'interface':1, 'protected':1, 'instanceof':1, 'implements':1 }; function skipComment() { var ch; while (index$2 < length$2) { ch = source$1.charCodeAt(index$2); if (isWhiteSpace(ch) || isLineTerminator(ch)) { ++index$2; } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index$2 < length$2 && isHexDigit(source$1[index$2])) { ch = source$1[index$2++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { throwError({}, MessageUnexpectedToken, ILLEGAL); } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source$1[index$2]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, MessageUnexpectedToken, ILLEGAL); } while (index$2 < length$2) { ch = source$1[index$2++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, MessageUnexpectedToken, ILLEGAL); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source$1.charCodeAt(index$2++); id = String.fromCharCode(ch); // '\u' (U+005C, U+0075) denotes an escaped character. if (ch === 0x5C) { if (source$1.charCodeAt(index$2) !== 0x75) { throwError({}, MessageUnexpectedToken, ILLEGAL); } ++index$2; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } id = ch; } while (index$2 < length$2) { ch = source$1.charCodeAt(index$2); if (!isIdentifierPart(ch)) { break; } ++index$2; id += String.fromCharCode(ch); // '\u' (U+005C, U+0075) denotes an escaped character. if (ch === 0x5C) { id = id.substr(0, id.length - 1); if (source$1.charCodeAt(index$2) !== 0x75) { throwError({}, MessageUnexpectedToken, ILLEGAL); } ++index$2; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index$2++; while (index$2 < length$2) { ch = source$1.charCodeAt(index$2); if (ch === 0x5C) { // Blackslash (U+005C) marks Unicode escape sequence. index$2 = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index$2; } else { break; } } return source$1.slice(start, index$2); } function scanIdentifier() { var start, id, type; start = index$2; // Backslash (U+005C) starts an escaped character. id = (source$1.charCodeAt(index$2) === 0x5C) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = TokenIdentifier; } else if (keywords$1.hasOwnProperty(id)) { type = TokenKeyword; } else if (id === 'null') { type = TokenNullLiteral; } else if (id === 'true' || id === 'false') { type = TokenBooleanLiteral; } else { type = TokenIdentifier; } return { type: type, value: id, start: start, end: index$2 }; } // 7.7 Punctuators function scanPunctuator() { var start = index$2, code = source$1.charCodeAt(index$2), code2, ch1 = source$1[index$2], ch2, ch3, ch4; switch (code) { // Check for most common single-character punctuators. case 0x2E: // . dot case 0x28: // ( open bracket case 0x29: // ) close bracket case 0x3B: // ; semicolon case 0x2C: // , comma case 0x7B: // { open curly brace case 0x7D: // } close curly brace case 0x5B: // [ case 0x5D: // ] case 0x3A: // : case 0x3F: // ? case 0x7E: // ~ ++index$2; return { type: TokenPunctuator, value: String.fromCharCode(code), start: start, end: index$2 }; default: code2 = source$1.charCodeAt(index$2 + 1); // '=' (U+003D) marks an assignment or comparison operator. if (code2 === 0x3D) { switch (code) { case 0x2B: // + case 0x2D: // - case 0x2F: // / case 0x3C: // < case 0x3E: // > case 0x5E: // ^ case 0x7C: // | case 0x25: // % case 0x26: // & case 0x2A: // * index$2 += 2; return { type: TokenPunctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), start: start, end: index$2 }; case 0x21: // ! case 0x3D: // = index$2 += 2; // !== and === if (source$1.charCodeAt(index$2) === 0x3D) { ++index$2; } return { type: TokenPunctuator, value: source$1.slice(start, index$2), start: start, end: index$2 }; } } } // 4-character punctuator: >>>= ch4 = source$1.substr(index$2, 4); if (ch4 === '>>>=') { index$2 += 4; return { type: TokenPunctuator, value: ch4, start: start, end: index$2 }; } // 3-character punctuators: === !== >>> <<= >>= ch3 = ch4.substr(0, 3); if (ch3 === '>>>' || ch3 === '<<=' || ch3 === '>>=') { index$2 += 3; return { type: TokenPunctuator, value: ch3, start: start, end: index$2 }; } // Other 2-character punctuators: ++ -- << >> && || ch2 = ch3.substr(0, 2); if ((ch1 === ch2[1] && ('+-<>&|'.indexOf(ch1) >= 0)) || ch2 === '=>') { index$2 += 2; return { type: TokenPunctuator, value: ch2, start: start, end: index$2 }; } // 1-character punctuators: < > = ! + - * % & | ^ / if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index$2; return { type: TokenPunctuator, value: ch1, start: start, end: index$2 }; } throwError({}, MessageUnexpectedToken, ILLEGAL); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index$2 < length$2) { if (!isHexDigit(source$1[index$2])) { break; } number += source$1[index$2++]; } if (number.length === 0) { throwError({}, MessageUnexpectedToken, ILLEGAL); } if (isIdentifierStart(source$1.charCodeAt(index$2))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } return { type: TokenNumericLiteral, value: parseInt('0x' + number, 16), start: start, end: index$2 }; } function scanOctalLiteral(start) { var number = '0' + source$1[index$2++]; while (index$2 < length$2) { if (!isOctalDigit(source$1[index$2])) { break; } number += source$1[index$2++]; } if (isIdentifierStart(source$1.charCodeAt(index$2)) || isDecimalDigit(source$1.charCodeAt(index$2))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } return { type: TokenNumericLiteral, value: parseInt(number, 8), octal: true, start: start, end: index$2 }; } function scanNumericLiteral() { var number, start, ch; ch = source$1[index$2]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index$2; number = ''; if (ch !== '.') { number = source$1[index$2++]; ch = source$1[index$2]; // Hex number starts with '0x'. // Octal number starts with '0'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index$2; return scanHexLiteral(start); } if (isOctalDigit(ch)) { return scanOctalLiteral(start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } } while (isDecimalDigit(source$1.charCodeAt(index$2))) { number += source$1[index$2++]; } ch = source$1[index$2]; } if (ch === '.') { number += source$1[index$2++]; while (isDecimalDigit(source$1.charCodeAt(index$2))) { number += source$1[index$2++]; } ch = source$1[index$2]; } if (ch === 'e' || ch === 'E') { number += source$1[index$2++]; ch = source$1[index$2]; if (ch === '+' || ch === '-') { number += source$1[index$2++]; } if (isDecimalDigit(source$1.charCodeAt(index$2))) { while (isDecimalDigit(source$1.charCodeAt(index$2))) { number += source$1[index$2++]; } } else { throwError({}, MessageUnexpectedToken, ILLEGAL); } } if (isIdentifierStart(source$1.charCodeAt(index$2))) { throwError({}, MessageUnexpectedToken, ILLEGAL); } return { type: TokenNumericLiteral, value: parseFloat(number), start: start, end: index$2 }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, octal = false; quote = source$1[index$2]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index$2; ++index$2; while (index$2 < length$2) { ch = source$1[index$2++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source$1[index$2++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'u': case 'x': if (source$1[index$2] === '{') { ++index$2; str += scanUnicodeCodePointEscape(); } else { str += scanHexEscape(ch); } break; case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index$2 < length$2 && isOctalDigit(source$1[index$2])) { octal = true; code = code * 8 + '01234567'.indexOf(source$1[index$2++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index$2 < length$2 && isOctalDigit(source$1[index$2])) { code = code * 8 + '01234567'.indexOf(source$1[index$2++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { if (ch === '\r' && source$1[index$2] === '\n') { ++index$2; } } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, MessageUnexpectedToken, ILLEGAL); } return { type: TokenStringLiteral, value: str, octal: octal, start: start, end: index$2 }; } function testRegExp(pattern, flags) { var tmp = pattern; if (flags.indexOf('u') >= 0) { // Replace each astral symbol and every Unicode code point // escape sequence with a single ASCII symbol to avoid throwing on // regular expressions that are only valid in combination with the // `/u` flag. // Note: replacing with the ASCII symbol `x` might cause false // negatives in unlikely scenarios. For example, `[\u{61}-b]` is a // perfectly valid pattern that is equivalent to `[a-b]`, but it // would be replaced by `[x-b]` which throws an error. tmp = tmp .replace(/\\u\{([0-9a-fA-F]+)\}/g, function($0, $1) { if (parseInt($1, 16) <= 0x10FFFF) { return 'x'; } throwError({}, MessageInvalidRegExp); }) .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, 'x'); } // First, detect invalid regular expressions. try { new RegExp(tmp); } catch (e) { throwError({}, MessageInvalidRegExp); } // Return a regular expression object for this pattern-flag pair, or // `null` in case the current environment doesn't support the flags it // uses. try { return new RegExp(pattern, flags); } catch (exception) { return null; } } function scanRegExpBody() { var ch, str, classMarker, terminated, body; ch = source$1[index$2]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source$1[index$2++]; classMarker = false; terminated = false; while (index$2 < length$2) { ch = source$1[index$2++]; str += ch; if (ch === '\\') { ch = source$1[index$2++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, MessageUnterminatedRegExp); } str += ch; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, MessageUnterminatedRegExp); } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } } } if (!terminated) { throwError({}, MessageUnterminatedRegExp); } // Exclude leading and trailing slash. body = str.substr(1, str.length - 2); return { value: body, literal: str }; } function scanRegExpFlags() { var ch, str, flags; str = ''; flags = ''; while (index$2 < length$2) { ch = source$1[index$2]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index$2; if (ch === '\\' && index$2 < length$2) { throwError({}, MessageUnexpectedToken, ILLEGAL); } else { flags += ch; str += ch; } } if (flags.search(/[^gimuy]/g) >= 0) { throwError({}, MessageInvalidRegExp, flags); } return { value: flags, literal: str }; } function scanRegExp() { var start, body, flags, value; lookahead = null; skipComment(); start = index$2; body = scanRegExpBody(); flags = scanRegExpFlags(); value = testRegExp(body.value, flags.value); return { literal: body.literal + flags.literal, value: value, regex: { pattern: body.value, flags: flags.value }, start: start, end: index$2 }; } function isIdentifierName(token) { return token.type === TokenIdentifier || token.type === TokenKeyword || token.type === TokenBooleanLiteral || token.type === TokenNullLiteral; } function advance() { var ch; skipComment(); if (index$2 >= length$2) { return { type: TokenEOF, start: index$2, end: index$2 }; } ch = source$1.charCodeAt(index$2); if (isIdentifierStart(ch)) { return scanIdentifier(); } // Very common: ( and ) and ; if (ch === 0x28 || ch === 0x29 || ch === 0x3B) { return scanPunctuator(); } // String literal starts with single quote (U+0027) or double quote (U+0022). if (ch === 0x27 || ch === 0x22) { return scanStringLiteral(); } // Dot (.) U+002E can also start a floating-point number, hence the need // to check the next character. if (ch === 0x2E) { if (isDecimalDigit(source$1.charCodeAt(index$2 + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index$2 = token.end; lookahead = advance(); index$2 = token.end; return token; } function peek$1() { var pos; pos = index$2; lookahead = advance(); index$2 = pos; } function finishArrayExpression(elements) { var node = new ASTNode(SyntaxArrayExpression); node.elements = elements; return node; } function finishBinaryExpression(operator, left, right) { var node = new ASTNode((operator === '||' || operator === '&&') ? SyntaxLogicalExpression : SyntaxBinaryExpression); node.operator = operator; node.left = left; node.right = right; return node; } function finishCallExpression(callee, args) { var node = new ASTNode(SyntaxCallExpression); node.callee = callee; node.arguments = args; return node; } function finishConditionalExpression(test, consequent, alternate) { var node = new ASTNode(SyntaxConditionalExpression); node.test = test; node.consequent = consequent; node.alternate = alternate; return node; } function finishIdentifier(name) { var node = new ASTNode(SyntaxIdentifier); node.name = name; return node; } function finishLiteral(token) { var node = new ASTNode(SyntaxLiteral); node.value = token.value; node.raw = source$1.slice(token.start, token.end); if (token.regex) { if (node.raw === '//') { node.raw = '/(?:)/'; } node.regex = token.regex; } return node; } function finishMemberExpression(accessor, object, property) { var node = new ASTNode(SyntaxMemberExpression); node.computed = accessor === '['; node.object = object; node.property = property; if (!node.computed) property.member = true; return node; } function finishObjectExpression(properties) { var node = new ASTNode(SyntaxObjectExpression); node.properties = properties; return node; } function finishProperty(kind, key, value) { var node = new ASTNode(SyntaxProperty); node.key = key; node.value = value; node.kind = kind; return node; } function finishUnaryExpression(operator, argument) { var node = new ASTNode(SyntaxUnaryExpression); node.operator = operator; node.argument = argument; node.prefix = true; return node; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function(whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); error = new Error(msg); error.index = index$2; error.description = msg; throw error; } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === TokenEOF) { throwError(token, MessageUnexpectedEOS); } if (token.type === TokenNumericLiteral) { throwError(token, MessageUnexpectedNumber); } if (token.type === TokenStringLiteral) { throwError(token, MessageUnexpectedString); } if (token.type === TokenIdentifier) { throwError(token, MessageUnexpectedIdentifier); } if (token.type === TokenKeyword) { throwError(token, MessageUnexpectedReserved); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, MessageUnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== TokenPunctuator || token.value !== value) { throwUnexpected(token); } } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === TokenPunctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { return lookahead.type === TokenKeyword && lookahead.value === keyword; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = []; index$2 = lookahead.start; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { elements.push(parseConditionalExpression()); if (!match(']')) { expect(','); } } } lex(); return finishArrayExpression(elements); } // 11.1.5 Object Initialiser function parseObjectPropertyKey() { var token; index$2 = lookahead.start; token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === TokenStringLiteral || token.type === TokenNumericLiteral) { if (token.octal) { throwError(token, MessageStrictOctalLiteral); } return finishLiteral(token); } return finishIdentifier(token.value); } function parseObjectProperty() { var token, key, id, value; index$2 = lookahead.start; token = lookahead; if (token.type === TokenIdentifier) { id = parseObjectPropertyKey(); expect(':'); value = parseConditionalExpression(); return finishProperty('init', id, value); } if (token.type === TokenEOF || token.type === TokenPunctuator) { throwUnexpected(token); } else { key = parseObjectPropertyKey(); expect(':'); value = parseConditionalExpression(); return finishProperty('init', key, value); } } function parseObjectInitialiser() { var properties = [], property, name, key, map = {}, toString = String; index$2 = lookahead.start; expect('{'); while (!match('}')) { property = parseObjectProperty(); if (property.key.type === SyntaxIdentifier) { name = property.key.name; } else { name = toString(property.key.value); } key = '$' + name; if (Object.prototype.hasOwnProperty.call(map, key)) { throwError({}, MessageStrictDuplicateProperty); } else { map[key] = true; } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return finishObjectExpression(properties); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); expr = parseExpression$1(); expect(')'); return expr; } // 11.1 Primary Expressions var legalKeywords = { "if": 1, "this": 1 }; function parsePrimaryExpression() { var type, token, expr; if (match('(')) { return parseGroupExpression(); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } type = lookahead.type; index$2 = lookahead.start; if (type === TokenIdentifier || legalKeywords[lookahead.value]) { expr = finishIdentifier(lex().value); } else if (type === TokenStringLiteral || type === TokenNumericLiteral) { if (lookahead.octal) { throwError(lookahead, MessageStrictOctalLiteral); } expr = finishLiteral(lex()); } else if (type === TokenKeyword) { throw new Error(DISABLED); } else if (type === TokenBooleanLiteral) { token = lex(); token.value = (token.value === 'true'); expr = finishLiteral(token); } else if (type === TokenNullLiteral) { token = lex(); token.value = null; expr = finishLiteral(token); } else if (match('/') || match('/=')) { expr = finishLiteral(scanRegExp()); peek$1(); } else { throwUnexpected(lex()); } return expr; } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = []; expect('('); if (!match(')')) { while (index$2 < length$2) { args.push(parseConditionalExpression()); if (match(')')) { break; } expect(','); } } expect(')'); return args; } function parseNonComputedProperty() { var token; index$2 = lookahead.start; token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return finishIdentifier(token.value); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression$1(); expect(']'); return expr; } function parseLeftHandSideExpressionAllowCall() { var expr, args, property; expr = parsePrimaryExpression(); for (;;) { if (match('.')) { property = parseNonComputedMember(); expr = finishMemberExpression('.', expr, property); } else if (match('(')) { args = parseArguments(); expr = finishCallExpression(expr, args); } else if (match('[')) { property = parseComputedMember(); expr = finishMemberExpression('[', expr, property); } else { break; } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var expr = parseLeftHandSideExpressionAllowCall(); if (lookahead.type === TokenPunctuator) { if ((match('++') || match('--'))) { throw new Error(DISABLED); } } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var token, expr; if (lookahead.type !== TokenPunctuator && lookahead.type !== TokenKeyword) { expr = parsePostfixExpression(); } else if (match('++') || match('--')) { throw new Error(DISABLED); } else if (match('+') || match('-') || match('~') || match('!')) { token = lex(); expr = parseUnaryExpression(); expr = finishUnaryExpression(token.value, expr); } else if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { throw new Error(DISABLED); } else { expr = parsePostfixExpression(); } return expr; } function binaryPrecedence(token) { var prec = 0; if (token.type !== TokenPunctuator && token.type !== TokenKeyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': case 'in': prec = 7; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var marker, markers, expr, token, prec, stack, right, operator, left, i; marker = lookahead; left = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token); if (prec === 0) { return left; } token.prec = prec; lex(); markers = [marker, lookahead]; right = parseUnaryExpression(); stack = [left, token, right]; while ((prec = binaryPrecedence(lookahead)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); markers.pop(); expr = finishBinaryExpression(operator, left, right); stack.push(expr); } // Shift. token = lex(); token.prec = prec; stack.push(token); markers.push(lookahead); expr = parseUnaryExpression(); stack.push(expr); } // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; markers.pop(); while (i > 1) { markers.pop() expr = finishBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, consequent, alternate; expr = parseBinaryExpression(); if (match('?')) { lex(); consequent = parseConditionalExpression(); expect(':'); alternate = parseConditionalExpression(); expr = finishConditionalExpression(expr, consequent, alternate); } return expr; } // 11.14 Comma Operator function parseExpression$1() { var expr = parseConditionalExpression(); if (match(',')) { throw new Error(DISABLED); // no sequence expressions } return expr; } function parse$3(code) { source$1 = code; index$2 = 0; length$2 = source$1.length; lookahead = null; peek$1(); var expr = parseExpression$1(); if (lookahead.type !== TokenEOF) { throw new Error("Unexpect token after expression."); } return expr; } var Constants = { NaN: 'NaN', E: 'Math.E', LN2: 'Math.LN2', LN10: 'Math.LN10', LOG2E: 'Math.LOG2E', LOG10E: 'Math.LOG10E', PI: 'Math.PI', SQRT1_2: 'Math.SQRT1_2', SQRT2: 'Math.SQRT2' }; function Functions(codegen) { function fncall(name, args, cast, type) { var obj = codegen(args[0]); if (cast) { obj = cast + '(' + obj + ')'; if (cast.lastIndexOf('new ', 0) === 0) obj = '(' + obj + ')'; } return obj + '.' + name + (type < 0 ? '' : type === 0 ? '()' : '(' + args.slice(1).map(codegen).join(',') + ')'); } function fn(name, cast, type) { return function(args) { return fncall(name, args, cast, type); }; } var DATE = 'new Date', STRING = 'String', REGEXP = 'RegExp'; return { // MATH functions isNaN: 'isNaN', isFinite: 'isFinite', abs: 'Math.abs', acos: 'Math.acos', asin: 'Math.asin', atan: 'Math.atan', atan2: 'Math.atan2', ceil: 'Math.ceil', cos: 'Math.cos', exp: 'Math.exp', floor: 'Math.floor', log: 'Math.log', max: 'Math.max', min: 'Math.min', pow: 'Math.pow', random: 'Math.random', round: 'Math.round', sin: 'Math.sin', sqrt: 'Math.sqrt', tan: 'Math.tan', clamp: function(args) { if (args.length < 3) error('Missing arguments to clamp function.'); if (args.length > 3) error('Too many arguments to clamp function.'); var a = args.map(codegen); return 'Math.max('+a[1]+', Math.min('+a[2]+','+a[0]+'))'; }, // DATE functions now: 'Date.now', utc: 'Date.UTC', datetime: DATE, date: fn('getDate', DATE, 0), day: fn('getDay', DATE, 0), year: fn('getFullYear', DATE, 0), month: fn('getMonth', DATE, 0), hours: fn('getHours', DATE, 0), minutes: fn('getMinutes', DATE, 0), seconds: fn('getSeconds', DATE, 0), milliseconds: fn('getMilliseconds', DATE, 0), time: fn('getTime', DATE, 0), timezoneoffset: fn('getTimezoneOffset', DATE, 0), utcdate: fn('getUTCDate', DATE, 0), utcday: fn('getUTCDay', DATE, 0), utcyear: fn('getUTCFullYear', DATE, 0), utcmonth: fn('getUTCMonth', DATE, 0), utchours: fn('getUTCHours', DATE, 0), utcminutes: fn('getUTCMinutes', DATE, 0), utcseconds: fn('getUTCSeconds', DATE, 0), utcmilliseconds: fn('getUTCMilliseconds', DATE, 0), // shared sequence functions length: fn('length', null, -1), indexof: fn('indexOf', null), lastindexof: fn('lastIndexOf', null), slice: fn('slice', null), // STRING functions parseFloat: 'parseFloat', parseInt: 'parseInt', upper: fn('toUpperCase', STRING, 0), lower: fn('toLowerCase', STRING, 0), substring: fn('substring', STRING), replace: fn('replace', STRING), // REGEXP functions regexp: REGEXP, test: fn('test', REGEXP), // Control Flow functions if: function(args) { if (args.length < 3) error('Missing arguments to if function.'); if (args.length > 3) error('Too many arguments to if function.'); var a = args.map(codegen); return a[0]+'?'+a[1]+':'+a[2]; } }; } function codegen(opt) { opt = opt || {}; var whitelist = opt.whitelist ? toSet(opt.whitelist) : {}, blacklist = opt.blacklist ? toSet(opt.blacklist) : {}, constants = opt.constants || Constants, functions = (opt.functions || Functions)(visit), globalvar = opt.globalvar, fieldvar = opt.fieldvar, globals = {}, fields = {}, memberDepth = 0; var outputGlobal = isFunction(globalvar) ? globalvar : function (id) { return globalvar + '["' + id + '"]'; }; function visit(ast) { if (isString(ast)) return ast; var generator = Generators[ast.type]; if (generator == null) error('Unsupported type: ' + ast.type); return generator(ast); } var Generators = { Literal: function(n) { return n.raw; }, Identifier: function(n) { var id = n.name; return memberDepth > 0 ? id : blacklist.hasOwnProperty(id) ? error('Illegal identifier: ' + id) : constants.hasOwnProperty(id) ? constants[id] : whitelist.hasOwnProperty(id) ? id : (globals[id] = 1, outputGlobal(id)); }, MemberExpression: function(n) { var d = !n.computed; var o = visit(n.object); if (d) memberDepth += 1; var p = visit(n.property); if (o === fieldvar) { fields[p] = 1; } // HACKish... if (d) memberDepth -= 1; return o + (d ? '.'+p : '['+p+']'); }, CallExpression: function(n) { if (n.callee.type !== 'Identifier') { error('Illegal callee type: ' + n.callee.type); } var callee = n.callee.name; var args = n.arguments; var fn = functions.hasOwnProperty(callee) && functions[callee]; if (!fn) error('Unrecognized function: ' + callee); return isFunction(fn) ? fn(args) : fn + '(' + args.map(visit).join(',') + ')'; }, ArrayExpression: function(n) { return '[' + n.elements.map(visit).join(',') + ']'; }, BinaryExpression: function(n) { return '(' + visit(n.left) + n.operator + visit(n.right) + ')'; }, UnaryExpression: function(n) { return '(' + n.operator + visit(n.argument) + ')'; }, ConditionalExpression: function(n) { return '(' + visit(n.test) + '?' + visit(n.consequent) + ':' + visit(n.alternate) + ')'; }, LogicalExpression: function(n) { return '(' + visit(n.left) + n.operator + visit(n.right) + ')'; }, ObjectExpression: function(n) { return '{' + n.properties.map(visit).join(',') + '}'; }, Property: function(n) { memberDepth += 1; var k = visit(n.key); memberDepth -= 1; return k + ':' + visit(n.value); } }; function codegen(ast) { var result = { code: visit(ast), globals: Object.keys(globals), fields: Object.keys(fields) }; globals = {}; fields = {}; return result; } codegen.functions = functions; codegen.constants = constants; return codegen; } var scalePrefix = '%'; var Literal = 'Literal'; var Identifier = 'Identifier'; var indexPrefix = '@'; var tuplePrefix = ':'; var eventPrefix = 'event.vega.'; var thisPrefix = 'this.'; // Expression Functions var eventFunctions = ['view', 'item', 'group', 'xy', 'x', 'y']; var scaleFunctions = ['bandwidth', 'copy', 'domain', 'range', 'gradient', 'invert', 'scale']; function getScale(name, ctx) { var s = isString(name) ? ctx.scales[name] : isObject(name) && name.signal ? ctx.signals[name.signal] : undefined; return s && s.value; } function formatter(method) { var cache = {}; return function(_, specifier) { var f = cache[specifier] || (cache[specifier] = method(specifier)); return f(_); }; } function expressionFunctions(codegen) { var fn = Functions(codegen); eventFunctions.forEach(function(name) { fn[name] = eventPrefix + name; }); for (var name in extendedFunctions) { fn[name] = thisPrefix + name; } return fn; } function log$3(df, method, value, message) { try { df[method]('EXPRESSION' + (message ? ' ' + message : ''), value); } catch (err) { df.warn(err); } return value; } var _window = (typeof window !== 'undefined' && window) || null; var _timeFormat = formatter(timeFormat); var _date = new Date(2000, 0, 1); var _time = function(month, day, specifier) { _date.setMonth(month); _date.setDate(day); return _timeFormat(_date, specifier); }; var extendedFunctions = { format: formatter(format), utcFormat: formatter(utcFormat), timeFormat: _timeFormat, pad: pad, truncate: truncate, rgb: rgb, lab: lab, hcl: hcl, hsl: hsl, gradient: scaleGradient, monthFormat: function(month) { return _time(month, 1, '%B'); }, monthAbbrevFormat: function(month) { return _time(month, 1, '%b'); }, dayFormat: function(day) { return _time(0, 2 + day, '%A'); }, dayAbbrevFormat: function(day) { return _time(0, 2 + day, '%a'); }, quarter: function(date) { return 1 + ~~(new Date(date).getMonth() / 3); }, utcquarter: function(date) { return 1 + ~~(new Date(date).getUTCMonth() / 3); }, warn: function(value, message) { return log$3(this.context.dataflow, 'warn', value, message); }, info: function(value, message) { return log$3(this.context.dataflow, 'info', value, message); }, debug: function(value, message) { return log$3(this.context.dataflow, 'debug', value, message); }, inScope: function(item) { var group = this.context.group, value = false; if (group) while (item) { if (item === group) { value = true; break; } item = item.mark.group; } return value; }, clampRange: function(range, min, max) { var lo = range[0], hi = range[1], span; if (hi < lo) span = hi, hi = lo, lo = span; span = hi - lo; return [ Math.min(Math.max(lo, min), max - span), Math.min(Math.max(hi, span), max) ]; }, pinchDistance: function() { return 'Math.sqrt(' + 'Math.pow(event.touches[0].clientX - event.touches[1].clientX, 2) + ' + 'Math.pow(event.touches[0].clientY - event.touches[1].clientY, 2)' + ')'; }, pinchAngle: function() { return 'Math.atan2(' + 'event.touches[1].clientY - event.touches[0].clientY,' + 'event.touches[1].clientX - event.touches[0].clientX' + ')'; }, open: function(uri, name) { var df = this.context.dataflow; if (_window && _window.open) { df.loader().sanitize(uri, {context:'open', name:name}) .then(function(url) { _window.open(url, name); }) .catch(function(e) { df.warn('Open url failed: ' + e); }); } else { df.warn('Open function can only be invoked in a browser.'); } }, screen: function() { return _window ? _window.screen : {}; }, windowsize: function() { return _window ? [_window.innerWidth, _window.innerHeight] : [undefined, undefined]; }, span: function(array) { return array[array.length-1] - array[0]; }, range: function(name, group) { var s = getScale(name, (group || this).context); return s && s.range ? s.range() : [0, 0]; }, domain: function(name, group) { var s = getScale(name, (group || this).context); return s ? s.domain() : []; }, bandwidth: function(name, group) { var s = getScale(name, (group || this).context); return s && s.bandwidth ? s.bandwidth() : 0; }, copy: function(name, group) { var s = getScale(name, (group || this).context); return s ? s.copy() : undefined; }, scale: function(name, value, group) { var s = getScale(name, (group || this).context); return s ? s(value) : undefined; }, invert: function(name, range, group) { var s = getScale(name, (group || this).context); return !s ? undefined : isArray(range) ? (s.invertRange || s.invert)(range) : (s.invert || s.invertExtent)(range); }, tuples: function(name) { var data = this.context.data[name]; return data ? data.values.value : []; }, indata: function(name, field, value) { var index = this.context.data[name]['index:' + field], entry = index ? index.value[value] : undefined; return entry ? entry.count : entry; }, inrange: function(value, range) { var r0 = range[0], r1 = range[range.length-1], t; if (r0 > r1) t = r0, r0 = r1, r1 = t; return r0 <= value && value <= r1; }, encode: function(item, name, retval) { if (item) { var df = this.context.dataflow, target = item.mark.source; df.pulse(target, df.changeset().encode(item, name)); } return retval !== undefined ? retval : item; }, modify: function(name, insert, remove, toggle, modify, values) { var df = this.context.dataflow, data = this.context.data[name], input = data.input, changes = data.changes, stamp = df.stamp(), predicate, key; if (!(input.value.length || insert || toggle)) { // nothing to do! return 0; } if (!changes || changes.stamp < stamp) { data.changes = (changes = df.changeset()); changes.stamp = stamp; df.runAfter(function() { df.pulse(input, changes).run(); }); } if (remove) { changes.remove(remove === true ? truthy : remove); } if (insert) { changes.insert(insert); } if (toggle) { predicate = function(_) { for (key in toggle) { if (_[key] !== toggle[key]) return false; } return true; }; if (input.value.filter(predicate).length) { changes.remove(predicate); } else { changes.insert(toggle); } } if (modify) { for (key in values) { changes.modify(modify, key, values[key]); } } return 1; } }; // AST visitors for dependency analysis function scaleVisitor(name, args, scope, params) { if (args[0].type === Literal) { // scale dependency name = args[0].value; var scaleName = scalePrefix + name; if (!params.hasOwnProperty(scaleName)) { try { params[scaleName] = scope.scaleRef(name); } catch (err) { // TODO: error handling? warning? } } } else if (args[0].type === Identifier) { // forward reference to signal name = args[0].name; args[0] = new ASTNode(Literal); args[0].raw = '{signal:"' + name + '"}'; } } function indataVisitor(name, args, scope, params) { if (args[0].type !== Literal) error('First argument to indata must be a string literal.'); if (args[1].type !== Literal) error('Second argument to indata must be a string literal.'); var data = args[0].value, field = args[1].value, indexName = indexPrefix + field; if (!params.hasOwnProperty(indexName)) { params[indexName] = scope.getData(data).indataRef(scope, field); } } function tuplesVisitor(name, args, scope, params) { if (args[0].type !== Literal) error('First argument to tuples must be a string literal.'); var data = args[0].value, dataName = tuplePrefix + data; if (!params.hasOwnProperty(dataName)) { params[dataName] = scope.getData(data).tuplesRef(); } } function visitors() { var v = { indata: indataVisitor, tuples: tuplesVisitor }; scaleFunctions.forEach(function(_) { v[_] = scaleVisitor; }); return v; } // Export code generator parameters var codegenParams = { blacklist: ['_'], whitelist: ['datum', 'event'], fieldvar: 'datum', globalvar: function(id) { return '_[' + $('$' + id) + ']'; }, functions: expressionFunctions, constants: Constants, visitors: visitors() }; var signalPrefix = '$'; var generator = codegen(codegenParams); function parseExpression(expr, scope, preamble) { var params = {}, ast, gen; // parse the expression to an abstract syntax tree (ast) try { ast = parse$3(expr); } catch (err) { error('Expression parse error: ' + expr); } // analyze ast function calls for dependencies ast.visit(function visitor(node) { if (node.type !== 'CallExpression') return; var name = node.callee.name, visit = codegenParams.visitors[name]; if (visit) visit(name, node.arguments, scope, params); }); // perform code generation gen = generator(ast); // collect signal dependencies gen.globals.forEach(function(name) { var signalName = signalPrefix + name; if (!params.hasOwnProperty(signalName) && scope.getSignal(name)) { params[signalName] = scope.signalRef(name); } }); // return generated expression code and dependencies return { $expr: preamble ? preamble + 'return(' + gen.code + ');' : gen.code, $fields: gen.fields, $params: params }; } var GroupMark = 'group'; var RectMark = 'rect'; var RuleMark = 'rule'; var SymbolMark = 'symbol'; var TextMark = 'text'; var marktypes = toSet([ '*', 'arc', 'area', 'group', 'image', 'line', 'path', 'rect', 'rule', 'shape', 'symbol', 'text' ]); function isMarkType(type) { return marktypes.hasOwnProperty(type); } /** * Parse an event selector string. * Returns an array of event stream definitions. */ function parseSelector(selector) { return parseMerge(selector.trim()) .map(parseSelector$1); } var LBRACK = '['; var RBRACK = ']'; var LBRACE = '{'; var RBRACE = '}'; var COLON = ':'; var COMMA = ','; var GT = '>'; var ILLEGAL$1 = /[\[\]\{\}]/; function find$1(s, i, endChar, pushChar, popChar) { var count = 0, n = s.length, c; for (; i<n; ++i) { c = s[i]; if (!count && c === endChar) return i; else if (popChar && popChar.indexOf(c) >= 0) --count; else if (pushChar && pushChar.indexOf(c) >= 0) ++count; } return i; } function parseMerge(s) { var output = [], start = 0, n = s.length, i = 0; while (i < n) { i = find$1(s, i, COMMA, LBRACK + LBRACE, RBRACK + RBRACE); output.push(s.substring(start, i).trim()); start = ++i; } if (output.length === 0) { throw 'Empty event selector: ' + s; } return output; } function parseSelector$1(s) { return s[0] === '[' ? parseBetween(s) : parseStream(s); } function parseBetween(s) { var start = 1, n = s.length, i = 1, b, stream; i = find$1(s, i, RBRACK, LBRACK, RBRACK); if (i === n) { throw 'Empty between selector: ' + s; } b = parseMerge(s.substring(start, i)); if (b.length !== 2) { throw 'Between selector must have two elements: ' + s; } s = s.slice(i + 1).trim(); if (s[0] !== GT) { throw 'Expected \'>\' after between selector: ' + s; } b = b.map(parseSelector$1); stream = parseSelector$1(s.slice(1).trim()); if (stream.between) { return { between: b, stream: stream }; } else { stream.between = b; } return stream; } function parseStream(s) { var stream = {source: 'view'}, source = [], throttle = [0, 0], markname = 0, start = 0, n = s.length, i = 0, j, filter; // extract throttle from end if (s[n-1] === RBRACE) { i = s.lastIndexOf(LBRACE); if (i >= 0) { try { throttle = parseThrottle(s.substring(i+1, n-1)); } catch (e) { throw 'Invalid throttle specification: ' + s; } s = s.slice(0, i).trim(); n = s.length; } else throw 'Unmatched right brace: ' + s; i = 0; } if (!n) throw s; // set name flag based on first char if (s[0] === '@') markname = ++i; // extract first part of multi-part stream selector j = find$1(s, i, COLON); if (j < n) { source.push(s.substring(start, j).trim()); start = i = ++j; } // extract remaining part of stream selector i = find$1(s, i, LBRACK); if (i === n) { source.push(s.substring(start, n).trim()); } else { source.push(s.substring(start, i).trim()); filter = []; start = ++i; if (start === n) throw 'Unmatched left bracket: ' + s; } // extract filters while (i < n) { i = find$1(s, i, RBRACK); if (i === n) throw 'Unmatched left bracket: ' + s; filter.push(s.substring(start, i).trim()); if (i < n-1 && s[++i] !== LBRACK) throw 'Expected left bracket: ' + s; start = ++i; } // marshall event stream specification if (!(n = source.length) || ILLEGAL$1.test(source[n-1])) { throw 'Invalid event selector: ' + s; } if (n > 1) { stream.type = source[1]; if (markname) { stream.markname = source[0].slice(1); } else if (isMarkType(source[0])) { stream.marktype = source[0]; } else { stream.source = source[0]; } } else { stream.type = source[0]; } if (stream.type.slice(-1) === '!') { stream.consume = true; stream.type = stream.type.slice(0, -1) } if (filter != null) stream.filter = filter; if (throttle[0]) stream.throttle = throttle[0]; if (throttle[1]) stream.debounce = throttle[1]; return stream; } function parseThrottle(s) { var a = s.split(COMMA); if (!s.length || a.length > 2) throw s; return a.map(function(_) { var x = +_; if (x !== x) throw s; return x; }); } var VIEW = 'view'; var SCOPE = 'scope'; function parseStream$1(stream, scope) { return stream.signal ? scope.getSignal(stream.signal).id : parseStream$2(stream, scope); } function eventSource(source) { return source === SCOPE ? VIEW : (source || VIEW); } function parseStream$2(stream, scope) { var method = stream.merge ? mergeStream : stream.stream ? nestedStream : stream.type ? eventStream : error('Invalid stream specification: ' + JSON.stringify(stream)); return method(stream, scope); } function mergeStream(stream, scope) { var list = stream.merge.map(function(s) { return parseStream$2(s, scope); }); var entry = streamParameters({merge: list}, stream, scope); return scope.addStream(entry).id; } function nestedStream(stream, scope) { var id = parseStream$2(stream.stream, scope), entry = streamParameters({stream: id}, stream, scope); return scope.addStream(entry).id; } function eventStream(stream, scope) { var id = scope.event(eventSource(stream.source), stream.type), entry = streamParameters({stream: id}, stream, scope); return Object.keys(entry).length === 1 ? id : scope.addStream(entry).id; } function streamParameters(entry, stream, scope) { var param = stream.between; if (param) { if (param.length !== 2) { error('Stream between parameter must have 2 entries.'); } entry.between = [ parseStream$2(param[0], scope), parseStream$2(param[1], scope) ]; } param = stream.filter ? array$1(stream.filter) : []; if (stream.marktype || stream.markname) { // add filter for mark type and/or mark name param.push(filterMark(stream.marktype, stream.markname)); } if (stream.source === SCOPE) { // add filter to limit events from sub-scope only param.push('inScope(event.item)'); } if (param.length) { entry.filter = parseExpression('(' + param.join(')&&(') + ')').$expr; } if ((param = stream.throttle) != null) { entry.throttle = +param; } if ((param = stream.debounce) != null) { entry.debounce = +param; } if (stream.consume) { entry.consume = true; } return entry; } function filterMark(type, name) { var item = 'event.item'; return item + (type && type !== '*' ? '&&' + item + '.mark.marktype===\'' + type + '\'' : '') + (name ? '&&' + item + '.mark.name===\'' + name + '\'' : ''); } var preamble = 'var datum=event.item&&event.item.datum;'; function parseUpdate(spec, scope, target) { var events = spec.events, update = spec.update, encode = spec.encode, sources = [], value = '', entry; if (!events) { error('Signal update missing events specification.'); } // interpret as an event selector string if (isString(events)) { events = parseSelector(events); } // separate event streams from signal updates events = array$1(events).filter(function(stream) { return stream.signal ? (sources.push(stream), 0) : 1; }); // merge event streams, include as source if (events.length) { sources.push(events.length > 1 ? {merge: events} : events[0]); } if (encode != null) { if (update) error('Signal encode and update are mutually exclusive.'); update = 'encode(item(),' + $(encode) + ')'; } // resolve update value value = isString(update) ? parseExpression(update, scope, preamble) : update.expr != null ? parseExpression(update.expr, scope, preamble) : update.value != null ? update.value : update.signal != null ? { $expr: '_.value', $params: {value: scope.signalRef(update.signal)} } : error('Invalid signal update specification.'); entry = { target: target, update: value }; if (spec.force) { entry.options = {force: true}; } sources.forEach(function(source) { source = {source: parseStream$1(source, scope)}; scope.addUpdate(extend(source, entry)); }); } function parseSignalUpdates(signal, scope) { var op = scope.getSignal(signal.name); if (signal.update) { var expr = parseExpression(signal.update, scope); op.update = expr.$expr; op.params = expr.$params; } if (signal.on) { signal.on.forEach(function(_) { parseUpdate(_, scope, op.id); }); } } function parseProjection(proj, scope) { var params = {}; for (var name in proj) { if (name === 'name') continue; params[name] = parseParameter(proj[name], scope); } scope.addProjection(proj.name, params); } function parseParameter(_, scope) { return isArray(_) ? _.map(function(_) { return parseParameter(_, scope); }) : !isObject(_) ? _ : _.signal ? scope.signalRef(_.signal) : error('Unsupported parameter object: ' + JSON.stringify(_)); } var Skip = toSet(['rule']); function adjustSpatial(encode, marktype) { var code = ''; if (Skip[marktype]) return code; if (encode.x2) { if (encode.x) { code += 'if(o.x>o.x2)$=o.x,o.x=o.x2,o.x2=$;'; code += 'o.width=o.x2-o.x;' } else if (encode.width) { code += 'o.x=o.x2-o.width;'; } else { code += 'o.x=o.x2;'; } } if (encode.xc) { if (encode.width) { code += 'o.x=o.xc-o.width/2;'; } else { code += 'o.x=o.xc;'; } } if (encode.y2) { if (encode.y) { code += 'if(o.y>o.y2)$=o.y,o.y=o.y2,o.y2=$;'; code += 'o.height=o.y2-o.y;' } else if (encode.height) { code += 'o.y=o.y2-o.height;'; } else { code += 'o.y=o.y2;'; } } if (encode.yc) { if (encode.height) { code += 'o.y=o.yc-o.height/2;'; } else { code += 'o.y=o.yc;'; } } return code; } function color$2(enc, scope, params, fields) { function color(type, x, y, z) { var a = entry(null, x, scope, params, fields), b = entry(null, y, scope, params, fields), c = entry(null, z, scope, params, fields); // TODO put color functions in scope return 'this.' + type + '(' + [a, b, c].join(',') + ').toString()'; } return (enc.c) ? color('hcl', enc.h, enc.c, enc.l) : (enc.h || enc.s) ? color('hsl', enc.h, enc.s, enc.l) : (enc.l || enc.a) ? color('lab', enc.l, enc.a, enc.b) : (enc.r || enc.g || enc.b) ? color('rgb', enc.r, enc.g, enc.b) : null; } function expression(code, scope, params, fields) { var expr = parseExpression(code, scope); expr.$fields.forEach(function(name) { fields[name] = 1; }); extend(params, expr.$params); return expr.$expr; } function field$1(ref, scope, params, fields) { return resolve$1(isObject(ref) ? ref : {datum: ref}, scope, params, fields); } function resolve$1(ref, scope, params, fields) { var object, level, field; if (ref.signal) { object = 'datum'; field = expression(ref.signal, scope, params, fields); } else if (ref.group || ref.parent) { level = Math.max(1, ref.level || 1); object = 'item'; while (level-- > 0) { object += '.mark.group'; } if (ref.parent) { field = ref.parent; object += '.datum'; } else { field = ref.group; } } else if (ref.datum) { object = 'datum'; field = ref.datum; } else { error('Invalid field reference: ' + JSON.stringify(ref)); } if (!ref.signal) { if (isString(field)) { fields[field] = 1; // TODO review field tracking? field = splitAccessPath(field).map($).join(']['); } else { field = resolve$1(field, scope, params, fields); } } return object + '[' + field + ']'; } function scale$2(enc, value, scope, params, fields) { var scale = getScale$1(enc.scale, scope, params, fields), interp, func, flag; if (enc.range != null) { // pull value from scale range interp = +enc.range; func = scale + '.range()'; value = (interp === 0) ? (func + '[0]') : '($=' + func + ',' + ((interp === 1) ? '$[$.length-1]' : '$[0]+' + interp + '*($[$.length-1]-$[0])') + ')'; } else { // run value through scale and/or pull scale bandwidth value = value != null ? scale + '(' + value + ')' : null; if (enc.band && (flag = hasBandwidth(enc.scale, scope))) { func = scale + '.bandwidth'; interp = +enc.band; interp = func + '()' + (interp===1 ? '' : '*' + interp); // if we don't know the scale type, check for bandwidth if (flag < 0) interp = '(' + func + '?' + interp + ':0)'; value = (value ? value + '+' : '') + interp; if (enc.extra) { // include logic to handle extraneous elements value = '(datum.extra?' + scale + '(datum.extra.value):' + value + ')'; } } if (value == null) value = '0'; } return value; } function hasBandwidth(name, scope) { if (!isString(name)) return -1; var type = scope.scaleType(name); return type === 'band' || type === 'point' ? 1 : 0; } function getScale$1(name, scope, params, fields) { var scaleName; if (isString(name)) { // direct scale lookup; add scale as parameter scaleName = scalePrefix + name; if (!params.hasOwnProperty(scaleName)) { params[scaleName] = scope.scaleRef(name); } scaleName = $(scaleName); } else { // indirect scale lookup; add all scales as parameters for (scaleName in scope.scales) { params[scalePrefix + scaleName] = scope.scaleRef(scaleName); } scaleName = $(scalePrefix) + '+' + field$1(name, scope, params, fields); } return '_[' + scaleName + ']'; } function gradient$1(enc, scope, params, fields) { return 'this.gradient(' + getScale$1(enc.gradient, scope, params, fields) + ',' + $(enc.start) + ',' + $(enc.stop) + ',' + $(enc.count) + ')'; } function property(property, scope, params, fields) { return isObject(property) ? '(' + entry(null, property, scope, params, fields) + ')' : property; } function entry(channel, enc, scope, params, fields) { if (enc.gradient != null) { return gradient$1(enc, scope, params, fields); } var value = (enc.color != null) ? color$2(enc.color, scope, params, fields) : (enc.field != null) ? field$1(enc.field, scope, params, fields) : (enc.signal != null) ? expression(enc.signal, scope, params, fields) : (enc.value != null) ? $(enc.value) : null; if (enc.scale != null) { value = scale$2(enc, value, scope, params, fields); } if (enc.exponent != null) { value = 'Math.pow(' + value + ',' + property(enc.exponent, scope, params, fields) + ')'; } if (enc.mult != null) { value += '*' + property(enc.mult, scope, params, fields); } if (enc.offset != null) { value += '+' + property(enc.offset, scope, params, fields); } if (enc.round) { value = 'Math.round(' + value + ')'; } return value; } function set$3(obj, key, value) { return obj + '[' + $(key) + ']=' + value + ';'; } function rule$1(channel, rules, scope, params, fields) { var code = ''; rules.forEach(function(rule) { var value = entry(channel, rule, scope, params, fields); code += rule.test ? expression(rule.test, scope, params, fields) + '?' + value + ':' : value; }); return set$3('o', channel, code); } function parseEncode(encode, marktype, params, scope) { var fields = {}, code = 'var o=item,datum=o.datum,$;', channel, enc, value; for (channel in encode) { enc = encode[channel]; if (isArray(enc)) { // rule code += rule$1(channel, enc, scope, params, fields); } else { value = entry(channel, enc, scope, params, fields); code += set$3('o', channel, value); } } code += adjustSpatial(encode, marktype); code += 'return 1;'; return { $expr: code, $fields: Object.keys(fields), $output: Object.keys(encode) }; } var MarkRole = 'mark'; var FrameRole$1 = 'frame'; var ScopeRole$1 = 'scope'; var AxisRole$1 = 'axis'; var AxisDomainRole = 'axis-domain'; var AxisGridRole = 'axis-grid'; var AxisLabelRole = 'axis-label'; var AxisTickRole = 'axis-tick'; var AxisTitleRole = 'axis-title'; var LegendRole$1 = 'legend'; var LegendEntryRole = 'legend-entry'; var LegendGradientRole = 'legend-gradient'; var LegendLabelRole = 'legend-label'; var LegendSymbolRole = 'legend-symbol'; var LegendTitleRole = 'legend-title'; function encoder(_) { return isObject(_) ? _ : {value: _}; } function extendEncode(encode, extra) { for (var name in extra) { if (name === 'interactive') continue; encode[name] = extend(encode[name] || {}, extra[name]); } return encode; } function encoders(encode, type, role, scope, params) { var enc, key; params = params || {}; params.encoders = {$encode: (enc = {})}; encode = applyDefaults(encode, type, role, scope.config); for (key in encode) { enc[key] = parseEncode(encode[key], type, params, scope); } return params; } function applyDefaults(encode, type, role, config) { var enter, key, skip; config = config && (role === FrameRole$1 ? config.group : role === MarkRole ? config.mark && config.mark[type] : null); if (config) { enter = {}; for (key in config) { // do not apply defaults if relevant fields are defined skip = has(key, encode) || (key === 'fill' || key === 'stroke') && (has('fill', encode) || has('stroke', encode)); if (!skip) enter[key] = {value: config[key]}; } encode = extend({}, encode); // defensive copy encode.enter = extend(enter, encode.enter); } return encode; } function has(key, encode) { return (encode.enter && encode.enter[key]) || (encode.update && encode.update[key]); } function guideMark(type, role, key, dataRef, encode, extras) { return { type: type, role: role, key: key, from: dataRef, interactive: !!(extras && extras.interactive), encode: extendEncode(encode, extras) }; } function legendGradient(scale, config, userEncode) { var zero = {value: 0}, encode = {}; encode.enter = { opacity: zero, x: zero, y: zero, width: {value: config.gradientWidth}, height: {value: config.gradientHeight}, stroke: {value: config.gradientStrokeColor}, strokeWidth: {value: config.gradientStrokeWidth} }; encode.exit = { opacity: zero }; encode.update = { x: zero, y: zero, width: {value: config.gradientWidth}, height: {value: config.gradientHeight}, fill: {gradient: scale}, opacity: {value: 1} }; return guideMark(RectMark, LegendGradientRole, undefined, undefined, encode, userEncode); } var Top = 'top'; var Left = 'left'; var Right = 'right'; var Bottom = 'bottom'; var Index = 'index'; var Label = 'label'; var Offset = 'offset'; var Perc = 'perc'; var Size = 'size'; var Total = 'total'; var Value = 'value'; var alignExpr = 'datum.' + Perc + '<=0?"left"' + ':datum.' + Perc + '>=1?"right":"center"'; function legendGradientLabels(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero, text: {field: Label}, fill: {value: config.labelColor}, font: {value: config.labelFont}, fontSize: {value: config.labelFontSize}, baseline: {value: config.gradientLabelBaseline} }; encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; enter.x = update.x = { field: Perc, mult: config.gradientWidth }; enter.y = update.y = { value: config.gradientHeight, offset: config.gradientLabelOffset }; enter.align = update.align = {signal: alignExpr}; return guideMark(TextMark, LegendLabelRole, Label, dataRef, encode, userEncode); } function legendLabels(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero, fill: {value: config.labelColor}, text: {field: Label}, font: {value: config.labelFont}, fontSize: {value: config.labelFontSize}, align: {value: config.labelAlign}, baseline: {value: config.labelBaseline} }; encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; enter.x = update.x = { field: Offset, offset: config.labelOffset }; enter.y = update.y = { field: Size, mult: 0.5, offset: { field: Total, offset: { field: {group: 'entryPadding'}, mult: {field: Index} } } }; return guideMark(TextMark, LegendLabelRole, Label, dataRef, encode, userEncode); } function legendSymbols(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}, enter, update; encode.enter = enter = { opacity: zero, shape: {value: config.symbolType}, size: {value: config.symbolSize}, strokeWidth: {value: config.symbolStrokeWidth} }; if (!spec.fill) { enter.stroke = {value: config.symbolColor}; } encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; enter.x = update.x = { field: Offset, mult: 0.5 }; enter.y = update.y = { field: Size, mult: 0.5, offset: { field: Total, offset: { field: {group: 'entryPadding'}, mult: {field: Index} } } }; ['shape', 'size', 'fill', 'stroke', 'opacity'].forEach(function(scale) { if (spec[scale]) { update[scale] = enter[scale] = {scale: spec[scale], field: Value}; } }); return guideMark(SymbolMark, LegendSymbolRole, Label, dataRef, encode, userEncode); } function legendTitle(spec, config, userEncode, dataRef) { var zero = {value: 0}, encode = {}; encode.enter = { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, opacity: zero, fill: {value: config.titleColor}, font: {value: config.titleFont}, fontSize: {value: config.titleFontSize}, fontWeight: {value: config.titleFontWeight}, align: {value: config.titleAlign}, baseline: {value: config.titleBaseline} }; encode.exit = { opacity: zero }; encode.update = { opacity: {value: 1}, text: {field: 'title'} }; return guideMark(TextMark, LegendTitleRole, null, dataRef, encode, userEncode); } function guideGroup(role, name, dataRef, interactive, encode, marks) { return { type: GroupMark, name: name, role: role, from: dataRef, interactive: interactive, encode: encode, marks: marks }; } function role(spec) { return spec.role || (spec.type === GroupMark && (spec.legends || spec.axes) ? ScopeRole$1 : MarkRole); } function definition$1(spec) { return { clip: spec.clip || false, interactive: spec.interactive === false ? false : true, marktype: spec.type, name: spec.name || undefined, role: role(spec), zindex: +spec.zindex || undefined }; } function dataName(name) { return name; } function Entry(type, value, params, parent) { this.id = -1, this.type = type; this.value = value; this.params = params; if (parent) this.parent = parent; } function entry$1(type, value, params, parent) { return new Entry(type, value, params, parent); } function operator(value, params) { return entry$1('Operator', value, params); } // ----- function ref(op) { var ref = {$ref: op.id}; // if operator not yet registered, cache ref to resolve later if (op.id < 0) (op.refs = op.refs || []).push(ref); return ref; } function fieldRef(field, name) { return name ? {$field: field, $name: name} : {$field: field}; } var keyFieldRef = fieldRef('key'); function compareRef(fields, orders) { return {$compare: fields, $order: orders}; } function keyRef(fields) { return {$key: fields}; } // ----- var Ascending = 'ascending'; var Descending = 'descending'; function sortKey(sort) { return !isObject(sort) ? '' : (sort.order === Descending ? '-' : '+') + aggrField(sort.op, sort.field); } function aggrField(op, field) { return (op && op.signal ? '$' + op.signal : op || '') + (op && field ? '_' : '') + (field && field.signal ? '$' + field.signal : field || ''); } // ----- function isSignal(_) { return _ && _.signal; } function transform$3(name) { return function(params, value, parent) { return entry$1(name, value, params || undefined, parent); }; } var Aggregate$1 = transform$3('Aggregate'); var AxisTicks$1 = transform$3('AxisTicks'); var Bound$1 = transform$3('Bound'); var Collect$1 = transform$3('Collect'); var Compare$1 = transform$3('Compare'); var DataJoin$1 = transform$3('DataJoin'); var Encode$1 = transform$3('Encode'); var Facet$1 = transform$3('Facet'); var Field$1 = transform$3('Field'); var Key$1 = transform$3('Key'); var LegendEntries$1 = transform$3('LegendEntries'); var Mark$1 = transform$3('Mark'); var MultiExtent$1 = transform$3('MultiExtent'); var MultiValues$1 = transform$3('MultiValues'); var Params$1 = transform$3('Params'); var PreFacet$1 = transform$3('PreFacet'); var Projection$1 = transform$3('Projection'); var Relay$1 = transform$3('Relay'); var Render$1 = transform$3('Render'); var Scale$1 = transform$3('Scale'); var Sieve$1 = transform$3('Sieve'); var ViewLayout$1 = transform$3('ViewLayout'); var Values$1 = transform$3('Values'); /** * Parse a data transform specification. */ function parseTransform(spec, scope) { var def = definition(spec.type); if (!def) error('Unrecognized transform type: ' + spec.type); var t = entry$1(def.type, null, parseParameters(def, spec, scope)); if (spec.signal) scope.addSignal(spec.signal, t); return t.metadata = def.metadata || {}, t; } /** * Parse all parameters of a data transform. */ function parseParameters(def, spec, scope) { var params = {}, pdef, i, n; for (i=0, n=def.params.length; i<n; ++i) { pdef = def.params[i]; params[pdef.name] = parseParameter$1(pdef, spec, scope); } return params; } /** * Parse a data transform parameter. */ function parseParameter$1(def, spec, scope) { var type = def.type, value; if (type === 'index') { return parseIndexParameter(def, spec, scope); } else if (type === 'param') { return parseSubParameters(def, spec, scope); } else if (type === 'projection') { return scope.projectionRef(spec[def.name]); } else { value = spec[def.name]; if (value === undefined) { if (def.required) { error('Missing required ' + spec.type + ' parameter: ' + def.name); } return; } return def.array && !isSignal(value) ? value.map(function(v) { return parameterValue(def, v, scope); }) : parameterValue(def, value, scope); } } /** * Parse a single parameter value. */ function parameterValue(def, value, scope) { var type = def.type; if (isSignal(value)) { return isExpr(type) ? error('Expression references can not be signals.') : isField(type) ? scope.fieldRef(value) : isCompare(type) ? scope.compareRef(value) : scope.signalRef(value.signal); } else { var expr = def.expr || isField(type); return expr && outerExpr(value) ? parseExpression(value.expr, scope) : expr && outerField(value) ? fieldRef(value.field) : isExpr(type) ? parseExpression(value, scope) : isData(type) ? ref(scope.getData(value).values) : isField(type) ? fieldRef(value) : isCompare(type) ? compareRef(array$1(value.field), array$1(value.order)) : value; } } /** * Parse parameter for accessing an index of another data set. */ function parseIndexParameter(def, spec, scope) { if (!isString(spec.from)) { error('Lookup "from" parameter must be a string literal.'); } return scope.getData(spec.from).lookupRef(scope, spec.key); } /** * Parse a parameter that contains one or more sub-parameter objects. */ function parseSubParameters(def, spec, scope) { var value = spec[def.name]; if (def.array) { if (!isArray(value)) { // signals not allowed! error('Expected an array of sub-parameters. Instead: ' + value); } return value.map(function(v) { return parseSubParameter(def, v, scope); }); } else { return parseSubParameter(def, value, scope); } } /** * Parse a sub-parameter object. */ function parseSubParameter(def, value, scope) { var params, pdef, k, i, n; // loop over defs to find matching key for (i=0, n=def.params.length; i<n; ++i) { pdef = def.params[i]; for (k in pdef.key) { if (pdef.key[k] !== value[k]) { pdef = null; break; } } if (pdef) break; } // raise error if matching key not found if (!pdef) error('Unsupported parameter: ' + JSON.stringify(value)); // parse params, create Params transform, return ref params = extend(parseParameters(pdef, value, scope), pdef.key); return ref(scope.add(Params$1(params))); } // -- Utilities ----- function outerExpr(_) { return _ && _.expr; } function outerField(_) { return _ && _.field; } function isData(_) { return _ === 'data'; } function isExpr(_) { return _ === 'expr'; } function isField(_) { return _ === 'field'; } function isCompare(_) { return _ === 'compare' } function parseData(from, group, scope) { var facet, key, op, dataRef; // if no source data, generate singleton datum if (!from) { dataRef = ref(scope.add(Collect$1(null, [{}]))); } // if faceted, process facet specification else if (facet = from.facet) { if (!group) error('Only group marks can be faceted.'); // use pre-faceted source data, if available if (facet.field != null) { dataRef = ref(scope.getData(facet.data).output); } else { key = scope.keyRef(facet.groupby); // generate facet aggregates if no direct data specification if (!from.data) { op = parseTransform(extend({ type: 'aggregate', groupby: array$1(facet.groupby) }, facet.aggregate)); op.params.key = key; op.params.pulse = ref(scope.getData(facet.data).output); dataRef = ref(scope.add(op)); } } } // if not yet defined, get source data reference if (!dataRef) { dataRef = from.$ref ? from : from.mark ? ref(scope.getData(dataName(from.mark)).output) : ref(scope.getData(from.data).output); } return {key: key, pulse: dataRef}; } function DataScope(scope, input, output, values) { this.scope = scope; this.input = input; this.output = output; this.values = values; this.index = {}; } DataScope.fromEntries = function(scope, entries) { var n = entries.length, i = 1, input = entries[0], values = entries[n-1], output = entries[n-2]; // add operator entries to this scope, wire up pulse chain scope.add(entries[0]); for (; i<n; ++i) { entries[i].params.pulse = ref(entries[i-1]); scope.add(entries[i]); } return new DataScope(scope, input, output, values); }; var prototype$69 = DataScope.prototype; prototype$69.countsRef = function(scope, field, sort) { var ds = this, cache = ds.counts || (ds.counts = {}), k = fieldKey(field), v, a, p; if (k != null) { scope = ds.scope; v = cache[k]; } if (!v) { p = { groupby: scope.fieldRef(field, 'key'), pulse: ref(ds.output) }; if (sort && sort.field) addSortField(scope, p, sort); a = scope.add(Aggregate$1(p)); v = scope.add(Collect$1({pulse: ref(a)})); v = {agg: a, ref: ref(v)}; if (k != null) cache[k] = v; } else if (sort && sort.field) { addSortField(scope, v.agg.params, sort); } return v.ref; }; function fieldKey(field) { return isString(field) ? field : null; } function addSortField(scope, p, sort) { var as = aggrField(sort.op, sort.field), s; if (p.ops) { for (var i=0, n=p.as.length; i<n; ++i) { if (p.as[i] === as) return; } } else { p.ops = ['count']; p.fields = [null]; p.as = ['count']; } if (sort.op) { p.ops.push((s=sort.op.signal) ? scope.signalRef(s) : sort.op); p.fields.push(scope.fieldRef(sort.field)); p.as.push(as); } } function cache(scope, ds, name, optype, field, counts, index) { var cache = ds[name] || (ds[name] = {}), sort = sortKey(counts), k = fieldKey(field), v, op; if (k != null) { scope = ds.scope; k = k + (sort ? '|' + sort : ''); v = cache[k]; } if (!v) { var params = counts ? {field: keyFieldRef, pulse: ds.countsRef(scope, field, counts)} : {field: scope.fieldRef(field), pulse: ref(ds.output)}; if (sort) params.sort = scope.sortRef(counts); op = scope.add(entry$1(optype, undefined, params)); if (index) ds.index[field] = op; v = ref(op); if (k != null) cache[k] = v; } return v; } prototype$69.tuplesRef = function() { return ref(this.values); }; prototype$69.extentRef = function(scope, field) { return cache(scope, this, 'extent', 'Extent', field, false); }; prototype$69.domainRef = function(scope, field) { return cache(scope, this, 'domain', 'Values', field, false); }; prototype$69.valuesRef = function(scope, field, sort) { return cache(scope, this, 'vals', 'Values', field, sort || true); }; prototype$69.lookupRef = function(scope, field) { return cache(scope, this, 'lookup', 'TupleIndex', field, false); }; prototype$69.indataRef = function(scope, field) { return cache(scope, this, 'indata', 'TupleIndex', field, true, true); }; function parseFacet(spec, scope, group) { var facet = spec.from.facet, name = facet.name, data = ref(scope.getData(facet.data).output), subscope, source, values, op; if (!facet.name) { error('Facet must have a name: ' + JSON.stringify(facet)); } if (!facet.data) { error('Facet must reference a data set: ' + JSON.stringify(facet)); } if (facet.field) { op = scope.add(PreFacet$1({ field: scope.fieldRef(facet.field), pulse: data })); } else if (facet.groupby) { op = scope.add(Facet$1({ key: scope.keyRef(facet.groupby), group: group.pulse, pulse: data })); } else { error('Facet must specify groupby or field: ' + JSON.stringify(facet)); } // initialize facet subscope subscope = scope.fork(); source = subscope.add(Collect$1()); values = subscope.add(Sieve$1({pulse: ref(source)})); subscope.addData(name, new DataScope(subscope, source, source, values)); subscope.addSignal('parent', null); // parse faceted subflow op.params.subflow = { $subflow: parseSpec(spec, subscope).toRuntime() }; } function parseSubflow(spec, scope, input) { var op = scope.add(PreFacet$1({pulse: input.pulse})), subscope = scope.fork(); subscope.add(Sieve$1()); subscope.addSignal('parent', null); // parse group mark subflow op.params.subflow = { $subflow: parseSpec(spec, subscope).toRuntime() }; } function parseTrigger(spec, scope, name) { var remove = spec.remove, insert = spec.insert, toggle = spec.toggle, modify = spec.modify, values = spec.values, op = scope.add(operator()), update, expr; update = 'if(' + spec.trigger + ',modify("' + name + '",' + [insert, remove, toggle, modify, values] .map(function(_) { return _ == null ? 'null' : _; }) .join(',') + '),0)'; expr = parseExpression(update, scope); op.update = expr.$expr; op.params = expr.$params; } function parseMark(spec, scope) { var role$$ = role(spec), group = spec.type === GroupMark, facet = spec.from && spec.from.facet, layout = role$$ === ScopeRole$1 || role$$ === FrameRole$1, op, input, store, bound, render, sieve, name, markRef, encodeRef, boundRef; // resolve input data input = parseData(spec.from, group, scope); // data join to map tuples to visual items op = scope.add(DataJoin$1(input)); // collect visual items op = store = scope.add(Collect$1({pulse: ref(op)})); // connect visual items to scenegraph op = scope.add(Mark$1({ markdef: definition$1(spec), scenepath: {$itempath: scope.markpath()}, pulse: ref(op) })); markRef = ref(op); // add visual encoders op = scope.add(Encode$1( encoders(spec.encode, spec.type, role$$, scope, {pulse: markRef}) )); // monitor parent marks to propagate changes op.params.parent = scope.encode(); // add post-encoding transforms, if defined if (spec.transform) { spec.transform.forEach(function(_) { var tx = parseTransform(_, scope); if (tx.metadata.generates || tx.metadata.changes) { error('Mark transforms should not generate new data.'); } tx.params.pulse = ref(op); scope.add(op = tx); }); } encodeRef = ref(op); // if group is faceted or requires view layout, recurse here if (facet || layout) { op = scope.add(ViewLayout$1({ legendMargin: scope.config.legendMargin, mark: markRef, pulse: encodeRef })); // we juggle the layout operator as we want it in our scope state, // but we also want it to be run *after* any faceting transforms scope.operators.pop(); scope.pushState(encodeRef, ref(op)); (facet ? parseFacet(spec, scope, input) : parseSubflow(spec, scope, input)); scope.popState(); scope.operators.push(op); } // compute bounding boxes bound = scope.add(Bound$1({mark: markRef, pulse: ref(op)})); boundRef = ref(bound); // if non-faceted / non-layout group, recurse here if (group && !facet && !layout) { scope.pushState(encodeRef, boundRef); // if a normal group mark, we must generate dynamic subflows // otherwise, we know the group is a guide with only one group item // in that case we can simplify the dataflow (role$$ === MarkRole ? parseSubflow(spec, scope, input) : parseSpec(spec, scope)); scope.popState(); } // render / sieve items render = scope.add(Render$1({pulse: boundRef})); sieve = scope.add(Sieve$1({pulse: boundRef}, undefined, scope.parent())); // if mark is named, make accessible as reactive geometry // add trigger updates if defined if (spec.name != null) { name = dataName(spec.name); scope.addData(name, new DataScope(scope, store, render, sieve)); if (spec.on) spec.on.forEach(function(on) { if (on.insert || on.remove || on.toggle) { error('Marks only support modify triggers.'); } parseTrigger(on, scope, name); }); } } function parseLegend(spec, scope) { var type = spec.type || 'symbol', config = scope.config.legend, name = spec.name || undefined, encode = spec.encode || {}, interactive = !!spec.interactive, datum, dataRef, entryRef, group, title, legendEncode, entryEncode, children; // resolve 'canonical' scale name var scale = spec.size || spec.shape || spec.fill || spec.stroke || spec.opacity; if (!scale) { error('Missing valid scale for legend.'); } // single-element data source for axis group datum = { orient: value(spec.orient, config.orient), title: spec.title }; dataRef = ref(scope.add(Collect$1(null, [datum]))); // encoding properties for legend group legendEncode = extendEncode({ update: { offset: encoder(value(spec.offset, config.offset)), padding: encoder(value(spec.padding, config.padding)), titlePadding: encoder(value(spec.titlePadding, config.titlePadding)) } }, encode.legend); // encoding properties for legend entry sub-group entryEncode = { update: { x: {field: {group: 'padding'}}, y: {field: {group: 'padding'}}, entryPadding: encoder(value(spec.entryPadding, config.entryPadding)) } }; if (type === 'gradient') { // data source for gradient labels entryRef = ref(scope.add(LegendEntries$1({ type: 'gradient', scale: scope.scaleRef(scale), count: scope.property(spec.tickCount), values: scope.property(spec.values), formatSpecifier: scope.property(spec.format) }))); children = [ legendGradient(scale, config, encode.gradient), legendGradientLabels(spec, config, encode.labels, entryRef) ]; } else { // data source for legend entries entryRef = ref(scope.add(LegendEntries$1({ size: sizeExpression(spec, config, encode.labels), scale: scope.scaleRef(scale), count: scope.property(spec.tickCount), values: scope.property(spec.values), formatSpecifier: scope.property(spec.formatSpecifier) }))); children = [ legendSymbols(spec, config, encode.symbols, entryRef), legendLabels(spec, config, encode.labels, entryRef) ]; } // generate legend marks children = [ guideGroup(LegendEntryRole, null, dataRef, interactive, entryEncode, children) ]; // include legend title if defined if (datum.title) { title = legendTitle(spec, config, encode.title, dataRef); entryEncode.update.y.offset = { field: {group: 'titlePadding'}, offset: title.encode.update.fontSize || title.encode.enter.fontSize }; children.push(title); } // build legend specification group = guideGroup(LegendRole$1, name, dataRef, interactive, legendEncode, children); if (spec.zindex) group.zindex = spec.zindex; // parse legend specification return parseMark(group, scope); } function value(value, defaultValue) { return value != null ? value : defaultValue; } function sizeExpression(spec, config, encode) { // TODO get override for symbolSize... var symbolSize = +config.symbolSize, fontSize; fontSize = encode && encode.update && encode.update.fontSize; if (!fontSize) fontSize = encode && encode.enter && encode.enter.fontSize; if (fontSize) fontSize = fontSize.value; // TODO support signal? if (!fontSize) fontSize = +config.labelFontSize; return spec.size ? {$expr: 'Math.max(Math.ceil(Math.sqrt(_.scale(datum))),' + fontSize + ')'} : Math.max(Math.ceil(Math.sqrt(symbolSize)), fontSize); } var types = [ 'identity', 'ordinal', 'band', 'point', 'index', 'linear', 'pow', 'sqrt', 'log', 'sequential', 'time', 'utc', 'quantize', 'quantile', 'threshold' ] var allTypes = toSet(types); var ordinalTypes = toSet(types.slice(1, 5)); function isOrdinal(type) { return ordinalTypes.hasOwnProperty(type); } function isQuantile(type) { return type === 'quantile'; } function parseScale(spec, scope) { var type = spec.type || 'linear', params, key; if (!allTypes.hasOwnProperty(type)) { error('Unrecognized scale type: ' + type); } params = { type: type, domain: parseScaleDomain(spec.domain, spec, scope) }; if (spec.range != null) { if (spec.rangeStep != null) { error('Scale range and rangeStep are mutually exclusive.'); } params.range = parseScaleRange(spec, scope); } for (key in spec) { if (params[key] || key === 'name') continue; params[key] = parseLiteral(spec[key], scope); } scope.addScale(spec.name, params); } function parseLiteral(v, scope) { return !isObject(v) ? v : v.signal ? scope.signalRef(v.signal) : error('Unsupported object: ' + v); } // -- SCALE DOMAIN ---- function parseScaleDomain(domain, spec, scope) { if (!domain) return; // default domain if (domain.signal) { return scope.signalRef(domain.signal); } return (isArray(domain) ? explicitDomain : domain.fields ? multipleDomain : singularDomain)(domain, spec, scope); } function explicitDomain(domain, spec, scope) { return domain.map(function(v) { return parseLiteral(v, scope); }); } function singularDomain(domain, spec, scope) { var data = scope.getData(domain.data); if (!data) error('Can not find data set: ' + domain.data); return isOrdinal(spec.type) ? data.valuesRef(scope, domain.field, parseSort(domain.sort, false)) : isQuantile(spec.type) ? data.domainRef(scope, domain.field) : data.extentRef(scope, domain.field); } function multipleDomain(domain, spec, scope) { var data = domain.data, fields = domain.fields.reduce(function(dom, d) { return dom.push(isString(d) ? {data: data, field: d} : d), dom; }, []); return (isOrdinal(spec.type) ? ordinalMultipleDomain : isQuantile(spec.type) ? quantileMultipleDomain : numericMultipleDomain)(domain, scope, fields); } function ordinalMultipleDomain(domain, scope, fields) { var counts, a, c, v; // get value counts for each domain field counts = fields.map(function(f) { var data = scope.getData(f.data); if (!data) error('Can not find data set: ' + f.data); return data.countsRef(scope, f.field); }); // sum counts from all fields a = scope.add(Aggregate$1({ groupby: keyFieldRef, ops:['sum'], fields: [scope.fieldRef('count')], as:['count'], pulse: counts })); // collect aggregate output c = scope.add(Collect$1({pulse: ref(a)})); // extract values for combined domain v = scope.add(Values$1({ field: keyFieldRef, sort: scope.sortRef(parseSort(domain.sort, true)), pulse: ref(c) })); return ref(v); } function parseSort(sort, multidomain) { if (sort) { if (!sort.field && !sort.op) { if (isObject(sort)) sort.field = 'key'; else sort = {field: 'key'}; } else if (!sort.field && sort.op !== 'count') { error('No field provided for sort aggregate op: ' + sort.op); } else if (multidomain && sort.field) { error('Multiple domain scales can not sort by field.'); } else if (multidomain && sort.op && sort.op !== 'count') { error('Multiple domain scales support op count only.'); } } return sort; } function quantileMultipleDomain(domain, scope, fields) { // get value arrays for each domain field var values = fields.map(function(f) { var data = scope.getData(f.data); if (!data) error('Can not find data set: ' + f.data); return data.domainRef(scope, f.field); }); // combine value arrays return ref(scope.add(MultiValues$1({values: values}))); } function numericMultipleDomain(domain, scope, fields) { // get extents for each domain field var extents = fields.map(function(f) { var data = scope.getData(f.data); if (!data) error('Can not find data set: ' + f.data); return data.extentRef(scope, f.field); }); // combine extents return ref(scope.add(MultiExtent$1({extents: extents}))); } // -- SCALE RANGE ----- function parseScaleRange(spec, scope) { var range = spec.range, config = scope.config.range; if (range.signal) { return scope.signalRef(range.signal); } else if (isString(range)) { if (config && config.hasOwnProperty(range)) { range = config[range]; } else if (range === 'width') { range = [0, {signal: 'width'}] } else if (range === 'height') { range = isOrdinal(spec.type) ? [0, {signal: 'height'}] : [{signal: 'height'}, 0] } else { error('Unrecognized scale range value: ' + range); } } else if (isOrdinal(spec.type) && !isArray(range)) { return parseScaleDomain(range, spec, scope); } else if (!isArray(range)) { error('Unsupported range type: ' + range); } return range.map(function(v) { return parseLiteral(v, scope); }); } function parseData$1(data, scope) { var transforms = []; if (data.transform) { data.transform.forEach(function(tx) { transforms.push(parseTransform(tx, scope)); }); } if (data.on) { data.on.forEach(function(on) { parseTrigger(on, scope, data.name); }); } scope.addDataPipeline(data.name, analyze(data, scope, transforms)); } /** * Analyze a data pipeline, add needed operators. */ function analyze(data, scope, ops) { // POSSIBLE TODOs: // - error checking for treesource on tree operators (BUT what if tree is upstream?) // - this is local analysis, perhaps some tasks better for global analysis... var output = [], source = null, modify = false, generate = false, upstream, i, n, t, m; if (data.values) { // hard-wired input data set output.push(source = collect({$ingest: data.values, $format: data.format})); } else if (data.url) { // load data from external source output.push(source = collect({$request: data.url, $format: data.format})); } else if (data.source) { // derives from another data set upstream = scope.getData(data.source); source = upstream.output; output.push(null); // populate later } // scan data transforms, add collectors as needed for (i=0, n=ops.length; i<n; ++i) { t = ops[i]; m = t.metadata; if (!source && !m.source) { output.push(source = collect()); } output.push(t); if (m.generates) generate = true; if (m.modifies && !generate) modify = true; if (m.source) source = t; else if (m.changes) source = null; } if (upstream) { output[0] = Relay$1({derive: modify, pulse: ref(upstream.output)}); if (modify) output.splice(1, 0, collect()); // collect derived tuples } if (!source) output.push(collect()); output.push(Sieve$1({})); return output; } function collect(values) { var s = Collect$1({}, values); return s.metadata = {source: true}, s; } function axisConfig(spec, scope) { var config = scope.config, orient = spec.orient, xy = (orient === Top || orient === Bottom) ? config.axisX : config.axisY, or = config['axis' + orient[0].toUpperCase() + orient.slice(1)], band = scope.scaleType(spec.scale) === 'band' && config.axisBand; return (xy || or || band) ? extend({}, config.axis, xy, or, band) : config.axis; } function axisDomain(spec, config, userEncode, dataRef) { var orient = spec.orient, zero = {value: 0}, encode = {}, enter, update, u, u2, v; encode.enter = enter = { opacity: zero, stroke: {value: config.tickColor}, strokeWidth: {value: config.tickWidth} }; encode.exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; (orient === Top || orient === Bottom) ? (u = 'x', v = 'y') : (u = 'y', v = 'x'); u2 = u + '2', enter[v] = zero; update[u] = enter[u] = position(spec, 0); update[u2] = enter[u2] = position(spec, 1); return guideMark(RuleMark, AxisDomainRole, null, dataRef, encode, userEncode); } function position(spec, pos) { return {scale: spec.scale, range: pos}; } function axisGrid(spec, config, userEncode, dataRef) { var orient = spec.orient, vscale = spec.gridScale, sign = (orient === Left || orient === Top) ? 1 : -1, offset = sign * spec.offset || 0, zero = {value: 0}, encode = {}, enter, exit, update, tickPos, u, v, v2, s; encode.enter = enter = { opacity: zero, stroke: {value: config.gridColor}, strokeWidth: {value: config.gridWidth}, strokeDash: {value: config.gridDash} }; encode.exit = exit = { opacity: zero }; encode.update = update = { opacity: {value: config.gridOpacity} }; tickPos = { scale: spec.scale, field: Value, band: config.bandPosition, round: config.tickRound, extra: config.tickExtra }; (orient === Top || orient === Bottom) ? (u = 'x', v = 'y', s = 'height') : (u = 'y', v = 'x', s = 'width'); v2 = v + '2', update[u] = enter[u] = exit[u] = tickPos; if (vscale) { enter[v] = {scale: vscale, range: 0, mult: sign, offset: offset}; update[v2] = enter[v2] = {scale: vscale, range: 1, mult: sign, offset: offset}; } else { enter[v] = {value: offset}; update[v2] = enter[v2] = {signal: s, mult: sign, offset: offset}; } return guideMark(RuleMark, AxisGridRole, Value, dataRef, encode, userEncode); } function axisTicks(spec, config, userEncode, dataRef, size) { var orient = spec.orient, sign = (orient === Left || orient === Top) ? -1 : 1, zero = {value: 0}, encode = {}, enter, exit, update, tickSize, tickPos; encode.enter = enter = { opacity: zero, stroke: {value: config.tickColor}, strokeWidth: {value: config.tickWidth} }; encode.exit = exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; tickSize = encoder(size); tickSize.mult = sign; tickPos = { scale: spec.scale, field: Value, band: config.bandPosition, round: config.tickRound, extra: config.tickExtra }; if (orient === Top || orient === Bottom) { update.y = enter.y = zero; update.y2 = enter.y2 = tickSize; update.x = enter.x = exit.x = tickPos; } else { update.x = enter.x = zero; update.x2 = enter.x2 = tickSize; update.y = enter.y = exit.y = tickPos; } return guideMark(RuleMark, AxisTickRole, Label, dataRef, encode, userEncode); } function axisLabels(spec, config, userEncode, dataRef, size) { var orient = spec.orient, sign = (orient === Left || orient === Top) ? -1 : 1, pad = spec.labelPadding != null ? spec.labelPadding : config.labelPadding, zero = {value: 0}, encode = {}, enter, exit, update, tickSize, tickPos; encode.enter = enter = { opacity: zero, fill: {value: config.labelColor}, font: {value: config.labelFont}, fontSize: {value: config.labelFontSize}, text: {field: Label} }; encode.exit = exit = { opacity: zero }; encode.update = update = { opacity: {value: 1} }; tickSize = encoder(size); tickSize.mult = sign; tickSize.offset = encoder(pad); tickSize.offset.mult = sign; tickPos = { scale: spec.scale, field: Value, band: 0.5 }; if (orient === Top || orient === Bottom) { update.y = enter.y = tickSize; update.x = enter.x = exit.x = tickPos; update.align = {value: 'center'}; update.baseline = {value: orient === Top ? 'bottom' : 'top'}; } else { update.x = enter.x = tickSize; update.y = enter.y = exit.y = tickPos; update.align = {value: orient === Right ? 'left' : 'right'}; update.baseline = {value: 'middle'}; } return guideMark(TextMark, AxisLabelRole, Label, dataRef, encode, userEncode); } function axisTitle(spec, config, userEncode, dataRef) { var orient = spec.orient, sign = (orient === Left || orient === Top) ? -1 : 1, horizontal = (orient === Top || orient === Bottom), encode = {}, update, titlePos; encode.enter = { opacity: {value: 0}, fill: {value: config.titleColor}, font: {value: config.titleFont}, fontSize: {value: config.titleFontSize}, fontWeight: {value: config.titleFontWeight}, align: {value: config.titleAlign} }; encode.exit = { opacity: {value: 0} }; encode.update = update = { opacity: {value: 1}, text: {field: 'title'} }; titlePos = { scale: spec.scale, range: 0.5 }; if (horizontal) { update.x = titlePos; update.angle = {value: 0}; update.baseline = {value: orient === Top ? 'bottom' : 'top'}; } else { update.y = titlePos; update.angle = {value: sign * 90}; update.baseline = {value: 'bottom'}; } if (config.titleAngle != null) { update.angle = {value: config.titleAngle}; } if (config.titleBaseline != null) { update.baseline = {value: config.titleBaseline}; } if (config.titleX != null) { update.x = {value: config.titleX}; } else if (horizontal && !has(userEncode, 'x')) { encode.enter.auto = {value: true} } if (config.titleY != null) { update.y = {value: config.titleY}; } else if (!horizontal && !has(userEncode, 'y')) { encode.enter.auto = {value: true} } return guideMark(TextMark, AxisTitleRole, null, dataRef, encode, userEncode); } function parseAxis(spec, scope) { var config = axisConfig(spec, scope), name = spec.name || undefined, encode = spec.encode || {}, interactive = !!spec.interactive, datum, dataRef, ticksRef, size, group, axisEncode, children; // single-element data source for axis group datum = { orient: spec.orient, tick: spec.tick != null ? !!spec.tick : config.tickDefault, label: spec.label != null ? !!spec.label : config.labelDefault, grid: spec.grid != null ? !!spec.grid : config.gridDefault, domain: spec.domain != null ? !!spec.domain : config.domainDefault, title: spec.title }; dataRef = ref(scope.add(Collect$1({}, [datum]))); // encoding properties for axis group item axisEncode = extendEncode({ update: { range: {expr: 'abs(span(range("' + spec.scale + '")))'}, offset: encoder(spec.offset || 0), position: encoder(spec.position || 0), titlePadding: encoder(spec.titlePadding || config.titlePadding), minExtent: encoder(spec.minExtent || config.minExtent), maxExtent: encoder(spec.maxExtent || config.maxExtent) } }, encode.axis); // data source for axis ticks ticksRef = ref(scope.add(AxisTicks$1({ scale: scope.scaleRef(spec.scale), extra: config.tickExtra, count: scope.property(spec.tickCount), values: scope.property(spec.values), formatSpecifier: scope.property(spec.format) }))); // generate axis marks children = []; // include axis gridlines if requested if (datum.grid) { children.push(axisGrid(spec, config, encode.grid, ticksRef)); } // include axis ticks if requested if (datum.tick) { size = spec.tickSize != null ? spec.tickSize : config.tickSize; children.push(axisTicks(spec, config, encode.ticks, ticksRef, size)); } // include axis labels if requested if (datum.label) { size = datum.tick ? size : 0; children.push(axisLabels(spec, config, encode.labels, ticksRef, size)); } // include axis domain path if requested if (datum.domain) { children.push(axisDomain(spec, config, encode.domain, dataRef)); } // include axis title if defined if (datum.title) { children.push(axisTitle(spec, config, encode.title, dataRef)); } // build axis specification group = guideGroup(AxisRole$1, name, dataRef, interactive, axisEncode, children); if (spec.zindex) group.zindex = spec.zindex; // parse axis specification return parseMark(group, scope); } function parseSpec(spec, scope, preprocessed) { var signals = array$1(spec.signals); if (!preprocessed) signals.forEach(function(_) { parseSignal(_, scope); }); array$1(spec.projections).forEach(function(_) { parseProjection(_, scope); }); array$1(spec.data).forEach(function(_) { parseData$1(_, scope); }); array$1(spec.scales).forEach(function(_) { parseScale(_, scope); }); signals.forEach(function(_) { parseSignalUpdates(_, scope); }); scope.parseLambdas(); array$1(spec.axes).forEach(function(_) { parseAxis(_, scope); }); array$1(spec.marks).forEach(function(_) { parseMark(_, scope); }); array$1(spec.legends).forEach(function(_) { parseLegend(_, scope); }); return scope; } var defined = toSet(['width', 'height', 'padding']); function parseView(spec, scope) { var op, input, encode, parent, root; scope.background = spec.background || scope.config.background; root = ref(scope.root = scope.add(operator())); scope.addSignal('width', spec.width || -1); scope.addSignal('height', spec.height || -1); scope.addSignal('padding', parsePadding(spec.padding)); array$1(spec.signals).forEach(function(_) { if (!defined[_.name]) parseSignal(_, scope); }); // Store root group item input = scope.add(Collect$1()); // Encode root group item encode = extendEncode({ enter: { x: {value: 0}, y: {value: 0} }, update: { width: {signal: 'width'}, height: {signal: 'height'} } }, spec.encode); encode = scope.add(Encode$1( encoders(encode, GroupMark, FrameRole$1, scope, {pulse: ref(input)})) ); // Perform view layout parent = scope.add(ViewLayout$1({ legendMargin: scope.config.legendMargin, autosize: spec.autosize || scope.config.autosize, mark: root, pulse: ref(encode) })); // Parse remainder of specification scope.pushState(ref(encode), ref(parent)); parseSpec(spec, scope, true); // Bound / render / sieve root item op = scope.add(Bound$1({mark: root, pulse: ref(parent)})); op = scope.add(Render$1({pulse: ref(op)})); op = scope.add(Sieve$1({pulse: ref(op)})); // Track metadata for root item scope.addData('root', new DataScope(scope, input, input, op)); return scope; } function Scope(config) { this.config = config; this.bindings = []; this.field = {}; this.signals = {}; this.lambdas = {}; this.scales = {}; this.events = {}; this.data = {}; this.streams = []; this.updates = []; this.operators = []; this.background = null; this._id = 0; this._subid = 0; this._nextsub = [0]; this._parent = []; this._encode = []; this._markpath = []; } function Subscope(scope) { this.config = scope.config; this.field = Object.create(scope.field); this.signals = Object.create(scope.signals); this.lambdas = Object.create(scope.lambdas); this.scales = Object.create(scope.scales); this.events = Object.create(scope.events); this.data = Object.create(scope.data); this.streams = []; this.updates = []; this.operators = []; this._id = 0; this._subid = ++scope._nextsub[0]; this._nextsub = scope._nextsub; this._parent = scope._parent.slice(); this._encode = scope._encode.slice(); this._markpath = scope._markpath; } var prototype$70 = Scope.prototype = Subscope.prototype; // ---- prototype$70.fork = function() { return new Subscope(this); }; prototype$70.toRuntime = function() { return this.finish(), { background: this.background, operators: this.operators, streams: this.streams, updates: this.updates, bindings: this.bindings }; }; prototype$70.id = function() { return (this._subid ? this._subid + ':' : 0) + this._id++; }; prototype$70.add = function(op) { this.operators.push(op); op.id = this.id(); // if pre-registration references exist, resolve them now if (op.refs) { op.refs.forEach(function(ref) { ref.$ref = op.id; }); op.refs = null; } return op; }; prototype$70.addStream = function(stream) { return this.streams.push(stream), stream.id = this.id(), stream; }; prototype$70.addUpdate = function(update) { return this.updates.push(update), update; }; // Apply metadata prototype$70.finish = function() { var name, ds; // annotate root if (this.root) this.root.root = true; // annotate signals for (name in this.signals) { this.signals[name].signal = name; } // annotate scales for (name in this.scales) { this.scales[name].scale = name; } // annotate data sets function annotate(op, name, type) { var data, list; if (op) { data = op.data || (op.data = {}); list = data[name] || (data[name] = []); list.push(type); } } for (name in this.data) { ds = this.data[name]; annotate(ds.input, name, 'input'); annotate(ds.output, name, 'output'); annotate(ds.values, name, 'values'); for (var field in ds.index) { annotate(ds.index[field], name, 'index:' + field); } } return this; }; // ---- prototype$70.pushState = function(encode, parent) { this._encode.push(ref(this.add(Sieve$1({pulse: encode})))); this._parent.push(parent); this._markpath.push(-1); }; prototype$70.popState = function() { this._parent.pop(); this._encode.pop(); this._markpath.pop(); }; prototype$70.parent = function() { return peek(this._parent); }; prototype$70.encode = function() { return peek(this._encode); }; prototype$70.markpath = function() { var p = this._markpath; return ++p[p.length-1], p.slice(); }; // ---- prototype$70.fieldRef = function(field, name) { if (isString(field)) return fieldRef(field, name); if (!field.signal) { error('Unsupported field reference: ' + JSON.stringify(field)); } var s = field.signal, f = this.field[s], params; if (!f) { // TODO: replace with update signalRef? params = {name: this.signalRef(s)} if (name) params.as = name; this.field[s] = f = ref(this.add(Field$1(params))); } return f; }; prototype$70.compareRef = function(cmp) { function check(_) { return isSignal(_) ? (signal = true, ref(sig[_.signal])) : _; } var sig = this.signals, signal = false, fields = array$1(cmp.field).map(check), orders = array$1(cmp.order).map(check); return signal ? ref(this.add(Compare$1({fields: fields, orders: orders}))) : compareRef(fields, orders); }; prototype$70.keyRef = function(fields) { function check(_) { return isSignal(_) ? (signal = true, ref(sig[_.signal])) : _; } var sig = this.signals, signal = false; fields = array$1(fields).map(check); return signal ? ref(this.add(Key$1({fields: fields}))) : keyRef(fields); }; prototype$70.sortRef = function(sort) { if (!sort) return sort; // including id ensures stable sorting // TODO review? enable multi-field sorts? var a = [aggrField(sort.op, sort.field), '_id'], o = sort.order || Ascending; return o.signal ? ref(this.add(Compare$1({ fields: a, orders: [o = this.signalRef(o.signal), o] }))) : compareRef(a, [o, o]); }; // ---- prototype$70.event = function(source, type) { var key = source + ':' + type; if (!this.events[key]) { var id = this.id(); this.streams.push({ id: id, source: source, type: type }); this.events[key] = id; } return this.events[key]; }; // ---- prototype$70.addSignal = function(name, value) { if (this.signals.hasOwnProperty(name)) { error('Duplicate signal name: ' + name); } var op = value instanceof Entry ? value : this.add(operator(value)); return this.signals[name] = op; }; prototype$70.getSignal = function(name) { if (!this.signals[name]) { error('Unrecognized signal name: ' + name); } return this.signals[name]; }; prototype$70.signalRef = function(s) { if (this.signals[s]) { return ref(this.signals[s]); } else if (!this.lambdas[s]) { this.lambdas[s] = this.add(operator(null)); } return ref(this.lambdas[s]); }; prototype$70.parseLambdas = function() { var code = Object.keys(this.lambdas); for (var i=0, n=code.length; i<n; ++i) { var s = code[i], e = parseExpression(s, this), op = this.lambdas[s]; op.params = e.$params; op.update = e.$expr; } }; prototype$70.property = function(spec) { return spec && spec.signal ? this.signalRef(spec.signal) : spec; }; prototype$70.addBinding = function(name, bind) { if (!this.bindings) error('Nested signals do not support binding.'); this.bindings.push(extend({signal: name}, bind)); }; // ---- prototype$70.addScaleProj = function(name, transform) { if (this.scales.hasOwnProperty(name)) { error('Duplicate scale or projection name: ' + name); } this.scales[name] = this.add(transform); } prototype$70.addScale = function(name, params) { this.addScaleProj(name, Scale$1(params)); }; prototype$70.addProjection = function(name, params) { this.addScaleProj(name, Projection$1(params)); }; prototype$70.getScale = function(name) { if (!this.scales[name]) { error('Unrecognized scale name: ' + name); } return this.scales[name]; }; prototype$70.projectionRef = prototype$70.scaleRef = function(name) { return ref(this.getScale(name)); }; prototype$70.projectionType = prototype$70.scaleType = function(name) { return this.getScale(name).params.type; }; // ---- prototype$70.addData = function(name, dataScope) { if (this.data.hasOwnProperty(name)) { error('Duplicate data set name: ' + name); } this.data[name] = dataScope; }; prototype$70.getData = function(name) { if (!this.data[name]) { error('Undefined data set name: ' + name); } return this.data[name]; }; prototype$70.addDataPipeline = function(name, entries) { if (this.data.hasOwnProperty(name)) { error('Duplicate data set name: ' + name); } this.addData(name, DataScope.fromEntries(this, entries)); }; function defaults(userConfig) { var config = defaults$1(), key; for (key in userConfig) { config[key] = isObject(config[key]) ? extend(config[key], userConfig[key]) : config[key] = userConfig[key]; } return config; } /** * Standard configuration defaults for Vega specification parsing. * Users can provide their own (sub-)set of these default values * by passing in a config object to the top-level parse method. */ function defaults$1() { return { // default for automatic sizing; options: none, pad, fit autosize: 'pad', // default view background color // covers the entire view component background: null, // defaults for top-level group marks // accepts mark properties (fill, stroke, etc) // covers the data rectangle within group width/height group: null, // defaults for basic mark types // each subset accepts mark properties (fill, stroke, etc) mark: { arc: { fill: 'steelblue' }, area: { fill: 'steelblue' }, image: null, line: { stroke: 'steelblue' }, path: { stroke: 'steelblue' }, rect: { fill: 'steelblue' }, rule: { stroke: '#000' }, shape: { stroke: 'steelblue' }, symbol: { fill: 'steelblue', size: 64 }, text: { fill: '#000', font: 'sans-serif', fontSize: 11 } }, // defaults for axes axis: { minExtent: 0, maxExtent: 200, bandPosition: 0.5, domainDefault: true, domainWidth: 1, domainColor: '#000', gridDefault: false, gridWidth: 1, gridColor: '#ddd', gridDash: [], gridOpacity: 1, labelDefault: true, labelColor: '#000', labelFont: 'sans-serif', labelFontSize: 10, labelPadding: 2, tickDefault: true, tickRound: true, tickSize: 5, tickWidth: 1, tickColor: '#000', titleAlign: 'center', titlePadding: 2, titleColor: '#000', titleFont: 'sans-serif', titleFontSize: 11, titleFontWeight: 'bold' }, // defaults for legends legend: { orient: 'right', offset: 18, padding: 0, entryPadding: 5, titlePadding: 5, gradientWidth: 100, gradientHeight: 20, gradientStrokeColor: '#ddd', gradientStrokeWidth: 0, gradientLabelBaseline: 'top', gradientLabelOffset: 2, labelColor: '#000', labelFontSize: 10, labelFont: 'sans-serif', labelAlign: 'left', labelBaseline: 'middle', labelOffset: 8, symbolType: 'circle', symbolSize: 100, symbolColor: '#888', symbolStrokeWidth: 1.5, titleColor: '#000', titleFont: 'sans-serif', titleFontSize: 11, titleFontWeight: 'bold', titleAlign: 'left', titleBaseline: 'top' }, // defaults for scale ranges range: { category: [ '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf' ], symbol: [ 'circle', 'square', 'triangle-up', 'cross', 'diamond', 'triangle-right', 'triangle-down', 'triangle-left' ] } }; } function parse$2(spec, config) { return parseView(spec, new Scope(defaults(config || spec.config))) .toRuntime(); } /** * Parse an expression given the argument signature and body code. */ function expression$1(args, code, ctx) { // wrap code in return statement if expression does not terminate if (code[code.length-1] !== ';') { code = 'return(' + code + ');'; } var fn = Function.apply(null, args.concat(code)); return ctx && ctx.functions ? fn.bind(ctx.functions) : fn; } /** * Parse an expression used to update an operator value. */ function operatorExpression(code, ctx) { return expression$1(['_'], code, ctx); } /** * Parse an expression provided as an operator parameter value. */ function parameterExpression(code, ctx) { return expression$1(['datum', '_'], code, ctx); } /** * Parse an expression applied to an event stream. */ function eventExpression(code, ctx) { return expression$1(['event'], code, ctx); } /** * Parse an expression used to handle an event-driven operator update. */ function handlerExpression(code, ctx) { return expression$1(['_', 'event'], code, ctx); } /** * Parse an expression that performs visual encoding. */ function encodeExpression(code, ctx) { return expression$1(['item', '_'], code, ctx); } /** * Parse a set of operator parameters. */ function parseParameters$1(spec, ctx, params) { params = params || {}; var key, value; for (key in spec) { value = spec[key]; if (value && value.$expr && value.$params) { // if expression, parse its parameters parseParameters$1(value.$params, ctx, params); } params[key] = isArray(value) ? value.map(function(v) { return parseParameter$2(v, ctx); }) : parseParameter$2(value, ctx); } return params; } /** * Parse a single parameter. */ function parseParameter$2(spec, ctx) { if (!spec || !isObject(spec)) return spec; for (var i=0, n=PARSERS.length, p; i<n; ++i) { p = PARSERS[i]; if (spec.hasOwnProperty(p.key)) { return p.parse(spec, ctx); } } return spec; } /** Reference parsers. */ var PARSERS = [ {key: '$ref', parse: getOperator}, {key: '$key', parse: getKey}, {key: '$expr', parse: getExpression}, {key: '$field', parse: getField$1}, {key: '$encode', parse: getEncode}, {key: '$compare', parse: getCompare}, {key: '$subflow', parse: getSubflow}, {key: '$itempath', parse: getItemPath} ]; /** * Resolve an operator reference. */ function getOperator(_, ctx) { return ctx.get(_.$ref) || error('Operator not defined: ' + _.$ref); } /** * Resolve an expression reference. */ function getExpression(_, ctx) { var k = 'e:' + _.$expr; return ctx.fn[k] || (ctx.fn[k] = accessor(parameterExpression(_.$expr, ctx), _.$fields, _.$name)); } /** * Resolve a key accessor reference. */ function getKey(_, ctx) { var k = 'k:' + _.$key; return ctx.fn[k] || (ctx.fn[k] = key(_.$key)); } /** * Resolve a field accessor reference. */ function getField$1(_, ctx) { var k = 'f:' + _.$field + '_' + _.$name; return ctx.fn[k] || (ctx.fn[k] = field(_.$field, _.$name)); } /** * Resolve a comparator function reference. */ function getCompare(_, ctx) { var k = 'c:' + _.$compare + '_' + _.$order; return ctx.fn[k] || (ctx.fn[k] = compare(_.$compare, _.$order)); } /** * Resolve an encode operator reference. */ function getEncode(_, ctx) { var spec = _.$encode, encode = {}, name, enc; for (name in spec) { enc = spec[name]; encode[name] = accessor(encodeExpression(enc.$expr, ctx), enc.$fields); encode[name].output = enc.$output; } return encode; } /** * Resolve a recursive subflow specification. */ function getSubflow(_, ctx) { var spec = _.$subflow; return function(dataflow, key, index, parent) { var subctx = parseDataflow(spec, ctx.fork(index)), op = subctx.get(spec.operators[0].id), p = subctx.signals.parent; if (p) p.set(parent); return op; }; } /** * Resolve an iteration index reference. */ function getItemPath(_, ctx) { return { marks: _.$itempath, items: ctx.itempath, context: ctx }; } /** * Parse a dataflow operator. */ function parseOperator(spec, ctx) { if (spec.type === 'Operator' || !spec.type) { ctx.operator(spec, spec.update ? operatorExpression(spec.update, ctx) : null); } else { ctx.transform(spec, spec.type); } } /** * Parse and assign operator parameters. */ function parseOperatorParameters(spec, ctx) { var op, params; if (spec.params) { if (!(op = ctx.get(spec.id))) { error('Invalid operator id: ' + spec.id); } params = parseParameters$1(spec.params, ctx); ctx.dataflow.connect(op, op.parameters(params)); } } /** * Parse an event stream specification. */ function parseStream$3(spec, ctx) { var filter = spec.filter != null ? eventExpression(spec.filter, ctx) : undefined, stream = spec.stream != null ? ctx.get(spec.stream) : undefined, args; if (spec.source) { stream = ctx.events(spec.source, spec.type, filter); } else if (spec.merge) { args = spec.merge.map(ctx.get.bind(ctx)); stream = args[0].merge.apply(args[0], args.slice(1)); } if (spec.between) { args = spec.between.map(ctx.get.bind(ctx)); stream = stream.between(args[0], args[1]); } if (spec.filter) { stream = stream.filter(filter); } if (spec.throttle != null) { stream = stream.throttle(+spec.throttle); } if (spec.debounce != null) { stream = stream.debounce(+spec.debounce); } if (stream == null) { error('Invalid stream definition: ' + JSON.stringify(spec)); } if (spec.consume) stream.consume(true); ctx.stream(spec, stream); } /** * Parse an event-driven operator update. */ function parseUpdate$1(spec, ctx) { var source = ctx.get(spec.source), target = null, update = spec.update, params = undefined; if (!source) error('Source not defined: ' + spec.source); if (spec.target && spec.target.$expr) { target = eventExpression(spec.target.$expr, ctx); } else { target = ctx.get(spec.target); } if (update && update.$expr) { if (update.$params) { params = parseParameters$1(update.$params, ctx); } update = handlerExpression(update.$expr, ctx); } ctx.update(spec, source, target, update, params); } /** * Parse a serialized dataflow specification. */ function parseDataflow(spec, ctx) { var operators = spec.operators || []; // parse background if (spec.background) { ctx.background = spec.background; } // parse operators operators.forEach(function(entry) { parseOperator(entry, ctx); }); // parse operator parameters operators.forEach(function(entry) { parseOperatorParameters(entry, ctx); }); // parse streams (spec.streams || []).forEach(function(entry) { parseStream$3(entry, ctx); }); // parse updates (spec.updates || []).forEach(function(entry) { parseUpdate$1(entry, ctx); }); return ctx; } /** * Context objects store the current parse state. * Enables lookup of parsed operators, event streams, accessors, etc. * Provides a 'fork' method for creating child contexts for subflows. */ function context$2(df, transforms, functions) { return new Context(df, transforms, functions); } function Context(df, transforms, functions) { this.dataflow = df; this.transforms = transforms; this.events = df.events.bind(df); this.signals = {}; this.scales = {}; this.nodes = {}; this.data = {}; this.fn = {}; this.itempath = []; if (functions) { this.functions = Object.create(functions); this.functions.context = this; } } function ContextFork(ctx, index) { this.dataflow = ctx.dataflow; this.transforms = ctx.transforms; this.functions = ctx.functions; this.events = ctx.events; this.signals = Object.create(ctx.signals); this.scales = Object.create(ctx.scales); this.nodes = Object.create(ctx.nodes); this.data = Object.create(ctx.data); this.fn = Object.create(ctx.fn); this.itempath = ctx.itempath.concat(index); if (ctx.functions) { this.functions = Object.create(ctx.functions); this.functions.context = this; } } Context.prototype = ContextFork.prototype = { fork: function(index) { var ctx = new ContextFork(this, index); (this.subcontext || (this.subcontext = [])).push(ctx); return ctx; }, get: function(id) { return this.nodes[id]; }, set: function(id, node) { return this.nodes[id] = node; }, add: function(spec, op) { var ctx = this, df = ctx.dataflow, data; ctx.set(spec.id, op); if (spec.type === 'Collect' && (data = spec.value)) { if (data.$ingest) { df.ingest(op, data.$ingest, data.$format); } else if (data.$request) { df.request(op, data.$request, data.$format); } else { df.pulse(op, df.changeset().insert(data)); } } if (spec.root) { ctx.root = op; } if (spec.parent) { var p = ctx.get(spec.parent.$ref); df.connect(p, [op]); op.targets().add(p); } if (spec.signal) { ctx.signals[spec.signal] = op; } if (spec.scale) { ctx.scales[spec.scale] = op; } if (spec.data) { for (var name in spec.data) { data = ctx.data[name] || (ctx.data[name] = {}); spec.data[name].forEach(function(role) { data[role] = op; }); } } }, operator: function(spec, update, params) { this.add(spec, this.dataflow.add(spec.value, update, params, spec.react)); }, transform: function(spec, type, params) { this.add(spec, this.dataflow.add(this.transforms[type], params)); }, stream: function(spec, stream) { this.set(spec.id, stream); }, update: function(spec, stream, target, update, params) { this.dataflow.on(stream, target, update, params, spec.options); } }; function runtime(view, spec, functions) { var fn = functions || extendedFunctions; return parseDataflow(spec, context$2(view, transforms, fn)); } function resizer(view, field) { var op = view.add(null, function(_) { view['_' + field] = _.size; view._autosize = view._resize = 1; }, {size: view._signals[field]} ); // set rank to ensure operator runs as soon as possible // size parameters should be reset prior to view layout return op.rank = 0, op; } function autosize(viewWidth, viewHeight, width, height, origin) { this.runAfter(function(view) { var rerun = 0; // clear autosize flag view._autosize = 0; // width value changed: update signal, skip resize op if (view.width() !== width) { rerun = 1; view.width(width); view._resizeWidth.skip(true); } // height value changed: update signal, skip resize op if (view.height() !== height) { rerun = 1; view.height(height); view._resizeHeight.skip(true); } // view width changed: update view property, set resize flag if (view._width !== viewWidth) { view._resize = 1; view._width = viewWidth; } // view height changed: update view property, set resize flag if (view._height !== viewHeight) { view._resize = 1; view._height = viewHeight; } // origin changed: update view property, set resize flag if (view._origin[0] !== origin[0] || view._origin[1] !== origin[1]) { view._resize = 1; view._origin = origin; } // run dataflow on width/height signal change if (rerun) view.run('enter'); }); } /** * Get or set the current signal state. If an input object is provided, * all property on that object will be assigned to signals of this view, * and the run method will be invoked. If no argument is provided, * returns a hash of all current signal values. * @param {object} [state] - The state vector to set. * @return {object|View} - If invoked with arguments, returns the * current signal state. Otherwise returns this View instance. */ function state(state) { var key, skip; if (arguments.length) { skip = {skip: true}; for (key in state) this.signal(key, state[key], skip); return this.run(); } else { state = {}; for (key in this._signals) state[key] = this.signal(key); return state; } } /** * Create a new View instance from a Vega dataflow runtime specification. * The generated View will not immediately be ready for display. Callers * should also invoke the initialize method (e.g., to set the parent * DOM element in browser-based deployment) and then invoke the run * method to evaluate the dataflow graph. Rendering will automatically * be peformed upon dataflow runs. * @constructor * @param {object} spec - The Vega dataflow runtime specification. */ function View(spec, options) { options = options || {}; Dataflow.call(this); this.loader(options.loader || this._loader); this.logLevel(options.logLevel || 0); this._el = null; this._renderType = options.renderer || Canvas$2; this._scenegraph = new Scenegraph(); var root = this._scenegraph.root; // initialize renderer and handler this._renderer = null; this._handler = new CanvasHandler().scene(root); this._queue = null; this._eventListeners = []; // initialize dataflow graph var ctx = runtime(this, spec, options.functions); this._runtime = ctx; this._signals = ctx.signals; this._bind = spec.bindings; // initialize scenegraph if (ctx.root) ctx.root.set(root); root.source = ctx.data.root.input; this.pulse( ctx.data.root.input, this.changeset().insert(root.items) ); // initialize background color this._background = ctx.background || null; // initialize view size this._width = this.width(); this._height = this.height(); this._origin = [0, 0]; this._resize = 0; this._autosize = 1; // initialize resize operators this._resizeWidth = resizer(this, 'width'); this._resizeHeight = resizer(this, 'height'); // initialize cursor cursor(this); } var prototype$68 = inherits(View, Dataflow); // -- DATAFLOW / RENDERING ---- prototype$68.run = function(encode) { Dataflow.prototype.run.call(this, encode); var q = this._queue; if (this._resize || !q || q.length) { this.render(q); this._queue = []; } return this; }; prototype$68.render = function(update) { if (this._renderer) { if (this._resize) this._resize = 0, resizeRenderer(this); this._renderer.render(this._scenegraph.root, update); } return this; }; prototype$68.enqueue = function(items) { if (this._queue && items && items.length) { this._queue = this._queue.concat(items); } }; // -- GET / SET ---- prototype$68.signal = function(name, value, options) { var op = this._signals[name]; return arguments.length === 1 ? (op ? op.value : undefined) : this.update(op, value, options); }; prototype$68.scenegraph = function() { return this._scenegraph; }; prototype$68.background = function(_) { return arguments.length ? (this._background = _, this._resize = 1, this) : this._background; }; prototype$68.width = function(_) { return arguments.length ? this.signal('width', _) : this.signal('width'); }; prototype$68.height = function(_) { return arguments.length ? this.signal('height', _) : this.signal('height'); }; prototype$68.padding = function(_) { return arguments.length ? this.signal('padding', _) : this.signal('padding'); }; prototype$68.renderer = function(type) { if (!arguments.length) return this._renderType; if (type !== SVG && type !== None$2) type = Canvas$2; if (type !== this._renderType) { this._renderType = type; if (this._renderer) { this._renderer = this._queue = null; this.initialize(this._el); } } return this; }; // -- SIZING ---- prototype$68.autosize = autosize; // -- DATA ---- prototype$68.data = data; prototype$68.insert = insert; prototype$68.remove = remove; // -- INITIALIZATION ---- prototype$68.initialize = initialize$1; // -- HEADLESS RENDERING ---- prototype$68.toImageURL = renderToImageURL; prototype$68.toCanvas = renderToCanvas; prototype$68.toSVG = renderToSVG; // -- EVENT HANDLING ---- prototype$68.events = events$1; prototype$68.finalize = finalize; prototype$68.hover = hover; // -- INPUT BINDING --- prototype$68.bind = bind$1; // -- SAVE / RESTORE STATE ---- prototype$68.state = state; transform('Bound', Bound); transform('Mark', Mark); transform('Render', Render); transform('ViewLayout', ViewLayout); /* eslint-disable no-unused-vars */ exports.version = version; exports.Dataflow = Dataflow; exports.EventStream = EventStream; exports.Parameters = Parameters; exports.Pulse = Pulse; exports.MultiPulse = MultiPulse; exports.Operator = Operator; exports.Transform = Transform; exports.changeset = changeset; exports.ingest = ingest; exports.register = register; exports.definition = definition; exports.definitions = definitions; exports.transform = transform; exports.transforms = transforms; exports.tupleid = tupleid; exports.textMetrics = textMetrics; exports.scale = scale$1; exports.scheme = getScheme; exports.projection = projection$1; exports.View = View; exports.parse = parse$2; exports.runtime = parseDataflow; exports.runtimeContext = context$2; exports.bin = bin$1; exports.bootstrapCI = bootstrapCI; exports.randomInteger = integer; exports.randomKDE = randomKDE; exports.randomMixture = randomMixture; exports.randomNormal = randomNormal; exports.randomUniform = randomUniform; exports.quartiles = quartiles; exports.accessor = accessor; exports.accessorName = accessorName; exports.accessorFields = accessorFields; exports.id = id; exports.identity = identity$1; exports.zero = zero; exports.one = one; exports.truthy = truthy; exports.falsy = falsy; exports.logger = logger; exports.None = None; exports.Warn = Warn; exports.Info = Info; exports.Debug = Debug; exports.array = array$1; exports.compare = compare; exports.constant = constant$1; exports.error = error; exports.extend = extend; exports.extentIndex = extentIndex; exports.field = field; exports.inherits = inherits; exports.isArray = isArray; exports.isFunction = isFunction; exports.isNumber = isNumber; exports.isObject = isObject; exports.isString = isString; exports.key = key; exports.merge = merge$1; exports.pad = pad; exports.peek = peek; exports.repeat = repeat; exports.splitAccessPath = splitAccessPath; exports.stringValue = $; exports.toSet = toSet; exports.truncate = truncate; exports.visitArray = visitArray; exports.loader = loader; exports.read = read; exports.inferType = inferType; exports.inferTypes = inferTypes; exports.typeParsers = typeParsers; exports.formats = formats$1; Object.defineProperty(exports, '__esModule', { value: true }); })));
EvergreenApp/Styles/gardenStyles.js
tr3v0r5/evergreen
import React from 'react'; import { StyleSheet} from 'react-native'; var plantHeightandWidth = 70; export default StyleSheet.create({ gardenIcon:{ position:'absolute', right:20, marginTop: 30 }, gardenHeader:{ justifyContent:'center', alignItems:'center', marginTop:20 }, gardenText:{ color:'#27ae60', fontFamily: 'HelveticaNeue-Thin', fontSize:30, textAlign:'center' }, gardenGrid:{ marginTop:40, justifyContent:'center', alignItems:'center', flexDirection:'row', flexWrap:'wrap' }, zoneContainer: { width: 150, height: 150, borderRadius:10, backgroundColor:'transparent', justifyContent: 'flex-end', }, zoneName:{ fontFamily: 'HelveticaNeue', fontSize:20, marginBottom:15, padding:10, color:'white' }, plantContainer:{ padding:10 }, plantImageContainer:{ width:plantHeightandWidth, height:plantHeightandWidth, borderRadius: plantHeightandWidth/2, }, plantName:{ fontFamily:'HelveticaNeue-Thin', textAlign:'center' }, plantGrid:{ marginLeft:10, flexDirection:'row', flexWrap:'wrap' }, plantAddIcon:{ display: 'flex', alignSelf: 'flex-start', } });
node_modules/react-router/es6/Lifecycle.js
dulik06/ReduxStarter
import warning from './routerWarning'; import React from 'react'; import invariant from 'invariant'; var object = React.PropTypes.object; /** * The Lifecycle mixin adds the routerWillLeave lifecycle method to a * component that may be used to cancel a transition or prompt the user * for confirmation. * * On standard transitions, routerWillLeave receives a single argument: the * location we're transitioning to. To cancel the transition, return false. * To prompt the user for confirmation, return a prompt message (string). * * During the beforeunload event (assuming you're using the useBeforeUnload * history enhancer), routerWillLeave does not receive a location object * because it isn't possible for us to know the location we're transitioning * to. In this case routerWillLeave must return a prompt message to prevent * the user from closing the window/tab. */ var Lifecycle = { contextTypes: { history: object.isRequired, // Nested children receive the route as context, either // set by the route component using the RouteContext mixin // or by some other ancestor. route: object }, propTypes: { // Route components receive the route object as a prop. route: object }, componentDidMount: function componentDidMount() { process.env.NODE_ENV !== 'production' ? warning(false, 'the `Lifecycle` mixin is deprecated, please use `context.router.setRouteLeaveHook(route, hook)`. http://tiny.cc/router-lifecyclemixin') : void 0; !this.routerWillLeave ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin requires you to define a routerWillLeave method') : invariant(false) : void 0; var route = this.props.route || this.context.route; !route ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The Lifecycle mixin must be used on either a) a <Route component> or ' + 'b) a descendant of a <Route component> that uses the RouteContext mixin') : invariant(false) : void 0; this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(route, this.routerWillLeave); }, componentWillUnmount: function componentWillUnmount() { if (this._unlistenBeforeLeavingRoute) this._unlistenBeforeLeavingRoute(); } }; export default Lifecycle;
src/components/generate-key/genKeyRoot.js
mailvelope/mailvelope
/** * Copyright (C) 2019 Mailvelope GmbH * Licensed under the GNU Affero General Public License version 3 */ import React from 'react'; import ReactDOM from 'react-dom'; import * as l10n from '../../lib/l10n'; import GenKey from './GenKey'; document.addEventListener('DOMContentLoaded', init); l10n.mapToLocal(); function init() { const query = new URLSearchParams(document.location.search); // component id const id = query.get('id') || ''; // component used as a container (client API) const root = document.createElement('div'); ReactDOM.render(<GenKey id={id} />, document.body.appendChild(root)); }
src/index.js
ArtixZ/LyingMan2
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import App from './components/app'; import reducers from './reducers'; const createStoreWithMiddleware = applyMiddleware()(createStore); ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <App /> </Provider> , document.querySelector('.container'));
public/vendor/datatables/media/js/jquery.js
maldicion069/HBPWebNodeJs
/*! 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});
admin/client/components/Forms/InvalidFieldType.js
pswoodworth/keystone
import React from 'react'; module.exports = React.createClass({ displayName: 'InvalidFieldType', propTypes: { path: React.PropTypes.string, type: React.PropTypes.string, }, render () { return <div className="alert alert-danger">Invalid field type <strong>{this.props.type}</strong> at path <strong>{this.props.path}</strong></div>; }, });
app/components/Filters/FilterSelect.js
juanda99/arasaac-frontend
import React from 'react' import PropTypes from 'prop-types' import SelectField from 'material-ui/SelectField' import MenuItem from 'material-ui/MenuItem' import muiThemeable from 'material-ui/styles/muiThemeable' import IconButton from 'material-ui/IconButton' import ActionHide from 'material-ui/svg-icons/action/highlight-off' import { FormattedMessage } from 'react-intl' import { List } from 'immutable' import styles from './styles' import messages from './messages' class FilterSelect extends React.Component { handleChange = (event, index, values) => { if (this.props.multiple) { this.props.onChange(this.props.filterType, List(values)) } else { this.props.onChange(this.props.filterType, values) } } handleReset = () => { if (this.props.multiple) { this.props.onChange(this.props.filterType, List()) } else { this.props.onChange(this.props.filterType, '') } } menuItems(values, items) { const { multiple } = this.props return items.map((item) => multiple ? ( <MenuItem key={item.primaryText} insetChildren={true} checked={values && values.includes(item.value)} {...item} /> ) : ( <MenuItem key={item.primaryText} {...item} /> ) ) } render() { // filterType will be used also as id, see https://github.com/callemall/material-ui/issues/6834 const { values, items, floatingLabelText, multiple, filterType, muiTheme, } = this.props let multipleProps = {} // useful for defining a selectionRenderer: if (multiple) multipleProps = { multiple } return ( <span style={styles.span}> <IconButton className="btnDeleteFilter" iconStyle={{ color: muiTheme.palette.accent1Color, verticalAlign: 'bottom', }} onClick={this.handleReset} tooltip={<FormattedMessage {...messages.filterTooltip} />} > <ActionHide /> </IconButton> <SelectField {...multipleProps} autoWidth={true} value={values} onChange={this.handleChange} style={styles.select} maxHeight={300} menuItemStyle={{ fontSize: '14px' }} floatingLabelText={floatingLabelText} id={filterType} > {this.menuItems(values, items)} </SelectField> </span> ) } } FilterSelect.displayName = 'FilterSelect' FilterSelect.propTypes = { items: PropTypes.arrayOf( PropTypes.shape({ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) .isRequired, primaryText: PropTypes.string.isRequired, }) ).isRequired, multiple: PropTypes.bool, muiTheme: PropTypes.object, floatingLabelText: PropTypes.string.isRequired, values: PropTypes.oneOfType([ PropTypes.string, PropTypes.number, PropTypes.array, ]).isRequired, filterType: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, } export default muiThemeable()(FilterSelect)
src/routes/app/routes/tables/routes/responsive/components/ResponsiveTables.js
ahthamrin/kbri-admin2
import React from 'react'; import QueueAnim from 'rc-queue-anim'; const ResponsiveTable = () => ( <article className="article"> <h2 className="article-title">Responsive Table</h2> <div className="box box-default table-box table-responsive mdl-shadow--2dp"> <table className="mdl-data-table"> <thead> <tr> <th className="mdl-data-table__cell--non-numeric">#</th> <th className="mdl-data-table__cell--non-numeric">Code</th> <th className="mdl-data-table__cell--non-numeric">Material</th> <th>Quantity</th> <th>Unit price</th> </tr> </thead> <tbody> <tr> <td className="mdl-data-table__cell--non-numeric">1</td> <td className="mdl-data-table__cell--non-numeric">AZ90</td> <td className="mdl-data-table__cell--non-numeric">Acrylic (Transparent)</td> <td>25</td> <td>$2.90</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">2</td> <td className="mdl-data-table__cell--non-numeric">BC30</td> <td className="mdl-data-table__cell--non-numeric">Plywood (Birch)</td> <td>50</td> <td>$1.25</td> </tr> <tr> <td className="mdl-data-table__cell--non-numeric">3</td> <td className="mdl-data-table__cell--non-numeric">DL32</td> <td className="mdl-data-table__cell--non-numeric">Laminate (Gold on Blue)</td> <td>10</td> <td>$2.35</td> </tr> </tbody> </table> </div> </article> ); const FlipScroll = () => ( <article className="article"> <h2 className="article-title">Flip Scroll</h2> <div className="box box-default table-box table-flip-scroll mdl-shadow--2dp"> <table className="mdl-data-table table-bordered table-striped cf no-margin"> <thead className="cf"> <tr> <th>Code</th> <th className="numeric">Price</th> <th className="numeric">Change</th> <th className="numeric">Open</th> <th className="numeric">High</th> <th className="numeric">Low</th> <th className="numeric">Volume</th> </tr> </thead> <tbody> <tr> <td>AAC</td> <td className="numeric">$1.38</td> <td className="numeric">-0.01</td> <td className="numeric">$1.39</td> <td className="numeric">$1.39</td> <td className="numeric">$1.38</td> <td className="numeric">9,395</td> </tr> <tr> <td>AAD</td> <td className="numeric">$1.15</td> <td className="numeric"> +0.02</td> <td className="numeric">$1.14</td> <td className="numeric">$1.15</td> <td className="numeric">$1.13</td> <td className="numeric">56,431</td> </tr> <tr> <td>AAX</td> <td className="numeric">$4.00</td> <td className="numeric">-0.04</td> <td className="numeric">$4.01</td> <td className="numeric">$4.05</td> <td className="numeric">$4.00</td> <td className="numeric">90,641</td> </tr> <tr> <td>ABC</td> <td className="numeric">$3.00</td> <td className="numeric"> +0.06</td> <td className="numeric">$2.98</td> <td className="numeric">$3.00</td> <td className="numeric">$2.96</td> <td className="numeric">862,518</td> </tr> <tr> <td>ABP</td> <td className="numeric">$1.91</td> <td className="numeric">0.00</td> <td className="numeric">$1.92</td> <td className="numeric">$1.93</td> <td className="numeric">$1.90</td> <td className="numeric">595,701</td> </tr> <tr> <td>ABY</td> <td className="numeric">$0.77</td> <td className="numeric"> +0.02</td> <td className="numeric">$0.76</td> <td className="numeric">$0.77</td> <td className="numeric">$0.76</td> <td className="numeric">54,567</td> </tr> <tr> <td>ACR</td> <td className="numeric">$3.71</td> <td className="numeric"> +0.01</td> <td className="numeric">$3.70</td> <td className="numeric">$3.72</td> <td className="numeric">$3.68</td> <td className="numeric">191,373</td> </tr> <tr> <td>ADU</td> <td className="numeric">$0.72</td> <td className="numeric">0.00</td> <td className="numeric">$0.73</td> <td className="numeric">$0.74</td> <td className="numeric">$0.72</td> <td className="numeric">8,602,291</td> </tr> <tr> <td>AGG</td> <td className="numeric">$7.81</td> <td className="numeric">-0.22</td> <td className="numeric">$7.82</td> <td className="numeric">$7.82</td> <td className="numeric">$7.81</td> <td className="numeric">148</td> </tr> <tr> <td>AGK</td> <td className="numeric">$13.82</td> <td className="numeric"> +0.02</td> <td className="numeric">$13.83</td> <td className="numeric">$13.83</td> <td className="numeric">$13.67</td> <td className="numeric">846,403</td> </tr> <tr> <td>AGO</td> <td className="numeric">$3.17</td> <td className="numeric">-0.02</td> <td className="numeric">$3.11</td> <td className="numeric">$3.22</td> <td className="numeric">$3.10</td> <td className="numeric">5,416,303</td> </tr> </tbody> </table> </div> </article> ); const Page = () => ( <section className="container-fluid with-maxwidth chapter"> <QueueAnim type="bottom" className="ui-animate"> <div key="1"><ResponsiveTable /></div> <div key="2"><FlipScroll /></div> </QueueAnim> </section> ); module.exports = Page;
public/src/containers/search_bar.js
agnieszkabugla/React-Movie-Project
import React, { Component } from 'react'; import PropTypes from 'prop-types'; class SearchBar extends Component { constructor(props) { super(props); } render() { return ( <div className="jumbotron jumbotron-fluid" id="jumbotron-color"> <div className="container"> <div className="links-div"> <a href="https://www.themoviedb.org/" > <img src="../../style/TMDB.png" id="tmdb"/> </a> <a href="http://www.imdb.com/"> <img src="../../style/IMDB.png" id="imdb"/> </a> </div> <h1 className="display-3 white-color" id="h1-font">Movie Search</h1> <p className="lead white-color">This is a simple movie search. Type in a title of the movie you want to find or just a part of its title. </p> <div className="input-group mb-2 mb-sm-0"> <div className="input-group-addon" id="big-search-bar"> <i className="fa fa-video-camera" /> </div> <input className="form-control" placeholder="Movie title" onChange={this.props.onInputChange} value={this.props.value} onKeyPress={this.props.onSubmitSearch} /> </div> </div> </div> ); } } SearchBar.propTypes = { onInputChange: PropTypes.func, value: PropTypes.string, onSubmitSearch: PropTypes.func }; export default SearchBar;
app/javascript/mastodon/features/compose/components/action_bar.js
rekif/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import DropdownMenuContainer from '../../../containers/dropdown_menu_container'; import { defineMessages, injectIntl } from 'react-intl'; const messages = defineMessages({ edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' }, pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' }, preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' }, follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' }, favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' }, lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' }, blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' }, domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' }, mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' }, filters: { id: 'navigation_bar.filters', defaultMessage: 'Muted words' }, }); export default @injectIntl class ActionBar extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, intl: PropTypes.object.isRequired, }; render () { const { intl } = this.props; let menu = []; menu.push({ text: intl.formatMessage(messages.edit_profile), href: '/settings/profile' }); menu.push({ text: intl.formatMessage(messages.preferences), href: '/settings/preferences' }); menu.push({ text: intl.formatMessage(messages.pins), to: '/pinned' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.follow_requests), to: '/follow_requests' }); menu.push({ text: intl.formatMessage(messages.favourites), to: '/favourites' }); menu.push({ text: intl.formatMessage(messages.lists), to: '/lists' }); menu.push(null); menu.push({ text: intl.formatMessage(messages.mutes), to: '/mutes' }); menu.push({ text: intl.formatMessage(messages.blocks), to: '/blocks' }); menu.push({ text: intl.formatMessage(messages.domain_blocks), to: '/domain_blocks' }); menu.push({ text: intl.formatMessage(messages.filters), href: '/filters' }); return ( <div className='compose__action-bar'> <div className='compose__action-bar-dropdown'> <DropdownMenuContainer items={menu} icon='ellipsis-v' size={24} direction='right' /> </div> </div> ); } }
Libraries/Utilities/throwOnWrongReactAPI.js
disparu86/react-native
/** * Copyright (c) 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 throwOnWrongReactAPI * @flow */ 'use strict'; function throwOnWrongReactAPI(key: string) { throw new Error( `Seems you're trying to access 'ReactNative.${key}' from the 'react-native' package. Perhaps you meant to access 'React.${key}' from the 'react' package instead? For example, instead of: import React, { Component, View } from 'react-native'; You should now do: import React, { Component } from 'react'; import { View } from 'react-native'; Check the release notes on how to upgrade your code - https://github.com/facebook/react-native/releases/tag/v0.25.1 `); } module.exports = throwOnWrongReactAPI;
components/centered-map/error-message.js
sgmap/inspire
import React from 'react' import PropTypes from 'prop-types' import ErrorIcon from 'react-icons/lib/fa/times-circle' const ErrorMessage = ({small, children}) => ( <div className='container'> <div className={`icon ${small ? 'small' : ''}`}> <ErrorIcon /> </div> <div className='text'> {children} </div> <style jsx>{` @import 'colors'; .container { display: flex; align-items: center; justify-content: center; flex-direction: column; height: 100%; padding: 10px; } .icon { display: flex; flex-wrap: wrap; font-size: 102px; margin: auto; color: $red; } .small { font-size: 54px; } .text { color: $red; font-weight: 600; text-align: center; } `}</style> </div> ) ErrorMessage.propTypes = { children: PropTypes.node.isRequired, small: PropTypes.bool } ErrorMessage.defaultProps = { small: false } export default ErrorMessage
js/App/Components/Profile/SubViews/UpdatePasswordBlock.js
telldus/telldus-live-mobile-v3
/** * Copyright 2016-present Telldus Technologies AB. * * This file is part of the Telldus Live! app. * * Telldus Live! app is free : you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Telldus Live! app is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>. * */ // @flow 'use strict'; import React, { useCallback, } from 'react'; import { useSelector } from 'react-redux'; import { useIntl } from 'react-intl'; import { TitledInfoBlock, } from '../../../../BaseComponents'; import i18n from '../../../Translations/common'; import Theme from '../../../Theme'; const UpdatePasswordBlock = (props: Object): Object => { const { navigation } = props; const {layout} = useSelector((state: Object): Object => state.app); const { formatMessage } = useIntl(); const { fontSize, } = getStyles(layout); const onPress = useCallback(() => { (() => { navigation.navigate('UpdatePasswordScreen'); })(); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <TitledInfoBlock label={formatMessage(i18n.changePassword)} fontSize={fontSize} icon={'angle-right'} onPress={onPress} /> ); }; const getStyles = (appLayout: Object): Object => { const { height, width } = appLayout; const isPortrait = height > width; const deviceWidth = isPortrait ? width : height; const { fontSizeFactorEight, } = Theme.Core; const fontSize = Math.floor(deviceWidth * fontSizeFactorEight); return { fontSize, }; }; export default (React.memo<Object>(UpdatePasswordBlock): Object);
src/routes/Home/components/HomeView.js
nnti3n/YouTime
import React from 'react' import SearchBar from './SearchBar' import CommentList from './CommentList' import VideoPlayer from './VideoPlayer' import CommentBar from './CommentBar' import SuggestVideo from './SuggestVideo' const YOUTIME_API = `http://youtime.herokuapp.com` class HomeView extends React.Component { constructor (props) { super(props) this.state = { videoId : '', container: 'youtube-player', currentTime: 0, commentList: [], currentComment: [], videoRemoteId: '', seekTo: 0, suggestVideo: [] } this.commentClickHandler = this.commentClickHandler.bind(this) this.updateComment = this.updateComment.bind(this) this.postComment = this.postComment.bind(this) this.fetchVideoComment = this.fetchVideoComment.bind(this) this.SearchVideo = this.SearchVideo.bind(this) } updateComment = (currentTime) => { currentTime *= 1000; this.setState({ currentTime: currentTime, currentComment: this.state.commentList.filter((data) => { return (data.time <= currentTime) && data.time + 5000 >= currentTime }) }) } postComment = (commentObject, callback) => { var option = { method: 'POST', body: JSON.stringify(commentObject), mode: 'cors', headers: new Headers({"Content-Type": "application/json"}) } fetch(YOUTIME_API + "/video/" + this.state.videoRemoteId, option) .then(res => { if (res.ok) { res.json().then((data) => { this.setState({ commentList: data.comment }) callback(null, commentObject); }) }else{ callback("CONNECT_ERROR") } }) } fetchVideoComment(videoId) { fetch(YOUTIME_API + `/video/link?site=youtube&id=${videoId}`) .then(res => res.json()) .then((data) => { this.setState({ videoRemoteId: data.id, commentList: data.comment }) }) } fetchSuggestedVideo = (limit) => { fetch(YOUTIME_API + `/video/random?limit=${limit}`) .then(res => res.json()) .then((data) => { this.setState({ suggestVideo: data }) }) } SearchVideo = (link) => { if (link.indexOf('youtube') !== -1 || link.indexOf('youtu.be') !== -1) { var regex = /(.+(\?v=|\/))|((\?|&).+)/g var videoId = link.replace(regex, '') this.setState({ videoId: videoId, videoTime: 0 }) this.fetchVideoComment(videoId) this.fetchSuggestedVideo(4) } else { console.log('invalid url') return } } commentClickHandler = (comment) => { this.setState({ seekTo: comment.time == 0 ? 1: comment.time/1000, justSeek: true }) } videoClickHandler = (video) => { console.log(video) this.setState({ videoId: video.url.id }) this.fetchVideoComment(video.url.id) } changeJustSeek = (justSeek) => { this.setState({ justSeek: justSeek }) } render() { return ( <div> <div className='Menu u-margin-bottom--40'> <h2 className='Menu-title'>YouTime</h2> <SearchBar SearchVideo={this.SearchVideo} /> </div> <div className='ViewBox u-margin-bottom--24'> <div> <VideoPlayer videoId={this.state.videoId} container={this.state.container} updateComment={this.updateComment} seekTo={this.state.seekTo} justSeek={this.state.justSeek} changeJustSeek={this.changeJustSeek} /> <CommentBar currentComment={this.state.currentComment} currentTime={this.state.currentTime} postComment={this.postComment} /> </div> <CommentList commentList={this.state.commentList} commentClickHandler={this.commentClickHandler} /> </div> <h4 className='u-margin-bottom--12'>Suggested Videos</h4> <SuggestVideo videoList={this.state.suggestVideo} videoClickHandler={this.videoClickHandler}/> </div> ) } } HomeView.propTypes = { SearchVideo: React.PropTypes.func } export default HomeView
packages/material-ui-icons/src/AccessAlarm.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z" /></React.Fragment> , 'AccessAlarm');
web/app/pages/password.js
bitemyapp/serials
// @flow import React from 'react' import {Link} from 'react-router' import {LogoPage} from './login' import {makeUpdate} from '../data/update' import {Alerts} from '../model/alert' import {User, forgotPassword, resetPassword} from '../model/user' import {transitionTo, Routes} from '../router' export class ForgotPassword extends React.Component { constructor(props:any) { super(props) this.state = {email: "", submitted: false} } onSubmit(e:any) { e.preventDefault() var email = this.state.email this.setState({email: "", submitted: true}) forgotPassword(email) .then(function() { // done... }) return } render():React.Element { var content; if (this.state.submitted) { content = this.renderCheck() } else { content = this.renderForm() } return <LogoPage alert={this.props.alert}> {content} </LogoPage> } renderForm():React.Element { return <form onSubmit={this.onSubmit.bind(this)}> <label>Email</label> <input type="email" ref="email" name="email" value={this.state.email} onChange={e => this.setState({email: e.target.value})} /> <button>Reset Password</button> </form> } renderCheck():React.Element { return <p>We've sent you an email with a link to reset your password</p> } } export class ResetPassword extends React.Component { state: { password: string; confirm: string; }; constructor(props:any) { super(props) this.state = {password: "", confirm: ""} } onSubmit(e:any) { Alerts.clear() e.preventDefault() var password = this.state.password var confirm = this.state.confirm if (password !== confirm) { Alerts.update("error", "Passwords did not match") return } resetPassword(this.props.params.token, this.state.password) .then(() => { Alerts.update("success", "Password updated successfully", true) transitionTo(Routes.login) }) // submit the reset password event // let them know } render():React.Element { return <LogoPage alert={this.props.alert}> <form onSubmit={this.onSubmit.bind(this)}> <label>Password</label> <input type="password" value={this.state.password} onChange={e => this.setState({password: e.target.value})} /> <label>Password Confirmation</label> <input type="password" value={this.state.confirm} onChange={e => this.setState({confirm: e.target.value})} /> <div className="row"> <div className="columns small-12 medium-6"> <button className="expand" onClick={this.onSubmit.bind(this)}>Reset Password</button> </div> </div> </form> </LogoPage> } }
src/routes.js
ClaudiuCeia/mioritic
// @flow import React from 'react'; import { Router, Route } from 'react-router'; import Home from './components/Home'; import CoursePage from './components/CoursePage'; import NotFound from './components/NotFound'; const Routes = (props: any) => ( <Router {...props}> <Route path="/" component={Home} /> <Route path="/course/*" component={CoursePage} /> <Route path="*" component={NotFound} /> </Router> ); export default Routes;
src/spa/dev/js/components/workflow-state.js
MoimHossain/netcore-microservice-tutorial
import React from 'react'; const WorkflowState = (props) => ( <div className="ui ordered steps"> <div className="completed step"> <div className="content"> <div className="title">SO</div> <div className="description">Schets ontwerp</div> </div> </div> <div className="completed step"> <div className="content"> <div className="title">DO</div> <div className="description">Definitive ontwerp</div> </div> </div> <div className="active step"> <div className="content"> <div className="title">VO</div> <div className="description">Voorlopig ontwerp</div> </div> </div> <div className="active step"> <div className="content"> <div className="title">UO</div> <div className="description">U? ontwerp</div> </div> </div> </div> ); export default WorkflowState;
src/containers/App.js
DIYAbility/Capacita-Controller-Interface
import React, { Component } from 'react'; import { connect } from 'react-redux'; import ReactSuperSimpleRouter from '../components/app/ReactSuperSimpleRouter'; import AppToolbar from '../components/app/AppToolbar'; import * as page from '../constants/pages'; import { changeRoute } from '../actions/actions-app'; import SignIn from '../pages/SignIn'; import ControllerLayout from '../pages/ControllerLayout'; import Help from '../pages/Help'; import Account from '../pages/Account'; import NotFound from '../pages/NotFound'; import './App.css'; class App extends Component { render() { return ( <div className="capacita-app"> <ReactSuperSimpleRouter route={this.props.app.route} onChange={this.onRouteChange.bind(this)} unsaved={this.props.layout.ui.dirty} /> <AppToolbar {...this.props} /> {this.renderPage()} </div> ); } onRouteChange(route) { this.props.dispatch(changeRoute(route)); } renderPage() { switch (this.props.app.route[0]) { case page.SIGNIN: return <SignIn />; case page.LAYOUT: return <ControllerLayout />; case page.HELP: return <Help />; case page.ACCOUNT: return <Account />; default: return <NotFound />; } } } const mapStateToProps = (state, props) => { return state; } export default connect(mapStateToProps)(App);
server/sonar-web/src/main/js/apps/global-permissions/permissions-list.js
joansmith/sonarqube
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import classNames from 'classnames'; import React from 'react'; import Permission from './permission'; export default React.createClass({ propTypes: { permissions: React.PropTypes.arrayOf(React.PropTypes.object).isRequired }, renderPermissions() { return this.props.permissions.map(permission => { return <Permission key={permission.key} permission={permission} project={this.props.project}/>; }); }, render() { let className = classNames({ 'new-loading': !this.props.ready }); return <ul id="global-permissions-list" className={className}>{this.renderPermissions()}</ul>; } });
node_modules/react-icons/io/flag.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const IoFlag = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m33.3 14.2s0.9-0.1 1.7-0.4c0 1.2-0.5 2.5-0.7 2.8-2.2 3.9-7.7 9.6-14.1 6.5-5.1-2.4-7.2-2.3-9.2-1.8-0.1 0-0.1 0-0.2 0-0.3 0.1-1.2 0.4-2 0.1v-15.4c0-1.2 1-2.4 2.5-2.7 3.1-0.6 8.3-0.4 11.6 5.8 3 5.7 7.6 5.6 10.4 5.1z m-26.4-11.7c0.3 0 0.6 0.3 0.6 0.6v33.8c0 0.3-0.3 0.6-0.6 0.6h-1.3c-0.3 0-0.6-0.3-0.6-0.6v-33.8c0-0.3 0.3-0.6 0.6-0.6h1.3z"/></g> </Icon> ) export default IoFlag
src/components/Login.js
kgosse/erp2042
/** * Created by kevin on 03/03/2016. */ import React from 'react'; import styleable from 'react-styleable'; import SelectField from 'material-ui/lib/select-field'; import MenuItem from 'material-ui/lib/menus/menu-item'; import RaisedButton from 'material-ui/lib/raised-button'; import { browserHistory } from 'react-router'; import css from './Login.css'; @styleable(css) class Login extends React.Component { constructor(props) { super(props); this.state = {value: 1}; } handleChange = (event, index, value) => this.setState({value}); handleConnextion = () => { browserHistory.push('/home'); }; render(){ return ( <div className={this.props.css.root}> <div className={this.props.css.card}> <h3>Choisissez un utilisateur</h3> <div> <SelectField value={this.state.value} onChange={this.handleChange}> <MenuItem value={1} primaryText=""/> <MenuItem value={2} primaryText="THIRION Guillaume"/> <MenuItem value={3} primaryText="SUBRAMANIAM Vijaï"/> <MenuItem value={4} primaryText="MORTIER Nicolas"/> <MenuItem value={5} primaryText="CHARPENTIER Boris"/> </SelectField> </div> <div className={this.props.css.button}> <RaisedButton label="Se connecter" secondary={true} onMouseUp={this.handleConnextion} onTouchEnd={this.handleConnextion} /> </div> </div> </div> ) } } export default Login;
es/withRouter.js
djkirby/react-router
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; }; import invariant from 'invariant'; import React from 'react'; import hoistStatics from 'hoist-non-react-statics'; import { ContextSubscriber } from './ContextUtils'; import { routerShape } from './PropTypes'; function getDisplayName(WrappedComponent) { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; } export default function withRouter(WrappedComponent, options) { var withRef = options && options.withRef; var WithRouter = React.createClass({ displayName: 'WithRouter', mixins: [ContextSubscriber('router')], contextTypes: { router: routerShape }, propTypes: { router: routerShape }, getWrappedInstance: function getWrappedInstance() { !withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0; return this.wrappedInstance; }, render: function render() { var _this = this; var router = this.props.router || this.context.router; if (!router) { return React.createElement(WrappedComponent, this.props); } var params = router.params, location = router.location, routes = router.routes; var props = _extends({}, this.props, { router: router, params: params, location: location, routes: routes }); if (withRef) { props.ref = function (c) { _this.wrappedInstance = c; }; } return React.createElement(WrappedComponent, props); } }); WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')'; WithRouter.WrappedComponent = WrappedComponent; return hoistStatics(WithRouter, WrappedComponent); }
ajax/libs/jquery-handsontable/0.10.2/jquery.handsontable.full.js
barcadictni/cdnjs
/** * Handsontable 0.10.2 * Handsontable is a simple jQuery plugin for editable tables with basic copy-paste compatibility with Excel and Google Docs * * Copyright 2012, Marcin Warpechowski * Licensed under the MIT license. * http://handsontable.com/ * * Date: Thu Jan 23 2014 23:06:23 GMT+0100 (CET) */ /*jslint white: true, browser: true, plusplus: true, indent: 4, maxerr: 50 */ var Handsontable = { //class namespace extension: {}, //extenstion namespace helper: {} //helper namespace }; (function ($, window, Handsontable) { "use strict"; //http://stackoverflow.com/questions/3629183/why-doesnt-indexof-work-on-an-array-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.filter() shim by Trevor Menagh (https://github.com/trevmex) with some modifications */ if (!Array.prototype.filter) { Array.prototype.filter = function (fun, thisp) { "use strict"; if (typeof this === "undefined" || this === null) { throw new TypeError(); } if (typeof fun !== "function") { throw new TypeError(); } thisp = thisp || this; if (isNodeList(thisp)) { thisp = convertNodeListToArray(thisp); } var len = thisp.length, res = [], i, val; for (i = 0; i < len; i += 1) { if (thisp.hasOwnProperty(i)) { val = thisp[i]; // in case fun mutates this if (fun.call(thisp, val, i, thisp)) { res.push(val); } } } return res; function isNodeList(object) { return /NodeList/i.test(object.item); } function convertNodeListToArray(nodeList) { var array = []; for (var i = 0, len = nodeList.length; i < len; i++){ array[i] = nodeList[i] } return array; } }; } /* * Copyright 2012 The Polymer Authors. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ if (typeof WeakMap === 'undefined') { (function() { var defineProperty = Object.defineProperty; try { var properDefineProperty = true; defineProperty(function(){}, 'foo', {}); } catch (e) { properDefineProperty = false; } /* IE8 does not support Date.now() but IE8 compatibility mode in IE9 and IE10 does. M$ deserves a high five for this one :) */ var counter = +(new Date) % 1e9; var WeakMap = function() { this.name = '__st' + (Math.random() * 1e9 >>> 0) + (counter++ + '__'); if(!properDefineProperty){ this._wmCache = []; } }; if(properDefineProperty){ WeakMap.prototype = { set: function(key, value) { var entry = key[this.name]; if (entry && entry[0] === key) entry[1] = value; else defineProperty(key, this.name, {value: [key, value], writable: true}); }, get: function(key) { var entry; return (entry = key[this.name]) && entry[0] === key ? entry[1] : undefined; }, 'delete': function(key) { this.set(key, undefined); } }; } else { WeakMap.prototype = { set: function(key, value) { if(typeof key == 'undefined' || typeof value == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ this._wmCache[i].value = value; return; } } this._wmCache.push({key: key, value: value}); }, get: function(key) { if(typeof key == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ return this._wmCache[i].value; } } return; }, 'delete': function(key) { if(typeof key == 'undefined') return; for(var i = 0, len = this._wmCache.length; i < len; i++){ if(this._wmCache[i].key == key){ Array.prototype.slice.call(this._wmCache, i, 1); } } } }; } window.WeakMap = WeakMap; })(); } Handsontable.activeGuid = null; /** * Handsontable constructor * @param rootElement The jQuery element in which Handsontable DOM will be inserted * @param userSettings * @constructor */ Handsontable.Core = function (rootElement, userSettings) { var priv , datamap , grid , selection , editorManager , autofill , instance = this , GridSettings = function () {}; Handsontable.helper.extend(GridSettings.prototype, DefaultSettings.prototype); //create grid settings as a copy of default settings Handsontable.helper.extend(GridSettings.prototype, userSettings); //overwrite defaults with user settings Handsontable.helper.extend(GridSettings.prototype, expandType(userSettings)); this.rootElement = rootElement; var $document = $(document.documentElement); var $body = $(document.body); this.guid = 'ht_' + Handsontable.helper.randomString(); //this is the namespace for global events if (!this.rootElement[0].id) { this.rootElement[0].id = this.guid; //if root element does not have an id, assign a random id } priv = { cellSettings: [], columnSettings: [], columnsSettingConflicts: ['data', 'width'], settings: new GridSettings(), // current settings instance settingsFromDOM: {}, selStart: new Handsontable.SelectionPoint(), selEnd: new Handsontable.SelectionPoint(), isPopulated: null, scrollable: null, extensions: {}, firstRun: true }; grid = { /** * Inserts or removes rows and columns * @param {String} action Possible values: "insert_row", "insert_col", "remove_row", "remove_col" * @param {Number} index * @param {Number} amount * @param {String} [source] Optional. Source of hook runner. * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows. */ alter: function (action, index, amount, source, keepEmptyRows) { var delta; amount = amount || 1; switch (action) { case "insert_row": delta = datamap.createRow(index, amount); if (delta) { if (priv.selStart.exists() && priv.selStart.row() >= index) { priv.selStart.row(priv.selStart.row() + delta); selection.transformEnd(delta, 0); //will call render() internally } else { selection.refreshBorders(); //it will call render and prepare methods } } break; case "insert_col": delta = datamap.createCol(index, amount); if (delta) { if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ var spliceArray = [index, 0]; spliceArray.length += delta; //inserts empty (undefined) elements at the end of an array Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArray); //inserts empty (undefined) elements into the colHeader array } if (priv.selStart.exists() && priv.selStart.col() >= index) { priv.selStart.col(priv.selStart.col() + delta); selection.transformEnd(0, delta); //will call render() internally } else { selection.refreshBorders(); //it will call render and prepare methods } } break; case "remove_row": datamap.removeRow(index, amount); priv.cellSettings.splice(index, amount); grid.adjustRowsAndCols(); selection.refreshBorders(); //it will call render and prepare methods break; case "remove_col": datamap.removeCol(index, amount); for(var row = 0, len = datamap.getAll().length; row < len; row++){ if(row in priv.cellSettings){ //if row hasn't been rendered it wouldn't have cellSettings priv.cellSettings[row].splice(index, amount); } } if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ if(typeof index == 'undefined'){ index = -1; } instance.getSettings().colHeaders.splice(index, amount); } priv.columnSettings.splice(index, amount); grid.adjustRowsAndCols(); selection.refreshBorders(); //it will call render and prepare methods break; default: throw new Error('There is no such action "' + action + '"'); break; } if (!keepEmptyRows) { grid.adjustRowsAndCols(); //makes sure that we did not add rows that will be removed in next refresh } }, /** * Makes sure there are empty rows at the bottom of the table */ adjustRowsAndCols: function () { var r, rlen, emptyRows = instance.countEmptyRows(true), emptyCols; //should I add empty rows to data source to meet minRows? rlen = instance.countRows(); if (rlen < priv.settings.minRows) { for (r = 0; r < priv.settings.minRows - rlen; r++) { datamap.createRow(); } } //should I add empty rows to meet minSpareRows? if (emptyRows < priv.settings.minSpareRows) { for (; emptyRows < priv.settings.minSpareRows && instance.countRows() < priv.settings.maxRows; emptyRows++) { datamap.createRow(); } } //count currently empty cols emptyCols = instance.countEmptyCols(true); //should I add empty cols to meet minCols? if (!priv.settings.columns && instance.countCols() < priv.settings.minCols) { for (; instance.countCols() < priv.settings.minCols; emptyCols++) { datamap.createCol(); } } //should I add empty cols to meet minSpareCols? if (!priv.settings.columns && instance.dataType === 'array' && emptyCols < priv.settings.minSpareCols) { for (; emptyCols < priv.settings.minSpareCols && instance.countCols() < priv.settings.maxCols; emptyCols++) { datamap.createCol(); } } if (priv.settings.enterBeginsEditing) { for (; (((priv.settings.minRows || priv.settings.minSpareRows) && instance.countRows() > priv.settings.minRows) && (priv.settings.minSpareRows && emptyRows > priv.settings.minSpareRows)); emptyRows--) { datamap.removeRow(); } } if (priv.settings.enterBeginsEditing && !priv.settings.columns) { for (; (((priv.settings.minCols || priv.settings.minSpareCols) && instance.countCols() > priv.settings.minCols) && (priv.settings.minSpareCols && emptyCols > priv.settings.minSpareCols)); emptyCols--) { datamap.removeCol(); } } var rowCount = instance.countRows(); var colCount = instance.countCols(); if (rowCount === 0 || colCount === 0) { selection.deselect(); } if (priv.selStart.exists()) { var selectionChanged; var fromRow = priv.selStart.row(); var fromCol = priv.selStart.col(); var toRow = priv.selEnd.row(); var toCol = priv.selEnd.col(); //if selection is outside, move selection to last row if (fromRow > rowCount - 1) { fromRow = rowCount - 1; selectionChanged = true; if (toRow > fromRow) { toRow = fromRow; } } else if (toRow > rowCount - 1) { toRow = rowCount - 1; selectionChanged = true; if (fromRow > toRow) { fromRow = toRow; } } //if selection is outside, move selection to last row if (fromCol > colCount - 1) { fromCol = colCount - 1; selectionChanged = true; if (toCol > fromCol) { toCol = fromCol; } } else if (toCol > colCount - 1) { toCol = colCount - 1; selectionChanged = true; if (fromCol > toCol) { fromCol = toCol; } } if (selectionChanged) { instance.selectCell(fromRow, fromCol, toRow, toCol); } } }, /** * Populate cells at position with 2d array * @param {Object} start Start selection position * @param {Array} input 2d array * @param {Object} [end] End selection position (only for drag-down mode) * @param {String} [source="populateFromArray"] * @param {String} [method="overwrite"] * @return {Object|undefined} ending td in pasted area (only if any cell was changed) */ populateFromArray: function (start, input, end, source, method) { var r, rlen, c, clen, setData = [], current = {}; rlen = input.length; if (rlen === 0) { return false; } var repeatCol , repeatRow , cmax , rmax; // insert data with specified pasteMode method switch (method) { case 'shift_down' : repeatCol = end ? end.col - start.col + 1 : 0; repeatRow = end ? end.row - start.row + 1 : 0; input = Handsontable.helper.translateRowsToColumns(input); for (c = 0, clen = input.length, cmax = Math.max(clen, repeatCol); c < cmax; c++) { if (c < clen) { for (r = 0, rlen = input[c].length; r < repeatRow - rlen; r++) { input[c].push(input[c][r % rlen]); } input[c].unshift(start.col + c, start.row, 0); instance.spliceCol.apply(instance, input[c]); } else { input[c % clen][0] = start.col + c; instance.spliceCol.apply(instance, input[c % clen]); } } break; case 'shift_right' : repeatCol = end ? end.col - start.col + 1 : 0; repeatRow = end ? end.row - start.row + 1 : 0; for (r = 0, rlen = input.length, rmax = Math.max(rlen, repeatRow); r < rmax; r++) { if (r < rlen) { for (c = 0, clen = input[r].length; c < repeatCol - clen; c++) { input[r].push(input[r][c % clen]); } input[r].unshift(start.row + r, start.col, 0); instance.spliceRow.apply(instance, input[r]); } else { input[r % rlen][0] = start.row + r; instance.spliceRow.apply(instance, input[r % rlen]); } } break; case 'overwrite' : default: // overwrite and other not specified options current.row = start.row; current.col = start.col; for (r = 0; r < rlen; r++) { if ((end && current.row > end.row) || (!priv.settings.minSpareRows && current.row > instance.countRows() - 1) || (current.row >= priv.settings.maxRows)) { break; } current.col = start.col; clen = input[r] ? input[r].length : 0; for (c = 0; c < clen; c++) { if ((end && current.col > end.col) || (!priv.settings.minSpareCols && current.col > instance.countCols() - 1) || (current.col >= priv.settings.maxCols)) { break; } if (!instance.getCellMeta(current.row, current.col).readOnly) { setData.push([current.row, current.col, input[r][c]]); } current.col++; if (end && c === clen - 1) { c = -1; } } current.row++; if (end && r === rlen - 1) { r = -1; } } instance.setDataAtCell(setData, null, null, source || 'populateFromArray'); break; } }, /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @param {Object[]} coordsArr * @returns {Object} */ getCornerCoords: function (coordsArr) { function mapProp(func, array, prop) { function getProp(el) { return el[prop]; } if (Array.prototype.map) { return func.apply(Math, array.map(getProp)); } return func.apply(Math, $.map(array, getProp)); } return { TL: { row: mapProp(Math.min, coordsArr, "row"), col: mapProp(Math.min, coordsArr, "col") }, BR: { row: mapProp(Math.max, coordsArr, "row"), col: mapProp(Math.max, coordsArr, "col") } }; }, /** * Returns array of td objects given start and end coordinates */ getCellsAtCoords: function (start, end) { var corners = grid.getCornerCoords([start, end]); var r, c, output = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { output.push(instance.view.getCellAtCoords({ row: r, col: c })); } } return output; } }; this.selection = selection = { //this public assignment is only temporary inProgress: false, /** * Sets inProgress to true. This enables onSelectionEnd and onSelectionEndByProp to function as desired */ begin: function () { instance.selection.inProgress = true; }, /** * Sets inProgress to false. Triggers onSelectionEnd and onSelectionEndByProp */ finish: function () { var sel = instance.getSelected(); instance.PluginHooks.run("afterSelectionEnd", sel[0], sel[1], sel[2], sel[3]); instance.PluginHooks.run("afterSelectionEndByProp", sel[0], instance.colToProp(sel[1]), sel[2], instance.colToProp(sel[3])); instance.selection.inProgress = false; }, isInProgress: function () { return instance.selection.inProgress; }, /** * Starts selection range on given td object * @param {Object} coords */ setRangeStart: function (coords) { priv.selStart.coords(coords); selection.setRangeEnd(coords); }, /** * Ends selection range on given td object * @param {Object} coords * @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to range end */ setRangeEnd: function (coords, scrollToCell) { instance.selection.begin(); priv.selEnd.coords(coords); if (!priv.settings.multiSelect) { priv.selStart.coords(coords); } //set up current selection instance.view.wt.selections.current.clear(); instance.view.wt.selections.current.add(priv.selStart.arr()); //set up area selection instance.view.wt.selections.area.clear(); if (selection.isMultiple()) { instance.view.wt.selections.area.add(priv.selStart.arr()); instance.view.wt.selections.area.add(priv.selEnd.arr()); } //set up highlight if (priv.settings.currentRowClassName || priv.settings.currentColClassName) { instance.view.wt.selections.highlight.clear(); instance.view.wt.selections.highlight.add(priv.selStart.arr()); instance.view.wt.selections.highlight.add(priv.selEnd.arr()); } //trigger handlers instance.PluginHooks.run("afterSelection", priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()); instance.PluginHooks.run("afterSelectionByProp", priv.selStart.row(), datamap.colToProp(priv.selStart.col()), priv.selEnd.row(), datamap.colToProp(priv.selEnd.col())); if (scrollToCell !== false) { instance.view.scrollViewport(coords); } selection.refreshBorders(); }, /** * Destroys editor, redraws borders around cells, prepares editor * @param {Boolean} revertOriginal * @param {Boolean} keepEditor */ refreshBorders: function (revertOriginal, keepEditor) { if (!keepEditor) { editorManager.destroyEditor(revertOriginal); } instance.view.render(); if (selection.isSelected() && !keepEditor) { editorManager.prepareEditor(); } }, /** * Returns information if we have a multiselection * @return {Boolean} */ isMultiple: function () { return !(priv.selEnd.col() === priv.selStart.col() && priv.selEnd.row() === priv.selStart.row()); }, /** * Selects cell relative to current cell (if possible) */ transformStart: function (rowDelta, colDelta, force) { if (priv.selStart.row() + rowDelta > instance.countRows() - 1) { if (force && priv.settings.minSpareRows > 0) { instance.alter("insert_row", instance.countRows()); } else if (priv.settings.autoWrapCol) { rowDelta = 1 - instance.countRows(); colDelta = priv.selStart.col() + colDelta == instance.countCols() - 1 ? 1 - instance.countCols() : 1; } } else if (priv.settings.autoWrapCol && priv.selStart.row() + rowDelta < 0 && priv.selStart.col() + colDelta >= 0) { rowDelta = instance.countRows() - 1; colDelta = priv.selStart.col() + colDelta == 0 ? instance.countCols() - 1 : -1; } if (priv.selStart.col() + colDelta > instance.countCols() - 1) { if (force && priv.settings.minSpareCols > 0) { instance.alter("insert_col", instance.countCols()); } else if (priv.settings.autoWrapRow) { rowDelta = priv.selStart.row() + rowDelta == instance.countRows() - 1 ? 1 - instance.countRows() : 1; colDelta = 1 - instance.countCols(); } } else if (priv.settings.autoWrapRow && priv.selStart.col() + colDelta < 0 && priv.selStart.row() + rowDelta >= 0) { rowDelta = priv.selStart.row() + rowDelta == 0 ? instance.countRows() - 1 : -1; colDelta = instance.countCols() - 1; } var totalRows = instance.countRows(); var totalCols = instance.countCols(); var coords = { row: priv.selStart.row() + rowDelta, col: priv.selStart.col() + colDelta }; if (coords.row < 0) { coords.row = 0; } else if (coords.row > 0 && coords.row >= totalRows) { coords.row = totalRows - 1; } if (coords.col < 0) { coords.col = 0; } else if (coords.col > 0 && coords.col >= totalCols) { coords.col = totalCols - 1; } selection.setRangeStart(coords); }, /** * Sets selection end cell relative to current selection end cell (if possible) */ transformEnd: function (rowDelta, colDelta) { if (priv.selEnd.exists()) { var totalRows = instance.countRows(); var totalCols = instance.countCols(); var coords = { row: priv.selEnd.row() + rowDelta, col: priv.selEnd.col() + colDelta }; if (coords.row < 0) { coords.row = 0; } else if (coords.row > 0 && coords.row >= totalRows) { coords.row = totalRows - 1; } if (coords.col < 0) { coords.col = 0; } else if (coords.col > 0 && coords.col >= totalCols) { coords.col = totalCols - 1; } selection.setRangeEnd(coords); } }, /** * Returns true if currently there is a selection on screen, false otherwise * @return {Boolean} */ isSelected: function () { return priv.selEnd.exists(); }, /** * Returns true if coords is within current selection coords * @return {Boolean} */ inInSelection: function (coords) { if (!selection.isSelected()) { return false; } var sel = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); return (sel.TL.row <= coords.row && sel.BR.row >= coords.row && sel.TL.col <= coords.col && sel.BR.col >= coords.col); }, /** * Deselects all selected cells */ deselect: function () { if (!selection.isSelected()) { return; } instance.selection.inProgress = false; //needed by HT inception priv.selEnd = new Handsontable.SelectionPoint(); //create new empty point to remove the existing one instance.view.wt.selections.current.clear(); instance.view.wt.selections.area.clear(); editorManager.destroyEditor(); selection.refreshBorders(); instance.PluginHooks.run('afterDeselect'); }, /** * Select all cells */ selectAll: function () { if (!priv.settings.multiSelect) { return; } selection.setRangeStart({ row: 0, col: 0 }); selection.setRangeEnd({ row: instance.countRows() - 1, col: instance.countCols() - 1 }, false); }, /** * Deletes data from selected cells */ empty: function () { if (!selection.isSelected()) { return; } var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); var r, c, changes = []; for (r = corners.TL.row; r <= corners.BR.row; r++) { for (c = corners.TL.col; c <= corners.BR.col; c++) { if (!instance.getCellMeta(r, c).readOnly) { changes.push([r, c, '']); } } } instance.setDataAtCell(changes); } }; this.autofill = autofill = { //this public assignment is only temporary handle: null, /** * Create fill handle and fill border objects */ init: function () { if (!autofill.handle) { autofill.handle = {}; } else { autofill.handle.disabled = false; } }, /** * Hide fill handle and fill border permanently */ disable: function () { autofill.handle.disabled = true; }, /** * Selects cells down to the last row in the left column, then fills down to that cell */ selectAdjacent: function () { var select, data, r, maxR, c; if (selection.isMultiple()) { select = instance.view.wt.selections.area.getCorners(); } else { select = instance.view.wt.selections.current.getCorners(); } data = datamap.getAll(); rows : for (r = select[2] + 1; r < instance.countRows(); r++) { for (c = select[1]; c <= select[3]; c++) { if (data[r][c]) { break rows; } } if (!!data[r][select[1] - 1] || !!data[r][select[3] + 1]) { maxR = r; } } if (maxR) { instance.view.wt.selections.fill.clear(); instance.view.wt.selections.fill.add([select[0], select[1]]); instance.view.wt.selections.fill.add([maxR, select[3]]); autofill.apply(); } }, /** * Apply fill values to the area in fill border, omitting the selection border */ apply: function () { var drag, select, start, end, _data; autofill.handle.isDragged = 0; drag = instance.view.wt.selections.fill.getCorners(); if (!drag) { return; } instance.view.wt.selections.fill.clear(); if (selection.isMultiple()) { select = instance.view.wt.selections.area.getCorners(); } else { select = instance.view.wt.selections.current.getCorners(); } if (drag[0] === select[0] && drag[1] < select[1]) { start = { row: drag[0], col: drag[1] }; end = { row: drag[2], col: select[1] - 1 }; } else if (drag[0] === select[0] && drag[3] > select[3]) { start = { row: drag[0], col: select[3] + 1 }; end = { row: drag[2], col: drag[3] }; } else if (drag[0] < select[0] && drag[1] === select[1]) { start = { row: drag[0], col: drag[1] }; end = { row: select[0] - 1, col: drag[3] }; } else if (drag[2] > select[2] && drag[1] === select[1]) { start = { row: select[2] + 1, col: drag[1] }; end = { row: drag[2], col: drag[3] }; } if (start) { _data = SheetClip.parse(datamap.getText(priv.selStart.coords(), priv.selEnd.coords())); instance.PluginHooks.run('beforeAutofill', start, end, _data); grid.populateFromArray(start, _data, end, 'autofill'); selection.setRangeStart({row: drag[0], col: drag[1]}); selection.setRangeEnd({row: drag[2], col: drag[3]}); } /*else { //reset to avoid some range bug selection.refreshBorders(); }*/ }, /** * Show fill border */ showBorder: function (coords) { coords.row = coords[0]; coords.col = coords[1]; var corners = grid.getCornerCoords([priv.selStart.coords(), priv.selEnd.coords()]); if (priv.settings.fillHandle !== 'horizontal' && (corners.BR.row < coords.row || corners.TL.row > coords.row)) { coords = [coords.row, corners.BR.col]; } else if (priv.settings.fillHandle !== 'vertical') { coords = [corners.BR.row, coords.col]; } else { return; //wrong direction } instance.view.wt.selections.fill.clear(); instance.view.wt.selections.fill.add([priv.selStart.coords().row, priv.selStart.coords().col]); instance.view.wt.selections.fill.add([priv.selEnd.coords().row, priv.selEnd.coords().col]); instance.view.wt.selections.fill.add(coords); instance.view.render(); } }; this.init = function () { instance.PluginHooks.run('beforeInit'); this.view = new Handsontable.TableView(this); editorManager = new Handsontable.EditorManager(instance, priv, selection, datamap); this.updateSettings(priv.settings, true); this.parseSettingsFromDOM(); this.forceFullRender = true; //used when data was changed this.view.render(); if (typeof priv.firstRun === 'object') { instance.PluginHooks.run('afterChange', priv.firstRun[0], priv.firstRun[1]); priv.firstRun = false; } instance.PluginHooks.run('afterInit'); }; function ValidatorsQueue() { //moved this one level up so it can be used in any function here. Probably this should be moved to a separate file var resolved = false; return { validatorsInQueue: 0, addValidatorToQueue: function () { this.validatorsInQueue++; resolved = false; }, removeValidatorFormQueue: function () { this.validatorsInQueue = this.validatorsInQueue - 1 < 0 ? 0 : this.validatorsInQueue - 1; this.checkIfQueueIsEmpty(); }, onQueueEmpty: function () { }, checkIfQueueIsEmpty: function () { if (this.validatorsInQueue == 0 && resolved == false) { resolved = true; this.onQueueEmpty(); } } }; } function validateChanges(changes, source, callback) { var waitingForValidator = new ValidatorsQueue(); waitingForValidator.onQueueEmpty = resolve; for (var i = changes.length - 1; i >= 0; i--) { if (changes[i] === null) { changes.splice(i, 1); } else { var row = changes[i][0]; var col = datamap.propToCol(changes[i][1]); var logicalCol = instance.runHooksAndReturn('modifyCol', col); //column order may have changes, so we need to translate physical col index (stored in datasource) to logical (displayed to user) var cellProperties = instance.getCellMeta(row, logicalCol); if (cellProperties.type === 'numeric' && typeof changes[i][3] === 'string') { if (changes[i][3].length > 0 && /^-?[\d\s]*\.?\d*$/.test(changes[i][3])) { changes[i][3] = numeral().unformat(changes[i][3] || '0'); //numeral cannot unformat empty string } } if (instance.getCellValidator(cellProperties)) { waitingForValidator.addValidatorToQueue(); instance.validateCell(changes[i][3], cellProperties, (function (i, cellProperties) { return function (result) { if (typeof result !== 'boolean') { throw new Error("Validation error: result is not boolean"); } if (result === false && cellProperties.allowInvalid === false) { changes.splice(i, 1); // cancel the change cellProperties.valid = true; // we cancelled the change, so cell value is still valid --i; } waitingForValidator.removeValidatorFormQueue(); } })(i, cellProperties) , source); } } } waitingForValidator.checkIfQueueIsEmpty(); function resolve() { var beforeChangeResult; if (changes.length) { beforeChangeResult = instance.PluginHooks.execute("beforeChange", changes, source); if (typeof beforeChangeResult === 'function') { $.when(result).then(function () { callback(); //called when async validators and async beforeChange are resolved }); } else if (beforeChangeResult === false) { changes.splice(0, changes.length); //invalidate all changes (remove everything from array) } } if (typeof beforeChangeResult !== 'function') { callback(); //called when async validators are resolved and beforeChange was not async } } } /** * Internal function to apply changes. Called after validateChanges * @param {Array} changes Array in form of [row, prop, oldValue, newValue] * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ function applyChanges(changes, source) { var i = changes.length - 1; if (i < 0) { return; } for (; 0 <= i; i--) { if (changes[i] === null) { changes.splice(i, 1); continue; } if (priv.settings.minSpareRows) { while (changes[i][0] > instance.countRows() - 1) { datamap.createRow(); } } if (instance.dataType === 'array' && priv.settings.minSpareCols) { while (datamap.propToCol(changes[i][1]) > instance.countCols() - 1) { datamap.createCol(); } } datamap.set(changes[i][0], changes[i][1], changes[i][3]); } instance.forceFullRender = true; //used when data was changed grid.adjustRowsAndCols(); selection.refreshBorders(null, true); instance.PluginHooks.run('afterChange', changes, source || 'edit'); } this.validateCell = function (value, cellProperties, callback, source) { var validator = instance.getCellValidator(cellProperties); if (Object.prototype.toString.call(validator) === '[object RegExp]') { validator = (function (validator) { return function (value, callback) { callback(validator.test(value)); } })(validator); } if (typeof validator == 'function') { value = instance.PluginHooks.execute("beforeValidate", value, cellProperties.row, cellProperties.prop, source); // To provide consistent behaviour, validation should be always asynchronous setTimeout(function () { validator.call(cellProperties, value, function (valid) { cellProperties.valid = valid; valid = instance.PluginHooks.execute("afterValidate", valid, value, cellProperties.row, cellProperties.prop, source); callback(valid); }); }); } else { //resolve callback even if validator function was not found cellProperties.valid = true; callback(true); } }; function setDataInputToArray(row, prop_or_col, value) { if (typeof row === "object") { //is it an array of changes return row; } else if ($.isPlainObject(value)) { //backwards compatibility return value; } else { return [ [row, prop_or_col, value] ]; } } /** * Set data at given cell * @public * @param {Number|Array} row or array of changes in format [[row, col, value], ...] * @param {Number|String} col or source String * @param {String} value * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ this.setDataAtCell = function (row, col, value, source) { var input = setDataInputToArray(row, col, value) , i , ilen , changes = [] , prop; for (i = 0, ilen = input.length; i < ilen; i++) { if (typeof input[i] !== 'object') { throw new Error('Method `setDataAtCell` accepts row number or changes array of arrays as its first parameter'); } if (typeof input[i][1] !== 'number') { throw new Error('Method `setDataAtCell` accepts row and column number as its parameters. If you want to use object property name, use method `setDataAtRowProp`'); } prop = datamap.colToProp(input[i][1]); changes.push([ input[i][0], prop, datamap.get(input[i][0], prop), input[i][2] ]); } if (!source && typeof row === "object") { source = col; } validateChanges(changes, source, function () { applyChanges(changes, source); }); }; /** * Set data at given row property * @public * @param {Number|Array} row or array of changes in format [[row, prop, value], ...] * @param {String} prop or source String * @param {String} value * @param {String} source String that identifies how this change will be described in changes array (useful in onChange callback) */ this.setDataAtRowProp = function (row, prop, value, source) { var input = setDataInputToArray(row, prop, value) , i , ilen , changes = []; for (i = 0, ilen = input.length; i < ilen; i++) { changes.push([ input[i][0], input[i][1], datamap.get(input[i][0], input[i][1]), input[i][2] ]); } if (!source && typeof row === "object") { source = prop; } validateChanges(changes, source, function () { applyChanges(changes, source); }); }; /** * Listen to document body keyboard input */ this.listen = function () { Handsontable.activeGuid = instance.guid; if (document.activeElement && document.activeElement !== document.body) { document.activeElement.blur(); } else if (!document.activeElement) { //IE document.body.focus(); } }; /** * Stop listening to document body keyboard input */ this.unlisten = function () { Handsontable.activeGuid = null; }; /** * Returns true if current Handsontable instance is listening on document body keyboard input */ this.isListening = function () { return Handsontable.activeGuid === instance.guid; }; /** * Destroys current editor, renders and selects current cell. If revertOriginal != true, edited data is saved * @param {Boolean} revertOriginal */ this.destroyEditor = function (revertOriginal) { selection.refreshBorders(revertOriginal); }; /** * Populate cells at position with 2d array * @param {Number} row Start row * @param {Number} col Start column * @param {Array} input 2d array * @param {Number=} endRow End row (use when you want to cut input when certain row is reached) * @param {Number=} endCol End column (use when you want to cut input when certain column is reached) * @param {String=} [source="populateFromArray"] * @param {String=} [method="overwrite"] * @return {Object|undefined} ending td in pasted area (only if any cell was changed) */ this.populateFromArray = function (row, col, input, endRow, endCol, source, method) { if (!(typeof input === 'object' && typeof input[0] === 'object')) { throw new Error("populateFromArray parameter `input` must be an array of arrays"); //API changed in 0.9-beta2, let's check if you use it correctly } return grid.populateFromArray({row: row, col: col}, input, typeof endRow === 'number' ? {row: endRow, col: endCol} : null, source, method); }; /** * Adds/removes data from the column * @param {Number} col Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ this.spliceCol = function (col, index, amount/*, elements... */) { return datamap.spliceCol.apply(datamap, arguments); }; /** * Adds/removes data from the row * @param {Number} row Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ this.spliceRow = function (row, index, amount/*, elements... */) { return datamap.spliceRow.apply(datamap, arguments); }; /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @param {Object[]} coordsArr * @returns {Object} */ this.getCornerCoords = function (coordsArr) { return grid.getCornerCoords(coordsArr); }; /** * Returns current selection. Returns undefined if there is no selection. * @public * @return {Array} [`startRow`, `startCol`, `endRow`, `endCol`] */ this.getSelected = function () { //https://github.com/warpech/jquery-handsontable/issues/44 //cjl if (selection.isSelected()) { return [priv.selStart.row(), priv.selStart.col(), priv.selEnd.row(), priv.selEnd.col()]; } }; /** * Parse settings from DOM and CSS * @public */ this.parseSettingsFromDOM = function () { var overflow = this.rootElement.css('overflow'); if (overflow === 'scroll' || overflow === 'auto') { this.rootElement[0].style.overflow = 'visible'; priv.settingsFromDOM.overflow = overflow; } else if (priv.settings.width === void 0 || priv.settings.height === void 0) { priv.settingsFromDOM.overflow = 'auto'; } if (priv.settings.width === void 0) { priv.settingsFromDOM.width = this.rootElement.width(); } else { priv.settingsFromDOM.width = void 0; } priv.settingsFromDOM.height = void 0; if (priv.settings.height === void 0) { if (priv.settingsFromDOM.overflow === 'scroll' || priv.settingsFromDOM.overflow === 'auto') { //this needs to read only CSS/inline style and not actual height //so we need to call getComputedStyle on cloned container var clone = this.rootElement[0].cloneNode(false); var parent = this.rootElement[0].parentNode; if (parent) { clone.removeAttribute('id'); parent.appendChild(clone); var computedHeight = parseInt(window.getComputedStyle(clone, null).getPropertyValue('height'), 10); if(isNaN(computedHeight) && clone.currentStyle){ computedHeight = parseInt(clone.currentStyle.height, 10) } if (computedHeight > 0) { priv.settingsFromDOM.height = computedHeight; } parent.removeChild(clone); } } } }; /** * Render visible data * @public */ this.render = function () { if (instance.view) { instance.forceFullRender = true; //used when data was changed instance.parseSettingsFromDOM(); selection.refreshBorders(null, true); } }; /** * Load data from array * @public * @param {Array} data */ this.loadData = function (data) { if (typeof data === 'object' && data !== null) { if (!(data.push && data.splice)) { //check if data is array. Must use duck-type check so Backbone Collections also pass it //when data is not an array, attempt to make a single-row array of it data = [data]; } } else if(data === null) { data = []; var row; for (var r = 0, rlen = priv.settings.startRows; r < rlen; r++) { row = []; for (var c = 0, clen = priv.settings.startCols; c < clen; c++) { row.push(null); } data.push(row); } } else { throw new Error("loadData only accepts array of objects or array of arrays (" + typeof data + " given)"); } priv.isPopulated = false; GridSettings.prototype.data = data; if (priv.settings.dataSchema instanceof Array || data[0] instanceof Array) { instance.dataType = 'array'; } else if (typeof priv.settings.dataSchema === 'function') { instance.dataType = 'function'; } else { instance.dataType = 'object'; } datamap = new Handsontable.DataMap(instance, priv, GridSettings); clearCellSettingCache(); grid.adjustRowsAndCols(); instance.PluginHooks.run('afterLoadData'); if (priv.firstRun) { priv.firstRun = [null, 'loadData']; } else { instance.PluginHooks.run('afterChange', null, 'loadData'); instance.render(); } priv.isPopulated = true; function clearCellSettingCache() { priv.cellSettings.length = 0; } }; /** * Return the current data object (the same that was passed by `data` configuration option or `loadData` method). Optionally you can provide cell range `r`, `c`, `r2`, `c2` to get only a fragment of grid data * @public * @param {Number} r (Optional) From row * @param {Number} c (Optional) From col * @param {Number} r2 (Optional) To row * @param {Number} c2 (Optional) To col * @return {Array|Object} */ this.getData = function (r, c, r2, c2) { if (typeof r === 'undefined') { return datamap.getAll(); } else { return datamap.getRange({row: r, col: c}, {row: r2, col: c2}, datamap.DESTINATION_RENDERER); } }; this.getCopyableData = function (startRow, startCol, endRow, endCol) { return datamap.getCopyableText({row: startRow, col: startCol}, {row: endRow, col: endCol}); } /** * Update settings * @public */ this.updateSettings = function (settings, init) { var i, clen; if (typeof settings.rows !== "undefined") { throw new Error("'rows' setting is no longer supported. do you mean startRows, minRows or maxRows?"); } if (typeof settings.cols !== "undefined") { throw new Error("'cols' setting is no longer supported. do you mean startCols, minCols or maxCols?"); } for (i in settings) { if (i === 'data') { continue; //loadData will be triggered later } else { if (instance.PluginHooks.hooks[i] !== void 0 || instance.PluginHooks.legacy[i] !== void 0) { if (typeof settings[i] === 'function' || Handsontable.helper.isArray(settings[i])) { instance.PluginHooks.add(i, settings[i]); } } else { // Update settings if (!init && settings.hasOwnProperty(i)) { GridSettings.prototype[i] = settings[i]; } //launch extensions if (Handsontable.extension[i]) { priv.extensions[i] = new Handsontable.extension[i](instance, settings[i]); } } } } // Load data or create data map if (settings.data === void 0 && priv.settings.data === void 0) { instance.loadData(null); //data source created just now } else if (settings.data !== void 0) { instance.loadData(settings.data); //data source given as option } else if (settings.columns !== void 0) { datamap.createMap(); } // Init columns constructors configuration clen = instance.countCols(); //Clear cellSettings cache priv.cellSettings.length = 0; if (clen > 0) { var proto, column; for (i = 0; i < clen; i++) { priv.columnSettings[i] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts); // shortcut for prototype proto = priv.columnSettings[i].prototype; // Use settings provided by user if (GridSettings.prototype.columns) { column = GridSettings.prototype.columns[i]; Handsontable.helper.extend(proto, column); Handsontable.helper.extend(proto, expandType(column)); } } } if (typeof settings.fillHandle !== "undefined") { if (autofill.handle && settings.fillHandle === false) { autofill.disable(); } else if (!autofill.handle && settings.fillHandle !== false) { autofill.init(); } } if (typeof settings.className !== "undefined") { if (GridSettings.prototype.className) { instance.rootElement.removeClass(GridSettings.prototype.className); } if (settings.className) { instance.rootElement.addClass(settings.className); } } if (!init) { instance.PluginHooks.run('afterUpdateSettings'); } grid.adjustRowsAndCols(); if (instance.view && !priv.firstRun) { instance.forceFullRender = true; //used when data was changed selection.refreshBorders(null, true); } }; this.getValue = function () { var sel = instance.getSelected(); if (GridSettings.prototype.getValue) { if (typeof GridSettings.prototype.getValue === 'function') { return GridSettings.prototype.getValue.call(instance); } else if (sel) { return instance.getData()[sel[0]][GridSettings.prototype.getValue]; } } else if (sel) { return instance.getDataAtCell(sel[0], sel[1]); } }; function expandType(obj) { if (!obj.hasOwnProperty('type')) return; //ignore obj.prototype.type var type, expandedType = {}; if (typeof obj.type === 'object') { type = obj.type; } else if (typeof obj.type === 'string') { type = Handsontable.cellTypes[obj.type]; if (type === void 0) { throw new Error('You declared cell type "' + obj.type + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } } for (var i in type) { if (type.hasOwnProperty(i) && !obj.hasOwnProperty(i)) { expandedType[i] = type[i]; } } return expandedType; } /** * Returns current settings object * @return {Object} */ this.getSettings = function () { return priv.settings; }; /** * Returns current settingsFromDOM object * @return {Object} */ this.getSettingsFromDOM = function () { return priv.settingsFromDOM; }; /** * Clears grid * @public */ this.clear = function () { selection.selectAll(); selection.empty(); }; /** * Inserts or removes rows and columns * @param {String} action See grid.alter for possible values * @param {Number} index * @param {Number} amount * @param {String} [source] Optional. Source of hook runner. * @param {Boolean} [keepEmptyRows] Optional. Flag for preventing deletion of empty rows. * @public */ this.alter = function (action, index, amount, source, keepEmptyRows) { grid.alter(action, index, amount, source, keepEmptyRows); }; /** * Returns <td> element corresponding to params row, col * @param {Number} row * @param {Number} col * @public * @return {Element} */ this.getCell = function (row, col) { return instance.view.getCellAtCoords({row: row, col: col}); }; /** * Returns property name associated with column number * @param {Number} col * @public * @return {String} */ this.colToProp = function (col) { return datamap.colToProp(col); }; /** * Returns column number associated with property name * @param {String} prop * @public * @return {Number} */ this.propToCol = function (prop) { return datamap.propToCol(prop); }; /** * Return value at `row`, `col` * @param {Number} row * @param {Number} col * @public * @return value (mixed data type) */ this.getDataAtCell = function (row, col) { return datamap.get(row, datamap.colToProp(col)); }; /** * Return value at `row`, `prop` * @param {Number} row * @param {String} prop * @public * @return value (mixed data type) */ this.getDataAtRowProp = function (row, prop) { return datamap.get(row, prop); }; /** * Return value at `col` * @param {Number} col * @public * @return value (mixed data type) */ this.getDataAtCol = function (col) { return [].concat.apply([], datamap.getRange({row: 0, col: col}, {row: priv.settings.data.length - 1, col: col}, datamap.DESTINATION_RENDERER)); }; /** * Return value at `prop` * @param {String} prop * @public * @return value (mixed data type) */ this.getDataAtProp = function (prop) { return [].concat.apply([], datamap.getRange({row: 0, col: datamap.propToCol(prop)}, {row: priv.settings.data.length - 1, col: datamap.propToCol(prop)}, datamap.DESTINATION_RENDERER)); }; /** * Return value at `row` * @param {Number} row * @public * @return value (mixed data type) */ this.getDataAtRow = function (row) { return priv.settings.data[row]; }; /** * Returns cell meta data object corresponding to params row, col * @param {Number} row * @param {Number} col * @public * @return {Object} */ this.getCellMeta = function (row, col) { var prop = datamap.colToProp(col) , cellProperties; row = translateRowIndex(row); col = translateColIndex(col); if ("undefined" === typeof priv.columnSettings[col]) { priv.columnSettings[col] = Handsontable.helper.columnFactory(GridSettings, priv.columnsSettingConflicts); } if (!priv.cellSettings[row]) { priv.cellSettings[row] = []; } if (!priv.cellSettings[row][col]) { priv.cellSettings[row][col] = new priv.columnSettings[col](); } cellProperties = priv.cellSettings[row][col]; //retrieve cellProperties from cache cellProperties.row = row; cellProperties.col = col; cellProperties.prop = prop; cellProperties.instance = instance; instance.PluginHooks.run('beforeGetCellMeta', row, col, cellProperties); Handsontable.helper.extend(cellProperties, expandType(cellProperties)); //for `type` added in beforeGetCellMeta if (cellProperties.cells) { var settings = cellProperties.cells.call(cellProperties, row, col, prop); if (settings) { Handsontable.helper.extend(cellProperties, settings); Handsontable.helper.extend(cellProperties, expandType(settings)); //for `type` added in cells } } instance.PluginHooks.run('afterGetCellMeta', row, col, cellProperties); return cellProperties; /** * If displayed rows order is different than the order of rows stored in memory (i.e. sorting is applied) * we need to translate logical (stored) row index to physical (displayed) index. * @param row - original row index * @returns {int} translated row index */ function translateRowIndex(row){ var getVars = {row: row}; instance.PluginHooks.execute('beforeGet', getVars); return getVars.row; } /** * If displayed columns order is different than the order of columns stored in memory (i.e. column were moved using manualColumnMove plugin) * we need to translate logical (stored) column index to physical (displayed) index. * @param col - original column index * @returns {int} - translated column index */ function translateColIndex(col){ return Handsontable.PluginHooks.execute(instance, 'modifyCol', col); // warning: this must be done after datamap.colToProp } }; var rendererLookup = Handsontable.helper.cellMethodLookupFactory('renderer'); this.getCellRenderer = function (row, col) { var renderer = rendererLookup.call(this, row, col); return Handsontable.renderers.getRenderer(renderer); }; this.getCellEditor = Handsontable.helper.cellMethodLookupFactory('editor'); this.getCellValidator = Handsontable.helper.cellMethodLookupFactory('validator'); /** * Validates all cells using their validator functions and calls callback when finished. Does not render the view * @param callback */ this.validateCells = function (callback) { var waitingForValidator = new ValidatorsQueue(); waitingForValidator.onQueueEmpty = callback; var i = instance.countRows() - 1; while (i >= 0) { var j = instance.countCols() - 1; while (j >= 0) { waitingForValidator.addValidatorToQueue(); instance.validateCell(instance.getDataAtCell(i, j), instance.getCellMeta(i, j), function () { waitingForValidator.removeValidatorFormQueue(); }, 'validateCells'); j--; } i--; } waitingForValidator.checkIfQueueIsEmpty(); }; /** * Return array of row headers (if they are enabled). If param `row` given, return header at given row as string * @param {Number} row (Optional) * @return {Array|String} */ this.getRowHeader = function (row) { if (row === void 0) { var out = []; for (var i = 0, ilen = instance.countRows(); i < ilen; i++) { out.push(instance.getRowHeader(i)); } return out; } else if (Object.prototype.toString.call(priv.settings.rowHeaders) === '[object Array]' && priv.settings.rowHeaders[row] !== void 0) { return priv.settings.rowHeaders[row]; } else if (typeof priv.settings.rowHeaders === 'function') { return priv.settings.rowHeaders(row); } else if (priv.settings.rowHeaders && typeof priv.settings.rowHeaders !== 'string' && typeof priv.settings.rowHeaders !== 'number') { return row + 1; } else { return priv.settings.rowHeaders; } }; /** * Returns information of this table is configured to display row headers * @returns {boolean} */ this.hasRowHeaders = function () { return !!priv.settings.rowHeaders; }; /** * Returns information of this table is configured to display column headers * @returns {boolean} */ this.hasColHeaders = function () { if (priv.settings.colHeaders !== void 0 && priv.settings.colHeaders !== null) { //Polymer has empty value = null return !!priv.settings.colHeaders; } for (var i = 0, ilen = instance.countCols(); i < ilen; i++) { if (instance.getColHeader(i)) { return true; } } return false; }; /** * Return array of column headers (if they are enabled). If param `col` given, return header at given column as string * @param {Number} col (Optional) * @return {Array|String} */ this.getColHeader = function (col) { if (col === void 0) { var out = []; for (var i = 0, ilen = instance.countCols(); i < ilen; i++) { out.push(instance.getColHeader(i)); } return out; } else { col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col); if (priv.settings.columns && priv.settings.columns[col] && priv.settings.columns[col].title) { return priv.settings.columns[col].title; } else if (Object.prototype.toString.call(priv.settings.colHeaders) === '[object Array]' && priv.settings.colHeaders[col] !== void 0) { return priv.settings.colHeaders[col]; } else if (typeof priv.settings.colHeaders === 'function') { return priv.settings.colHeaders(col); } else if (priv.settings.colHeaders && typeof priv.settings.colHeaders !== 'string' && typeof priv.settings.colHeaders !== 'number') { return Handsontable.helper.spreadsheetColumnLabel(col); } else { return priv.settings.colHeaders; } } }; /** * Return column width from settings (no guessing). Private use intended * @param {Number} col * @return {Number} */ this._getColWidthFromSettings = function (col) { var cellProperties = instance.getCellMeta(0, col); var width = cellProperties.width; if (width === void 0 || width === priv.settings.width) { width = cellProperties.colWidths; } if (width !== void 0 && width !== null) { switch (typeof width) { case 'object': //array width = width[col]; break; case 'function': width = width(col); break; } if (typeof width === 'string') { width = parseInt(width, 10); } } return width; }; /** * Return column width * @param {Number} col * @return {Number} */ this.getColWidth = function (col) { col = Handsontable.PluginHooks.execute(instance, 'modifyCol', col); var response = { width: instance._getColWidthFromSettings(col) }; if (!response.width) { response.width = 50; } instance.PluginHooks.run('afterGetColWidth', col, response); return response.width; }; /** * Return total number of rows in grid * @return {Number} */ this.countRows = function () { return priv.settings.data.length; }; /** * Return total number of columns in grid * @return {Number} */ this.countCols = function () { if (instance.dataType === 'object' || instance.dataType === 'function') { if (priv.settings.columns && priv.settings.columns.length) { return priv.settings.columns.length; } else { return datamap.colToPropCache.length; } } else if (instance.dataType === 'array') { if (priv.settings.columns && priv.settings.columns.length) { return priv.settings.columns.length; } else if (priv.settings.data && priv.settings.data[0] && priv.settings.data[0].length) { return priv.settings.data[0].length; } else { return 0; } } }; /** * Return index of first visible row * @return {Number} */ this.rowOffset = function () { return instance.view.wt.getSetting('offsetRow'); }; /** * Return index of first visible column * @return {Number} */ this.colOffset = function () { return instance.view.wt.getSetting('offsetColumn'); }; /** * Return number of visible rows. Returns -1 if table is not visible * @return {Number} */ this.countVisibleRows = function () { return instance.view.wt.drawn ? instance.view.wt.wtTable.rowStrategy.countVisible() : -1; }; /** * Return number of visible columns. Returns -1 if table is not visible * @return {Number} */ this.countVisibleCols = function () { return instance.view.wt.drawn ? instance.view.wt.wtTable.columnStrategy.countVisible() : -1; }; /** * Return number of empty rows * @return {Boolean} ending If true, will only count empty rows at the end of the data source */ this.countEmptyRows = function (ending) { var i = instance.countRows() - 1 , empty = 0; while (i >= 0) { datamap.get(i, 0); if (instance.isEmptyRow(datamap.getVars.row)) { empty++; } else if (ending) { break; } i--; } return empty; }; /** * Return number of empty columns * @return {Boolean} ending If true, will only count empty columns at the end of the data source row */ this.countEmptyCols = function (ending) { if (instance.countRows() < 1) { return 0; } var i = instance.countCols() - 1 , empty = 0; while (i >= 0) { if (instance.isEmptyCol(i)) { empty++; } else if (ending) { break; } i--; } return empty; }; /** * Return true if the row at the given index is empty, false otherwise * @param {Number} r Row index * @return {Boolean} */ this.isEmptyRow = function (r) { return priv.settings.isEmptyRow.call(instance, r); }; /** * Return true if the column at the given index is empty, false otherwise * @param {Number} c Column index * @return {Boolean} */ this.isEmptyCol = function (c) { return priv.settings.isEmptyCol.call(instance, c); }; /** * Selects cell on grid. Optionally selects range to another cell * @param {Number} row * @param {Number} col * @param {Number} [endRow] * @param {Number} [endCol] * @param {Boolean} [scrollToCell=true] If true, viewport will be scrolled to the selection * @public * @return {Boolean} */ this.selectCell = function (row, col, endRow, endCol, scrollToCell) { if (typeof row !== 'number' || row < 0 || row >= instance.countRows()) { return false; } if (typeof col !== 'number' || col < 0 || col >= instance.countCols()) { return false; } if (typeof endRow !== "undefined") { if (typeof endRow !== 'number' || endRow < 0 || endRow >= instance.countRows()) { return false; } if (typeof endCol !== 'number' || endCol < 0 || endCol >= instance.countCols()) { return false; } } priv.selStart.coords({row: row, col: col}); if (document.activeElement && document.activeElement !== document.documentElement && document.activeElement !== document.body) { document.activeElement.blur(); //needed or otherwise prepare won't focus the cell. selectionSpec tests this (should move focus to selected cell) } instance.listen(); if (typeof endRow === "undefined") { selection.setRangeEnd({row: row, col: col}, scrollToCell); } else { selection.setRangeEnd({row: endRow, col: endCol}, scrollToCell); } instance.selection.finish(); return true; }; this.selectCellByProp = function (row, prop, endRow, endProp, scrollToCell) { arguments[1] = datamap.propToCol(arguments[1]); if (typeof arguments[3] !== "undefined") { arguments[3] = datamap.propToCol(arguments[3]); } return instance.selectCell.apply(instance, arguments); }; /** * Deselects current sell selection on grid * @public */ this.deselectCell = function () { selection.deselect(); }; /** * Remove grid from DOM * @public */ this.destroy = function () { instance.clearTimeouts(); if (instance.view) { //in case HT is destroyed before initialization has finished instance.view.wt.destroy(); } instance.rootElement.empty(); instance.rootElement.removeData('handsontable'); instance.rootElement.off('.handsontable'); $(window).off('.' + instance.guid); $document.off('.' + instance.guid); $body.off('.' + instance.guid); instance.PluginHooks.run('afterDestroy'); }; /** * Returns active editor object * @returns {Object} */ this.getActiveEditor = function(){ return editorManager.getActiveEditor(); }; /** * Return Handsontable instance * @public * @return {Object} */ this.getInstance = function () { return instance.rootElement.data("handsontable"); }; (function () { // Create new instance of plugin hooks instance.PluginHooks = new Handsontable.PluginHookClass(); // Upgrade methods to call of global PluginHooks instance var _run = instance.PluginHooks.run , _exe = instance.PluginHooks.execute; instance.PluginHooks.run = function (key, p1, p2, p3, p4, p5) { _run.call(this, instance, key, p1, p2, p3, p4, p5); Handsontable.PluginHooks.run(instance, key, p1, p2, p3, p4, p5); }; instance.PluginHooks.execute = function (key, p1, p2, p3, p4, p5) { var globalHandlerResult = Handsontable.PluginHooks.execute(instance, key, p1, p2, p3, p4, p5); var localHandlerResult = _exe.call(this, instance, key, globalHandlerResult, p2, p3, p4, p5); return typeof localHandlerResult == 'undefined' ? globalHandlerResult : localHandlerResult; }; // Map old API with new methods instance.addHook = function () { instance.PluginHooks.add.apply(instance.PluginHooks, arguments); }; instance.addHookOnce = function () { instance.PluginHooks.once.apply(instance.PluginHooks, arguments); }; instance.removeHook = function () { instance.PluginHooks.remove.apply(instance.PluginHooks, arguments); }; instance.runHooks = function () { instance.PluginHooks.run.apply(instance.PluginHooks, arguments); }; instance.runHooksAndReturn = function () { return instance.PluginHooks.execute.apply(instance.PluginHooks, arguments); }; })(); this.timeouts = {}; /** * Sets timeout. Purpose of this method is to clear all known timeouts when `destroy` method is called * @public */ this.registerTimeout = function (key, handle, ms) { clearTimeout(this.timeouts[key]); this.timeouts[key] = setTimeout(handle, ms || 0); }; /** * Clears all known timeouts * @public */ this.clearTimeouts = function () { for (var key in this.timeouts) { if (this.timeouts.hasOwnProperty(key)) { clearTimeout(this.timeouts[key]); } } }; /** * Handsontable version */ this.version = '0.10.2'; //inserted by grunt from package.json }; var DefaultSettings = function () {}; DefaultSettings.prototype = { data: void 0, width: void 0, height: void 0, startRows: 5, startCols: 5, rowHeaders: null, colHeaders: null, minRows: 0, minCols: 0, maxRows: Infinity, maxCols: Infinity, minSpareRows: 0, minSpareCols: 0, multiSelect: true, fillHandle: true, fixedRowsTop: 0, fixedColumnsLeft: 0, outsideClickDeselects: true, enterBeginsEditing: true, enterMoves: {row: 1, col: 0}, tabMoves: {row: 0, col: 1}, autoWrapRow: false, autoWrapCol: false, copyRowsLimit: 1000, copyColsLimit: 1000, pasteMode: 'overwrite', currentRowClassName: void 0, currentColClassName: void 0, stretchH: 'hybrid', isEmptyRow: function (r) { var val; for (var c = 0, clen = this.countCols(); c < clen; c++) { val = this.getDataAtCell(r, c); if (val !== '' && val !== null && typeof val !== 'undefined') { return false; } } return true; }, isEmptyCol: function (c) { var val; for (var r = 0, rlen = this.countRows(); r < rlen; r++) { val = this.getDataAtCell(r, c); if (val !== '' && val !== null && typeof val !== 'undefined') { return false; } } return true; }, observeDOMVisibility: true, allowInvalid: true, invalidCellClassName: 'htInvalid', placeholderCellClassName: 'htPlaceholder', readOnlyCellClassName: 'htDimmed', fragmentSelection: false, readOnly: false, nativeScrollbars: false, type: 'text', copyable: true, debug: false //shows debug overlays in Walkontable }; Handsontable.DefaultSettings = DefaultSettings; $.fn.handsontable = function (action) { var i , ilen , args , output , userSettings , $this = this.first() // Use only first element from list , instance = $this.data('handsontable'); // Init case if (typeof action !== 'string') { userSettings = action || {}; if (instance) { instance.updateSettings(userSettings); } else { instance = new Handsontable.Core($this, userSettings); $this.data('handsontable', instance); instance.init(); } return $this; } // Action case else { args = []; if (arguments.length > 1) { for (i = 1, ilen = arguments.length; i < ilen; i++) { args.push(arguments[i]); } } if (instance) { if (typeof instance[action] !== 'undefined') { output = instance[action].apply(instance, args); } else { throw new Error('Handsontable do not provide action: ' + action); } } return output; } }; /** * Handsontable TableView constructor * @param {Object} instance */ Handsontable.TableView = function (instance) { var that = this , $window = $(window) , $documentElement = $(document.documentElement); this.instance = instance; this.settings = instance.getSettings(); this.settingsFromDOM = instance.getSettingsFromDOM(); instance.rootElement.data('originalStyle', instance.rootElement[0].getAttribute('style')); //needed to retrieve original style in jsFiddle link generator in HT examples. may be removed in future versions // in IE7 getAttribute('style') returns an object instead of a string, but we only support IE8+ instance.rootElement.addClass('handsontable'); var table = document.createElement('TABLE'); table.className = 'htCore'; this.THEAD = document.createElement('THEAD'); table.appendChild(this.THEAD); this.TBODY = document.createElement('TBODY'); table.appendChild(this.TBODY); instance.$table = $(table); instance.rootElement.prepend(instance.$table); instance.rootElement.on('mousedown.handsontable', function (event) { if (!that.isTextSelectionAllowed(event.target)) { clearTextSelection(); event.preventDefault(); window.focus(); //make sure that window that contains HOT is active. Important when HOT is in iframe. } }); $documentElement.on('keyup.' + instance.guid, function (event) { if (instance.selection.isInProgress() && !event.shiftKey) { instance.selection.finish(); } }); var isMouseDown; $documentElement.on('mouseup.' + instance.guid, function (event) { if (instance.selection.isInProgress() && event.which === 1) { //is left mouse button instance.selection.finish(); } isMouseDown = false; if (instance.autofill.handle && instance.autofill.handle.isDragged) { if (instance.autofill.handle.isDragged > 1) { instance.autofill.apply(); } instance.autofill.handle.isDragged = 0; } if (Handsontable.helper.isOutsideInput(document.activeElement)) { instance.unlisten(); } }); $documentElement.on('mousedown.' + instance.guid, function (event) { var next = event.target; if (next !== that.wt.wtTable.spreader) { //immediate click on "spreader" means click on the right side of vertical scrollbar while (next !== document.documentElement) { if (next === null) { return; //click on something that was a row but now is detached (possibly because your click triggered a rerender) } if (next === instance.rootElement[0] || next.nodeName === 'HANDSONTABLE-TABLE') { return; //click inside container or Web Component (HANDSONTABLE-TABLE is the name of the custom element) } next = next.parentNode; } } if (that.settings.outsideClickDeselects) { instance.deselectCell(); } else { instance.destroyEditor(); } }); instance.rootElement.on('mousedown.handsontable', '.dragdealer', function () { instance.destroyEditor(); }); instance.$table.on('selectstart', function (event) { if (that.settings.fragmentSelection) { return; } //https://github.com/warpech/jquery-handsontable/issues/160 //selectstart is IE only event. Prevent text from being selected when performing drag down in IE8 event.preventDefault(); }); var clearTextSelection = function () { //http://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript if (window.getSelection) { if (window.getSelection().empty) { // Chrome window.getSelection().empty(); } else if (window.getSelection().removeAllRanges) { // Firefox window.getSelection().removeAllRanges(); } } else if (document.selection) { // IE? document.selection.empty(); } }; var walkontableConfig = { debug: function () { return that.settings.debug; }, table: table, stretchH: this.settings.stretchH, data: instance.getDataAtCell, totalRows: instance.countRows, totalColumns: instance.countCols, nativeScrollbars: this.settings.nativeScrollbars, offsetRow: 0, offsetColumn: 0, width: this.getWidth(), height: this.getHeight(), fixedColumnsLeft: function () { return that.settings.fixedColumnsLeft; }, fixedRowsTop: function () { return that.settings.fixedRowsTop; }, rowHeaders: function () { return instance.hasRowHeaders() ? [function (index, TH) { that.appendRowHeader(index, TH); }] : [] }, columnHeaders: function () { return instance.hasColHeaders() ? [function (index, TH) { that.appendColHeader(index, TH); }] : [] }, columnWidth: instance.getColWidth, cellRenderer: function (row, col, TD) { var prop = that.instance.colToProp(col) , cellProperties = that.instance.getCellMeta(row, col) , renderer = that.instance.getCellRenderer(cellProperties); var value = that.instance.getDataAtRowProp(row, prop); renderer(that.instance, TD, row, col, prop, value, cellProperties); that.instance.PluginHooks.run('afterRenderer', TD, row, col, prop, value, cellProperties); }, selections: { current: { className: 'current', border: { width: 2, color: '#5292F7', style: 'solid', cornerVisible: function () { return that.settings.fillHandle && !that.isCellEdited() && !instance.selection.isMultiple() } } }, area: { className: 'area', border: { width: 1, color: '#89AFF9', style: 'solid', cornerVisible: function () { return that.settings.fillHandle && !that.isCellEdited() && instance.selection.isMultiple() } } }, highlight: { highlightRowClassName: that.settings.currentRowClassName, highlightColumnClassName: that.settings.currentColClassName }, fill: { className: 'fill', border: { width: 1, color: 'red', style: 'solid' } } }, hideBorderOnMouseDownOver: function () { return that.settings.fragmentSelection; }, onCellMouseDown: function (event, coords, TD) { instance.listen(); isMouseDown = true; var coordsObj = {row: coords[0], col: coords[1]}; if (event.button === 2 && instance.selection.inInSelection(coordsObj)) { //right mouse button //do nothing } else if (event.shiftKey) { instance.selection.setRangeEnd(coordsObj); } else { instance.selection.setRangeStart(coordsObj); } instance.PluginHooks.run('afterOnCellMouseDown', event, coords, TD); }, /*onCellMouseOut: function (/*event, coords, TD* /) { if (isMouseDown && that.settings.fragmentSelection === 'single') { clearTextSelection(); //otherwise text selection blinks during multiple cells selection } },*/ onCellMouseOver: function (event, coords, TD) { var coordsObj = {row: coords[0], col: coords[1]}; if (isMouseDown) { /*if (that.settings.fragmentSelection === 'single') { clearTextSelection(); //otherwise text selection blinks during multiple cells selection }*/ instance.selection.setRangeEnd(coordsObj); } else if (instance.autofill.handle && instance.autofill.handle.isDragged) { instance.autofill.handle.isDragged++; instance.autofill.showBorder(coords); } instance.PluginHooks.run('afterOnCellMouseOver', event, coords, TD); }, onCellCornerMouseDown: function (event) { instance.autofill.handle.isDragged = 1; event.preventDefault(); instance.PluginHooks.run('afterOnCellCornerMouseDown', event); }, onCellCornerDblClick: function () { instance.autofill.selectAdjacent(); }, beforeDraw: function (force) { that.beforeRender(force); }, onDraw: function(force){ that.onDraw(force); }, onScrollVertically: function () { instance.runHooks('afterScrollVertically'); }, onScrollHorizontally: function () { instance.runHooks('afterScrollHorizontally'); } }; instance.PluginHooks.run('beforeInitWalkontable', walkontableConfig); this.wt = new Walkontable(walkontableConfig); $window.on('resize.' + instance.guid, function () { instance.registerTimeout('resizeTimeout', function () { instance.parseSettingsFromDOM(); var newWidth = that.getWidth(); var newHeight = that.getHeight(); if (walkontableConfig.width !== newWidth || walkontableConfig.height !== newHeight) { instance.forceFullRender = true; that.render(); walkontableConfig.width = newWidth; walkontableConfig.height = newHeight; } }, 60); }); $(that.wt.wtTable.spreader).on('mousedown.handsontable, contextmenu.handsontable', function (event) { if (event.target === that.wt.wtTable.spreader && event.which === 3) { //right mouse button exactly on spreader means right clickon the right hand side of vertical scrollbar event.stopPropagation(); } }); $documentElement.on('click.' + instance.guid, function () { if (that.settings.observeDOMVisibility) { if (that.wt.drawInterrupted) { that.instance.forceFullRender = true; that.render(); } } }); }; Handsontable.TableView.prototype.isTextSelectionAllowed = function (el) { if ( Handsontable.helper.isInput(el) ) { return (true); } if (this.settings.fragmentSelection && this.wt.wtDom.isChildOf(el, this.TBODY)) { return (true); } return false; }; Handsontable.TableView.prototype.isCellEdited = function () { var activeEditor = this.instance.getActiveEditor(); return activeEditor && activeEditor.isOpened(); }; Handsontable.TableView.prototype.getWidth = function () { var val = this.settings.width !== void 0 ? this.settings.width : this.settingsFromDOM.width; return typeof val === 'function' ? val() : val; }; Handsontable.TableView.prototype.getHeight = function () { var val = this.settings.height !== void 0 ? this.settings.height : this.settingsFromDOM.height; return typeof val === 'function' ? val() : val; }; Handsontable.TableView.prototype.beforeRender = function (force) { if (force) { //force = did Walkontable decide to do full render this.instance.PluginHooks.run('beforeRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render? this.wt.update('width', this.getWidth()); this.wt.update('height', this.getHeight()); } }; Handsontable.TableView.prototype.onDraw = function(force){ if (force) { //force = did Walkontable decide to do full render this.instance.PluginHooks.run('afterRender', this.instance.forceFullRender); //this.instance.forceFullRender = did Handsontable request full render? } }; Handsontable.TableView.prototype.render = function () { this.wt.draw(!this.instance.forceFullRender); this.instance.forceFullRender = false; this.instance.rootElement.triggerHandler('render.handsontable'); }; /** * Returns td object given coordinates */ Handsontable.TableView.prototype.getCellAtCoords = function (coords) { var td = this.wt.wtTable.getCell([coords.row, coords.col]); if (td < 0) { //there was an exit code (cell is out of bounds) return null; } else { return td; } }; /** * Scroll viewport to selection * @param coords */ Handsontable.TableView.prototype.scrollViewport = function (coords) { this.wt.scrollViewport([coords.row, coords.col]); }; /** * Append row header to a TH element * @param row * @param TH */ Handsontable.TableView.prototype.appendRowHeader = function (row, TH) { if (row > -1) { this.wt.wtDom.fastInnerHTML(TH, this.instance.getRowHeader(row)); } else { var DIV = document.createElement('DIV'); DIV.className = 'relative'; this.wt.wtDom.fastInnerText(DIV, '\u00A0'); this.wt.wtDom.empty(TH); TH.appendChild(DIV); } }; /** * Append column header to a TH element * @param col * @param TH */ Handsontable.TableView.prototype.appendColHeader = function (col, TH) { var DIV = document.createElement('DIV') , SPAN = document.createElement('SPAN'); DIV.className = 'relative'; SPAN.className = 'colHeader'; this.wt.wtDom.fastInnerHTML(SPAN, this.instance.getColHeader(col)); DIV.appendChild(SPAN); this.wt.wtDom.empty(TH); TH.appendChild(DIV); this.instance.PluginHooks.run('afterGetColHeader', col, TH); }; /** * Given a element's left position relative to the viewport, returns maximum element width until the right edge of the viewport (before scrollbar) * @param {Number} left * @return {Number} */ Handsontable.TableView.prototype.maximumVisibleElementWidth = function (left) { var rootWidth = this.wt.wtViewport.getWorkspaceWidth(); if(this.settings.nativeScrollbars) { return rootWidth; } return rootWidth - left; }; /** * Given a element's top position relative to the viewport, returns maximum element height until the bottom edge of the viewport (before scrollbar) * @param {Number} top * @return {Number} */ Handsontable.TableView.prototype.maximumVisibleElementHeight = function (top) { var rootHeight = this.wt.wtViewport.getWorkspaceHeight(); if(this.settings.nativeScrollbars) { return rootHeight; } return rootHeight - top; }; /** * Utility to register editors and common namespace for keeping reference to all editor classes */ (function (Handsontable) { 'use strict'; function RegisteredEditor(editorClass) { var clazz, instances; instances = {}; clazz = editorClass; this.getInstance = function (hotInstance) { if (!(hotInstance.guid in instances)) { instances[hotInstance.guid] = new clazz(hotInstance); } return instances[hotInstance.guid]; } } var registeredEditorNames = {}; var registeredEditorClasses = new WeakMap(); Handsontable.editors = { /** * Registers editor under given name * @param {String} editorName * @param {Function} editorClass */ registerEditor: function (editorName, editorClass) { var editor = new RegisteredEditor(editorClass); if (typeof editorName === "string") { registeredEditorNames[editorName] = editor; } registeredEditorClasses.set(editorClass, editor); }, /** * Returns instance (singleton) of editor class * @param {String|Function} editorName/editorClass * @returns {Function} editorClass */ getEditor: function (editorName, hotInstance) { var editor; if (typeof editorName == 'function') { if (!(registeredEditorClasses.get(editorName))) { this.registerEditor(null, editorName); } editor = registeredEditorClasses.get(editorName); } else if (typeof editorName == 'string') { editor = registeredEditorNames[editorName]; } else { throw Error('Only strings and functions can be passed as "editor" parameter '); } if (!editor) { throw Error('No editor registered under name "' + editorName + '"'); } return editor.getInstance(hotInstance); } }; })(Handsontable); (function(Handsontable){ 'use strict'; Handsontable.EditorManager = function(instance, priv, selection){ var that = this; var $document = $(document); var keyCodes = Handsontable.helper.keyCode; var activeEditor; var init = function () { function onKeyDown(event) { if (!instance.isListening()) { return; } if (priv.settings.beforeOnKeyDown) { // HOT in HOT Plugin priv.settings.beforeOnKeyDown.call(instance, event); } instance.PluginHooks.run('beforeKeyDown', event); if (!event.isImmediatePropagationStopped()) { priv.lastKeyCode = event.keyCode; if (selection.isSelected()) { var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) if (!activeEditor.isWaiting()) { if (!Handsontable.helper.isMetaKey(event.keyCode) && !ctrlDown) { that.openEditor(''); event.stopPropagation(); //required by HandsontableEditor return; } } var rangeModifier = event.shiftKey ? selection.setRangeEnd : selection.setRangeStart; switch (event.keyCode) { case keyCodes.A: if (ctrlDown) { selection.selectAll(); //select all cells event.preventDefault(); event.stopPropagation(); break; } case keyCodes.ARROW_UP: if (that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionUp(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_DOWN: if (that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionDown(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_RIGHT: if(that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionRight(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.ARROW_LEFT: if(that.isEditorOpened() && !activeEditor.isWaiting()){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionLeft(event.shiftKey); event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.TAB: var tabMoves = typeof priv.settings.tabMoves === 'function' ? priv.settings.tabMoves(event) : priv.settings.tabMoves; if (event.shiftKey) { selection.transformStart(-tabMoves.row, -tabMoves.col); //move selection left } else { selection.transformStart(tabMoves.row, tabMoves.col, true); //move selection right (add a new column if needed) } event.preventDefault(); event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.BACKSPACE: case keyCodes.DELETE: selection.empty(event); that.prepareEditor(); event.preventDefault(); break; case keyCodes.F2: /* F2 */ that.openEditor(); event.preventDefault(); //prevent Opera from opening Go to Page dialog break; case keyCodes.ENTER: /* return/enter */ if(that.isEditorOpened()){ if (activeEditor.state !== Handsontable.EditorState.WAITING){ that.closeEditorAndSaveChanges(ctrlDown); } moveSelectionAfterEnter(event.shiftKey); } else { if (instance.getSettings().enterBeginsEditing){ that.openEditor(); } else { moveSelectionAfterEnter(event.shiftKey); } } event.preventDefault(); //don't add newline to field event.stopImmediatePropagation(); //required by HandsontableEditor break; case keyCodes.ESCAPE: if(that.isEditorOpened()){ that.closeEditorAndRestoreOriginalValue(ctrlDown); } event.preventDefault(); break; case keyCodes.HOME: if (event.ctrlKey || event.metaKey) { rangeModifier({row: 0, col: priv.selStart.col()}); } else { rangeModifier({row: priv.selStart.row(), col: 0}); } event.preventDefault(); //don't scroll the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.END: if (event.ctrlKey || event.metaKey) { rangeModifier({row: instance.countRows() - 1, col: priv.selStart.col()}); } else { rangeModifier({row: priv.selStart.row(), col: instance.countCols() - 1}); } event.preventDefault(); //don't scroll the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.PAGE_UP: selection.transformStart(-instance.countVisibleRows(), 0); instance.view.wt.scrollVertical(-instance.countVisibleRows()); instance.view.render(); event.preventDefault(); //don't page up the window event.stopPropagation(); //required by HandsontableEditor break; case keyCodes.PAGE_DOWN: selection.transformStart(instance.countVisibleRows(), 0); instance.view.wt.scrollVertical(instance.countVisibleRows()); instance.view.render(); event.preventDefault(); //don't page down the window event.stopPropagation(); //required by HandsontableEditor break; default: break; } } } } $document.on('keydown.handsontable.' + instance.guid, onKeyDown); function onDblClick() { // that.instance.destroyEditor(); that.openEditor(); } instance.view.wt.update('onCellDblClick', onDblClick); instance.addHook('afterDestroy', function(){ $document.off('keydown.handsontable.' + instance.guid); }); function moveSelectionAfterEnter(shiftKey){ var enterMoves = typeof priv.settings.enterMoves === 'function' ? priv.settings.enterMoves(event) : priv.settings.enterMoves; if (shiftKey) { selection.transformStart(-enterMoves.row, -enterMoves.col); //move selection up } else { selection.transformStart(enterMoves.row, enterMoves.col, true); //move selection down (add a new row if needed) } } function moveSelectionUp(shiftKey){ if (shiftKey) { selection.transformEnd(-1, 0); } else { selection.transformStart(-1, 0); } } function moveSelectionDown(shiftKey){ if (shiftKey) { selection.transformEnd(1, 0); //expanding selection down with shift } else { selection.transformStart(1, 0); //move selection down } } function moveSelectionRight(shiftKey){ if (shiftKey) { selection.transformEnd(0, 1); } else { selection.transformStart(0, 1); } } function moveSelectionLeft(shiftKey){ if (shiftKey) { selection.transformEnd(0, -1); } else { selection.transformStart(0, -1); } } }; /** * Destroy current editor, if exists * @param {Boolean} revertOriginal */ this.destroyEditor = function (revertOriginal) { this.closeEditor(revertOriginal); }; this.getActiveEditor = function () { return activeEditor; }; /** * Prepare text input to be displayed at given grid cell */ this.prepareEditor = function () { if (activeEditor && activeEditor.isWaiting()){ this.closeEditor(false, false, function(dataSaved){ if(dataSaved){ that.prepareEditor(); } }); return; } var row = priv.selStart.row(); var col = priv.selStart.col(); var prop = instance.colToProp(col); var td = instance.getCell(row, col); var originalValue = instance.getDataAtCell(row, col); var cellProperties = instance.getCellMeta(row, col); var editorClass = instance.getCellEditor(cellProperties); activeEditor = Handsontable.editors.getEditor(editorClass, instance); activeEditor.prepare(row, col, prop, td, originalValue, cellProperties); }; this.isEditorOpened = function () { return activeEditor.isOpened(); }; this.openEditor = function (initialValue) { activeEditor.beginEditing(initialValue); }; this.closeEditor = function (restoreOriginalValue, ctrlDown, callback) { if (!activeEditor){ if(callback) { callback(false); } } else { activeEditor.finishEditing(restoreOriginalValue, ctrlDown, callback); } }; this.closeEditorAndSaveChanges = function(ctrlDown){ return this.closeEditor(false, ctrlDown); }; this.closeEditorAndRestoreOriginalValue = function(ctrlDown){ return this.closeEditor(true, ctrlDown); }; init(); }; })(Handsontable); /** * Utility to register renderers and common namespace for keeping reference to all renderers classes */ (function (Handsontable) { 'use strict'; var registeredRenderers = {}; Handsontable.renderers = { /** * Registers renderer under given name * @param {String} rendererName * @param {Function} rendererFunction */ registerRenderer: function (rendererName, rendererFunction) { registeredRenderers[rendererName] = rendererFunction }, /** * @param {String|Function} rendererName/rendererFunction * @returns {Function} rendererFunction */ getRenderer: function (rendererName) { if (typeof rendererName == 'function'){ return rendererName; } if (typeof rendererName != 'string'){ throw Error('Only strings and functions can be passed as "renderer" parameter '); } if (!(rendererName in registeredRenderers)) { throw Error('No editor registered under name "' + rendererName + '"'); } return registeredRenderers[rendererName]; } }; })(Handsontable); /** * DOM helper optimized for maximum performance * It is recommended for Handsontable plugins and renderers, because it is much faster than jQuery * @type {WalkonableDom} */ Handsontable.Dom = new WalkontableDom(); /** * Returns true if keyCode represents a printable character * @param {Number} keyCode * @return {Boolean} */ Handsontable.helper.isPrintableChar = function (keyCode) { return ((keyCode == 32) || //space (keyCode >= 48 && keyCode <= 57) || //0-9 (keyCode >= 96 && keyCode <= 111) || //numpad (keyCode >= 186 && keyCode <= 192) || //;=,-./` (keyCode >= 219 && keyCode <= 222) || //[]{}\|"' keyCode >= 226 || //special chars (229 for Asian chars) (keyCode >= 65 && keyCode <= 90)); //a-z }; Handsontable.helper.isMetaKey = function (keyCode) { var keyCodes = Handsontable.helper.keyCode; var metaKeys = [ keyCodes.ARROW_DOWN, keyCodes.ARROW_UP, keyCodes.ARROW_LEFT, keyCodes.ARROW_RIGHT, keyCodes.HOME, keyCodes.END, keyCodes.DELETE, keyCodes.BACKSPACE, keyCodes.F1, keyCodes.F2, keyCodes.F3, keyCodes.F4, keyCodes.F5, keyCodes.F6, keyCodes.F7, keyCodes.F8, keyCodes.F9, keyCodes.F10, keyCodes.F11, keyCodes.F12, keyCodes.TAB, keyCodes.PAGE_DOWN, keyCodes.PAGE_UP, keyCodes.ENTER, keyCodes.ESCAPE, keyCodes.SHIFT, keyCodes.CAPS_LOCK, keyCodes.ALT ]; return metaKeys.indexOf(keyCode) != -1; }; Handsontable.helper.isCtrlKey = function (keyCode) { var keys = Handsontable.helper.keyCode; return [keys.CONTROL_LEFT, 224, keys.COMMAND_LEFT, keys.COMMAND_RIGHT].indexOf(keyCode) != -1; }; /** * Converts a value to string * @param value * @return {String} */ Handsontable.helper.stringify = function (value) { switch (typeof value) { case 'string': case 'number': return value + ''; break; case 'object': if (value === null) { return ''; } else { return value.toString(); } break; case 'undefined': return ''; break; default: return value.toString(); } }; /** * Generates spreadsheet-like column names: A, B, C, ..., Z, AA, AB, etc * @param index * @returns {String} */ Handsontable.helper.spreadsheetColumnLabel = function (index) { var dividend = index + 1; var columnLabel = ''; var modulo; while (dividend > 0) { modulo = (dividend - 1) % 26; columnLabel = String.fromCharCode(65 + modulo) + columnLabel; dividend = parseInt((dividend - modulo) / 26, 10); } return columnLabel; }; /** * Checks if value of n is a numeric one * http://jsperf.com/isnan-vs-isnumeric/4 * @param n * @returns {boolean} */ Handsontable.helper.isNumeric = function (n) { var t = typeof n; return t == 'number' ? !isNaN(n) && isFinite(n) : t == 'string' ? !n.length ? false : n.length == 1 ? /\d/.test(n) : /^\s*[+-]?\s*(?:(?:\d+(?:\.\d+)?(?:e[+-]?\d+)?)|(?:0x[a-f\d]+))\s*$/i.test(n) : t == 'object' ? !!n && typeof n.valueOf() == "number" && !(n instanceof Date) : false; }; Handsontable.helper.isArray = function (obj) { return Object.prototype.toString.call(obj).match(/array/i) !== null; }; /** * Checks if child is a descendant of given parent node * http://stackoverflow.com/questions/2234979/how-to-check-in-javascript-if-one-element-is-a-child-of-another * @param parent * @param child * @returns {boolean} */ Handsontable.helper.isDescendant = function (parent, child) { var node = child.parentNode; while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; }; /** * Generates a random hex string. Used as namespace for Handsontable instance events. * @return {String} - 16 character random string: "92b1bfc74ec4" */ Handsontable.helper.randomString = function () { return walkontableRandomString(); }; /** * Inherit without without calling parent constructor, and setting `Child.prototype.constructor` to `Child` instead of `Parent`. * Creates temporary dummy function to call it as constructor. * Described in ticket: https://github.com/warpech/jquery-handsontable/pull/516 * @param {Object} Child child class * @param {Object} Parent parent class * @return {Object} extended Child */ Handsontable.helper.inherit = function (Child, Parent) { Parent.prototype.constructor = Parent; Child.prototype = new Parent(); Child.prototype.constructor = Child; return Child; }; /** * Perform shallow extend of a target object with extension's own properties * @param {Object} target An object that will receive the new properties * @param {Object} extension An object containing additional properties to merge into the target */ Handsontable.helper.extend = function (target, extension) { for (var i in extension) { if (extension.hasOwnProperty(i)) { target[i] = extension[i]; } } }; Handsontable.helper.getPrototypeOf = function (obj) { var prototype; if(typeof obj.__proto__ == "object"){ prototype = obj.__proto__; } else { var oldConstructor, constructor = obj.constructor; if (typeof obj.constructor == "function") { oldConstructor = constructor; if (delete obj.constructor){ constructor = obj.constructor; // get real constructor obj.constructor = oldConstructor; // restore constructor } } prototype = constructor ? constructor.prototype : null; // needed for IE } return prototype; }; /** * Factory for columns constructors. * @param {Object} GridSettings * @param {Array} conflictList * @return {Object} ColumnSettings */ Handsontable.helper.columnFactory = function (GridSettings, conflictList) { function ColumnSettings () {} Handsontable.helper.inherit(ColumnSettings, GridSettings); // Clear conflict settings for (var i = 0, len = conflictList.length; i < len; i++) { ColumnSettings.prototype[conflictList[i]] = void 0; } return ColumnSettings; }; Handsontable.helper.translateRowsToColumns = function (input) { var i , ilen , j , jlen , output = [] , olen = 0; for (i = 0, ilen = input.length; i < ilen; i++) { for (j = 0, jlen = input[i].length; j < jlen; j++) { if (j == olen) { output.push([]); olen++; } output[j].push(input[i][j]) } } return output; }; Handsontable.helper.to2dArray = function (arr) { var i = 0 , ilen = arr.length; while (i < ilen) { arr[i] = [arr[i]]; i++; } }; Handsontable.helper.extendArray = function (arr, extension) { var i = 0 , ilen = extension.length; while (i < ilen) { arr.push(extension[i]); i++; } }; /** * Determines if the given DOM element is an input field. * Notice: By 'input' we mean input, textarea and select nodes * @param element - DOM element * @returns {boolean} */ Handsontable.helper.isInput = function (element) { var inputs = ['INPUT', 'SELECT', 'TEXTAREA']; return inputs.indexOf(element.nodeName) > -1; } /** * Determines if the given DOM element is an input field placed OUTSIDE of HOT. * Notice: By 'input' we mean input, textarea and select nodes * @param element - DOM element * @returns {boolean} */ Handsontable.helper.isOutsideInput = function (element) { return Handsontable.helper.isInput(element) && element.className.indexOf('handsontableInput') == -1; }; Handsontable.helper.keyCode = { MOUSE_LEFT: 1, MOUSE_RIGHT: 3, MOUSE_MIDDLE: 2, BACKSPACE: 8, COMMA: 188, DELETE: 46, END: 35, ENTER: 13, ESCAPE: 27, CONTROL_LEFT: 91, COMMAND_LEFT: 17, COMMAND_RIGHT: 93, ALT: 18, HOME: 36, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, SPACE: 32, SHIFT: 16, CAPS_LOCK: 20, TAB: 9, ARROW_RIGHT: 39, ARROW_LEFT: 37, ARROW_UP: 38, ARROW_DOWN: 40, F1: 112, F2: 113, F3: 114, F4: 115, F5: 116, F6: 117, F7: 118, F8: 119, F9: 120, F10: 121, F11: 122, F12: 123, A: 65, X: 88, C: 67, V: 86 }; /** * Determines whether given object is a plain Object. * Note: String and Array are not plain Objects * @param {*} obj * @returns {boolean} */ Handsontable.helper.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; /** * Determines whether given object is an Array. * Note: String is not an Array * @param {*} obj * @returns {boolean} */ Handsontable.helper.isArray = function(obj){ return Array.isArray ? Array.isArray(obj) : Object.prototype.toString.call(obj) == '[object Array]'; }; Handsontable.helper.pivot = function (arr) { var pivotedArr = []; if(!arr || arr.length == 0 || !arr[0] || arr[0].length == 0){ return pivotedArr; } var rowCount = arr.length; var colCount = arr[0].length; for(var i = 0; i < rowCount; i++){ for(var j = 0; j < colCount; j++){ if(!pivotedArr[j]){ pivotedArr[j] = []; } pivotedArr[j][i] = arr[i][j]; } } return pivotedArr; }; Handsontable.helper.proxy = function (fun, context) { return function () { return fun.apply(context, arguments); }; }; Handsontable.helper.cellMethodLookupFactory = function (methodName) { return function cellMethodLookup (row, col) { return (function getMethodFromProperties(properties) { if (!properties){ return; //method not found } else if (properties.hasOwnProperty(methodName) && properties[methodName]) { //check if it is own and is not empty return properties[methodName]; //method defined directly } else if (properties.hasOwnProperty('type') && properties.type) { //check if it is own and is not empty var type; if(typeof properties.type != 'string' ){ throw new Error('Cell type must be a string '); } type = translateTypeNameToObject(properties.type); return type[methodName]; //method defined in type. if does not exist (eg. validator), returns undefined } return getMethodFromProperties(Handsontable.helper.getPrototypeOf(properties)); })(typeof row == 'number' ? this.getCellMeta(row, col) : row); }; function translateTypeNameToObject(typeName) { var type = Handsontable.cellTypes[typeName]; if(typeof type == 'undefined'){ throw new Error('You declared cell type "' + typeName + '" as a string that is not mapped to a known object. Cell type must be an object or a string mapped to an object in Handsontable.cellTypes'); } return type; } }; Handsontable.SelectionPoint = function () { this._row = null; //private use intended this._col = null; }; Handsontable.SelectionPoint.prototype.exists = function () { return (this._row !== null); }; Handsontable.SelectionPoint.prototype.row = function (val) { if (val !== void 0) { this._row = val; } return this._row; }; Handsontable.SelectionPoint.prototype.col = function (val) { if (val !== void 0) { this._col = val; } return this._col; }; Handsontable.SelectionPoint.prototype.coords = function (coords) { if (coords !== void 0) { this._row = coords.row; this._col = coords.col; } return { row: this._row, col: this._col } }; Handsontable.SelectionPoint.prototype.arr = function (arr) { if (arr !== void 0) { this._row = arr[0]; this._col = arr[1]; } return [this._row, this._col] }; (function (Handsontable) { 'use strict'; /** * Utility class that gets and saves data from/to the data source using mapping of columns numbers to object property names * TODO refactor arguments of methods getRange, getText to be numbers (not objects) * TODO remove priv, GridSettings from object constructor * * @param instance * @param priv * @param GridSettings * @constructor */ Handsontable.DataMap = function (instance, priv, GridSettings) { this.instance = instance; this.priv = priv; this.GridSettings = GridSettings; this.dataSource = this.instance.getSettings().data; if (this.dataSource[0]) { this.duckSchema = this.recursiveDuckSchema(this.dataSource[0]); } else { this.duckSchema = {}; } this.createMap(); this.getVars = {}; //used by modifier this.setVars = {}; //used by modifier }; Handsontable.DataMap.prototype.DESTINATION_RENDERER = 1; Handsontable.DataMap.prototype.DESTINATION_CLIPBOARD_GENERATOR = 2; Handsontable.DataMap.prototype.recursiveDuckSchema = function (obj) { var schema; if ($.isPlainObject(obj)) { schema = {}; for (var i in obj) { if (obj.hasOwnProperty(i)) { if ($.isPlainObject(obj[i])) { schema[i] = this.recursiveDuckSchema(obj[i]); } else { schema[i] = null; } } } } else { schema = []; } return schema; }; Handsontable.DataMap.prototype.recursiveDuckColumns = function (schema, lastCol, parent) { var prop, i; if (typeof lastCol === 'undefined') { lastCol = 0; parent = ''; } if ($.isPlainObject(schema)) { for (i in schema) { if (schema.hasOwnProperty(i)) { if (schema[i] === null) { prop = parent + i; this.colToPropCache.push(prop); this.propToColCache[prop] = lastCol; lastCol++; } else { lastCol = this.recursiveDuckColumns(schema[i], lastCol, i + '.'); } } } } return lastCol; }; Handsontable.DataMap.prototype.createMap = function () { if (typeof this.getSchema() === "undefined") { throw new Error("trying to create `columns` definition but you didnt' provide `schema` nor `data`"); } var i, ilen, schema = this.getSchema(); this.colToPropCache = []; this.propToColCache = {}; var columns = this.instance.getSettings().columns; if (columns) { for (i = 0, ilen = columns.length; i < ilen; i++) { this.colToPropCache[i] = columns[i].data; this.propToColCache[columns[i].data] = i; } } else { this.recursiveDuckColumns(schema); } }; Handsontable.DataMap.prototype.colToProp = function (col) { col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col); if (this.colToPropCache && typeof this.colToPropCache[col] !== 'undefined') { return this.colToPropCache[col]; } else { return col; } }; Handsontable.DataMap.prototype.propToCol = function (prop) { var col; if (typeof this.propToColCache[prop] !== 'undefined') { col = this.propToColCache[prop]; } else { col = prop; } col = Handsontable.PluginHooks.execute(this.instance, 'modifyCol', col); return col; }; Handsontable.DataMap.prototype.getSchema = function () { var schema = this.instance.getSettings().dataSchema; if (schema) { if (typeof schema === 'function') { return schema(); } return schema; } return this.duckSchema; }; /** * Creates row at the bottom of the data array * @param {Number} [index] Optional. Index of the row before which the new row will be inserted */ Handsontable.DataMap.prototype.createRow = function (index, amount) { var row , colCount = this.instance.countCols() , numberOfCreatedRows = 0 , currentIndex; if (!amount) { amount = 1; } if (typeof index !== 'number' || index >= this.instance.countRows()) { index = this.instance.countRows(); } currentIndex = index; var maxRows = this.instance.getSettings().maxRows; while (numberOfCreatedRows < amount && this.instance.countRows() < maxRows) { if (this.instance.dataType === 'array') { row = []; for (var c = 0; c < colCount; c++) { row.push(null); } } else if (this.instance.dataType === 'function') { row = this.instance.getSettings().dataSchema(index); } else { row = $.extend(true, {}, this.getSchema()); } if (index === this.instance.countRows()) { this.dataSource.push(row); } else { this.dataSource.splice(index, 0, row); } numberOfCreatedRows++; currentIndex++; } this.instance.PluginHooks.run('afterCreateRow', index, numberOfCreatedRows); this.instance.forceFullRender = true; //used when data was changed return numberOfCreatedRows; }; /** * Creates col at the right of the data array * @param {Number} [index] Optional. Index of the column before which the new column will be inserted * * @param {Number} [amount] Optional. */ Handsontable.DataMap.prototype.createCol = function (index, amount) { if (this.instance.dataType === 'object' || this.instance.getSettings().columns) { throw new Error("Cannot create new column. When data source in an object, " + "you can only have as much columns as defined in first data row, data schema or in the 'columns' setting." + "If you want to be able to add new columns, you have to use array datasource."); } var rlen = this.instance.countRows() , data = this.dataSource , constructor , numberOfCreatedCols = 0 , currentIndex; if (!amount) { amount = 1; } currentIndex = index; var maxCols = this.instance.getSettings().maxCols; while (numberOfCreatedCols < amount && this.instance.countCols() < maxCols) { constructor = Handsontable.helper.columnFactory(this.GridSettings, this.priv.columnsSettingConflicts); if (typeof index !== 'number' || index >= this.instance.countCols()) { for (var r = 0; r < rlen; r++) { if (typeof data[r] === 'undefined') { data[r] = []; } data[r].push(null); } // Add new column constructor this.priv.columnSettings.push(constructor); } else { for (var r = 0; r < rlen; r++) { data[r].splice(currentIndex, 0, null); } // Add new column constructor at given index this.priv.columnSettings.splice(currentIndex, 0, constructor); } numberOfCreatedCols++; currentIndex++; } this.instance.PluginHooks.run('afterCreateCol', index, numberOfCreatedCols); this.instance.forceFullRender = true; //used when data was changed return numberOfCreatedCols; }; /** * Removes row from the data array * @param {Number} [index] Optional. Index of the row to be removed. If not provided, the last row will be removed * @param {Number} [amount] Optional. Amount of the rows to be removed. If not provided, one row will be removed */ Handsontable.DataMap.prototype.removeRow = function (index, amount) { if (!amount) { amount = 1; } if (typeof index !== 'number') { index = -amount; } index = (this.instance.countRows() + index) % this.instance.countRows(); // We have to map the physical row ids to logical and than perform removing with (possibly) new row id var logicRows = this.physicalRowsToLogical(index, amount); var actionWasNotCancelled = this.instance.PluginHooks.execute('beforeRemoveRow', index, amount); if (actionWasNotCancelled === false) { return; } var data = this.dataSource; var newData = data.filter(function (row, index) { return logicRows.indexOf(index) == -1; }); data.length = 0; Array.prototype.push.apply(data, newData); this.instance.PluginHooks.run('afterRemoveRow', index, amount); this.instance.forceFullRender = true; //used when data was changed }; /** * Removes column from the data array * @param {Number} [index] Optional. Index of the column to be removed. If not provided, the last column will be removed * @param {Number} [amount] Optional. Amount of the columns to be removed. If not provided, one column will be removed */ Handsontable.DataMap.prototype.removeCol = function (index, amount) { if (this.instance.dataType === 'object' || this.instance.getSettings().columns) { throw new Error("cannot remove column with object data source or columns option specified"); } if (!amount) { amount = 1; } if (typeof index !== 'number') { index = -amount; } index = (this.instance.countCols() + index) % this.instance.countCols(); var actionWasNotCancelled = this.instance.PluginHooks.execute('beforeRemoveCol', index, amount); if (actionWasNotCancelled === false) { return; } var data = this.dataSource; for (var r = 0, rlen = this.instance.countRows(); r < rlen; r++) { data[r].splice(index, amount); } this.priv.columnSettings.splice(index, amount); this.instance.PluginHooks.run('afterRemoveCol', index, amount); this.instance.forceFullRender = true; //used when data was changed }; /** * Add / removes data from the column * @param {Number} col Index of column in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ Handsontable.DataMap.prototype.spliceCol = function (col, index, amount/*, elements...*/) { var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : []; var colData = this.instance.getDataAtCol(col); var removed = colData.slice(index, index + amount); var after = colData.slice(index + amount); Handsontable.helper.extendArray(elements, after); var i = 0; while (i < amount) { elements.push(null); //add null in place of removed elements i++; } Handsontable.helper.to2dArray(elements); this.instance.populateFromArray(index, col, elements, null, null, 'spliceCol'); return removed; }; /** * Add / removes data from the row * @param {Number} row Index of row in which do you want to do splice. * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end * @param {Number} amount An integer indicating the number of old array elements to remove. If amount is 0, no elements are removed * param {...*} elements Optional. The elements to add to the array. If you don't specify any elements, spliceCol simply removes elements from the array */ Handsontable.DataMap.prototype.spliceRow = function (row, index, amount/*, elements...*/) { var elements = 4 <= arguments.length ? [].slice.call(arguments, 3) : []; var rowData = this.instance.getDataAtRow(row); var removed = rowData.slice(index, index + amount); var after = rowData.slice(index + amount); Handsontable.helper.extendArray(elements, after); var i = 0; while (i < amount) { elements.push(null); //add null in place of removed elements i++; } this.instance.populateFromArray(row, index, [elements], null, null, 'spliceRow'); return removed; }; /** * Returns single value from the data array * @param {Number} row * @param {Number} prop */ Handsontable.DataMap.prototype.get = function (row, prop) { this.getVars.row = row; this.getVars.prop = prop; this.instance.PluginHooks.run('beforeGet', this.getVars); if (typeof this.getVars.prop === 'string' && this.getVars.prop.indexOf('.') > -1) { var sliced = this.getVars.prop.split("."); var out = this.dataSource[this.getVars.row]; if (!out) { return null; } for (var i = 0, ilen = sliced.length; i < ilen; i++) { out = out[sliced[i]]; if (typeof out === 'undefined') { return null; } } return out; } else if (typeof this.getVars.prop === 'function') { /** * allows for interacting with complex structures, for example * d3/jQuery getter/setter properties: * * {columns: [{ * data: function(row, value){ * if(arguments.length === 1){ * return row.property(); * } * row.property(value); * } * }]} */ return this.getVars.prop(this.dataSource.slice( this.getVars.row, this.getVars.row + 1 )[0]); } else { return this.dataSource[this.getVars.row] ? this.dataSource[this.getVars.row][this.getVars.prop] : null; } }; var copyableLookup = Handsontable.helper.cellMethodLookupFactory('copyable'); /** * Returns single value from the data array (intended for clipboard copy to an external application) * @param {Number} row * @param {Number} prop * @return {String} */ Handsontable.DataMap.prototype.getCopyable = function (row, prop) { if (copyableLookup.call(this.instance, row, this.propToCol(prop))) { return this.get(row, prop); } return ''; }; /** * Saves single value to the data array * @param {Number} row * @param {Number} prop * @param {String} value * @param {String} [source] Optional. Source of hook runner. */ Handsontable.DataMap.prototype.set = function (row, prop, value, source) { this.setVars.row = row; this.setVars.prop = prop; this.setVars.value = value; this.instance.PluginHooks.run('beforeSet', this.setVars, source || "datamapGet"); if (typeof this.setVars.prop === 'string' && this.setVars.prop.indexOf('.') > -1) { var sliced = this.setVars.prop.split("."); var out = this.dataSource[this.setVars.row]; for (var i = 0, ilen = sliced.length - 1; i < ilen; i++) { out = out[sliced[i]]; } out[sliced[i]] = this.setVars.value; } else if (typeof this.setVars.prop === 'function') { /* see the `function` handler in `get` */ this.setVars.prop(this.dataSource.slice( this.setVars.row, this.setVars.row + 1 )[0], this.setVars.value); } else { this.dataSource[this.setVars.row][this.setVars.prop] = this.setVars.value; } }; /** * This ridiculous piece of code maps rows Id that are present in table data to those displayed for user. * The trick is, the physical row id (stored in settings.data) is not necessary the same * as the logical (displayed) row id (e.g. when sorting is applied). */ Handsontable.DataMap.prototype.physicalRowsToLogical = function (index, amount) { var totalRows = this.instance.countRows(); var physicRow = (totalRows + index) % totalRows; var logicRows = []; var rowsToRemove = amount; while (physicRow < totalRows && rowsToRemove) { this.get(physicRow, 0); //this performs an actual mapping and saves the result to getVars logicRows.push(this.getVars.row); rowsToRemove--; physicRow++; } return logicRows; }; /** * Clears the data array */ Handsontable.DataMap.prototype.clear = function () { for (var r = 0; r < this.instance.countRows(); r++) { for (var c = 0; c < this.instance.countCols(); c++) { this.set(r, this.colToProp(c), ''); } } }; /** * Returns the data array * @return {Array} */ Handsontable.DataMap.prototype.getAll = function () { return this.dataSource; }; /** * Returns data range as array * @param {Object} start Start selection position * @param {Object} end End selection position * @param {Number} destination Destination of datamap.get * @return {Array} */ Handsontable.DataMap.prototype.getRange = function (start, end, destination) { var r, rlen, c, clen, output = [], row; var getFn = destination === this.DESTINATION_CLIPBOARD_GENERATOR ? this.getCopyable : this.get; rlen = Math.max(start.row, end.row); clen = Math.max(start.col, end.col); for (r = Math.min(start.row, end.row); r <= rlen; r++) { row = []; for (c = Math.min(start.col, end.col); c <= clen; c++) { row.push(getFn.call(this, r, this.colToProp(c))); } output.push(row); } return output; }; /** * Return data as text (tab separated columns) * @param {Object} start (Optional) Start selection position * @param {Object} end (Optional) End selection position * @return {String} */ Handsontable.DataMap.prototype.getText = function (start, end) { return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_RENDERER)); }; /** * Return data as copyable text (tab separated columns intended for clipboard copy to an external application) * @param {Object} start (Optional) Start selection position * @param {Object} end (Optional) End selection position * @return {String} */ Handsontable.DataMap.prototype.getCopyableText = function (start, end) { return SheetClip.stringify(this.getRange(start, end, this.DESTINATION_CLIPBOARD_GENERATOR)); }; })(Handsontable); (function (Handsontable) { 'use strict'; /* Adds appropriate CSS class to table cell, based on cellProperties */ Handsontable.renderers.cellDecorator = function (instance, TD, row, col, prop, value, cellProperties) { if (cellProperties.readOnly) { instance.view.wt.wtDom.addClass(TD, cellProperties.readOnlyCellClassName); } if (cellProperties.valid === false && cellProperties.invalidCellClassName) { instance.view.wt.wtDom.addClass(TD, cellProperties.invalidCellClassName); } if (!value && cellProperties.placeholder) { instance.view.wt.wtDom.addClass(TD, cellProperties.placeholderCellClassName); } } })(Handsontable); /** * Default text renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var TextRenderer = function (instance, TD, row, col, prop, value, cellProperties) { Handsontable.renderers.cellDecorator.apply(this, arguments); if (!value && cellProperties.placeholder) { value = cellProperties.placeholder; } var escaped = Handsontable.helper.stringify(value); if (cellProperties.rendererTemplate) { instance.view.wt.wtDom.empty(TD); var TEMPLATE = document.createElement('TEMPLATE'); TEMPLATE.setAttribute('bind', '{{}}'); TEMPLATE.innerHTML = cellProperties.rendererTemplate; HTMLTemplateElement.decorate(TEMPLATE); TEMPLATE.model = instance.getDataAtRow(row); TD.appendChild(TEMPLATE); } else { instance.view.wt.wtDom.fastInnerText(TD, escaped); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } }; //Handsontable.TextRenderer = TextRenderer; //Left for backward compatibility Handsontable.renderers.TextRenderer = TextRenderer; Handsontable.renderers.registerRenderer('text', TextRenderer); })(Handsontable); (function (Handsontable) { var clonableWRAPPER = document.createElement('DIV'); clonableWRAPPER.className = 'htAutocompleteWrapper'; var clonableARROW = document.createElement('DIV'); clonableARROW.className = 'htAutocompleteArrow'; clonableARROW.appendChild(document.createTextNode('\u25BC')); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips var wrapTdContentWithWrapper = function(TD, WRAPPER){ WRAPPER.innerHTML = TD.innerHTML; Handsontable.Dom.empty(TD); TD.appendChild(WRAPPER); }; /** * Autocomplete renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ var AutocompleteRenderer = function (instance, TD, row, col, prop, value, cellProperties) { var WRAPPER = clonableWRAPPER.cloneNode(true); //this is faster than createElement var ARROW = clonableARROW.cloneNode(true); //this is faster than createElement Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties); TD.appendChild(ARROW); Handsontable.Dom.addClass(TD, 'htAutocomplete'); if (!TD.firstChild) { //http://jsperf.com/empty-node-if-needed //otherwise empty fields appear borderless in demo/renderers.html (IE) TD.appendChild(document.createTextNode('\u00A0')); //\u00A0 equals &nbsp; for a text node //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } if (!instance.acArrowListener) { //not very elegant but easy and fast instance.acArrowListener = function () { instance.view.wt.getSetting('onCellDblClick'); }; instance.rootElement.on('mousedown', '.htAutocompleteArrow', instance.acArrowListener); //this way we don't bind event listener to each arrow. We rely on propagation instead } }; Handsontable.AutocompleteRenderer = AutocompleteRenderer; Handsontable.renderers.AutocompleteRenderer = AutocompleteRenderer; Handsontable.renderers.registerRenderer('autocomplete', AutocompleteRenderer); })(Handsontable); /** * Checkbox renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var clonableINPUT = document.createElement('INPUT'); clonableINPUT.className = 'htCheckboxRendererInput'; clonableINPUT.type = 'checkbox'; clonableINPUT.setAttribute('autocomplete', 'off'); var CheckboxRenderer = function (instance, TD, row, col, prop, value, cellProperties) { if (typeof cellProperties.checkedTemplate === "undefined") { cellProperties.checkedTemplate = true; } if (typeof cellProperties.uncheckedTemplate === "undefined") { cellProperties.uncheckedTemplate = false; } instance.view.wt.wtDom.empty(TD); //TODO identify under what circumstances this line can be removed var INPUT = clonableINPUT.cloneNode(false); //this is faster than createElement if (value === cellProperties.checkedTemplate || value === Handsontable.helper.stringify(cellProperties.checkedTemplate)) { INPUT.checked = true; TD.appendChild(INPUT); } else if (value === cellProperties.uncheckedTemplate || value === Handsontable.helper.stringify(cellProperties.uncheckedTemplate)) { TD.appendChild(INPUT); } else if (value === null) { //default value INPUT.className += ' noValue'; TD.appendChild(INPUT); } else { instance.view.wt.wtDom.fastInnerText(TD, '#bad value#'); //this is faster than innerHTML. See: https://github.com/warpech/jquery-handsontable/wiki/JavaScript-&-DOM-performance-tips } var $input = $(INPUT); if (cellProperties.readOnly) { $input.on('click', function (event) { event.preventDefault(); }); } else { $input.on('mousedown', function (event) { event.stopPropagation(); //otherwise can confuse cell mousedown handler }); $input.on('mouseup', function (event) { event.stopPropagation(); //otherwise can confuse cell dblclick handler }); $input.on('change', function(){ if (this.checked) { instance.setDataAtRowProp(row, prop, cellProperties.checkedTemplate); } else { instance.setDataAtRowProp(row, prop, cellProperties.uncheckedTemplate); } }); } if(!instance.CheckboxRenderer || !instance.CheckboxRenderer.beforeKeyDownHookBound){ instance.CheckboxRenderer = { beforeKeyDownHookBound : true }; instance.addHook('beforeKeyDown', function(event){ if(event.keyCode == Handsontable.helper.keyCode.SPACE){ var selection = instance.getSelected(); var cell, checkbox, cellProperties; var selStart = { row: Math.min(selection[0], selection[2]), col: Math.min(selection[1], selection[3]) }; var selEnd = { row: Math.max(selection[0], selection[2]), col: Math.max(selection[1], selection[3]) }; for(var row = selStart.row; row <= selEnd.row; row++ ){ for(var col = selEnd.col; col <= selEnd.col; col++){ cell = instance.getCell(row, col); cellProperties = instance.getCellMeta(row, col); checkbox = cell.querySelectorAll('input[type=checkbox]'); if(checkbox.length > 0 && !cellProperties.readOnly){ if(!event.isImmediatePropagationStopped()){ event.stopImmediatePropagation(); event.preventDefault(); } for(var i = 0, len = checkbox.length; i < len; i++){ checkbox[i].checked = !checkbox[i].checked; $(checkbox[i]).trigger('change'); } } } } } }); } }; Handsontable.CheckboxRenderer = CheckboxRenderer; Handsontable.renderers.CheckboxRenderer = CheckboxRenderer; Handsontable.renderers.registerRenderer('checkbox', CheckboxRenderer); })(Handsontable); /** * Numeric cell renderer * @param {Object} instance Handsontable instance * @param {Element} TD Table cell where to render * @param {Number} row * @param {Number} col * @param {String|Number} prop Row object property name * @param value Value to render (remember to escape unsafe HTML before inserting to DOM!) * @param {Object} cellProperties Cell properites (shared by cell renderer and editor) */ (function (Handsontable) { 'use strict'; var NumericRenderer = function (instance, TD, row, col, prop, value, cellProperties) { if (Handsontable.helper.isNumeric(value)) { if (typeof cellProperties.language !== 'undefined') { numeral.language(cellProperties.language) } value = numeral(value).format(cellProperties.format || '0'); //docs: http://numeraljs.com/ instance.view.wt.wtDom.addClass(TD, 'htNumeric'); } Handsontable.renderers.TextRenderer(instance, TD, row, col, prop, value, cellProperties); }; Handsontable.NumericRenderer = NumericRenderer; //Left for backward compatibility with versions prior 0.10.0 Handsontable.renderers.NumericRenderer = NumericRenderer; Handsontable.renderers.registerRenderer('numeric', NumericRenderer); })(Handsontable); (function(Handosntable){ 'use strict'; var PasswordRenderer = function (instance, TD, row, col, prop, value, cellProperties) { Handsontable.renderers.TextRenderer.apply(this, arguments); value = TD.innerHTML; var hash; var hashLength = cellProperties.hashLength || value.length; var hashSymbol = cellProperties.hashSymbol || '*'; for( hash = ''; hash.split(hashSymbol).length - 1 < hashLength; hash += hashSymbol); instance.view.wt.wtDom.fastInnerHTML(TD, hash); }; Handosntable.PasswordRenderer = PasswordRenderer; Handosntable.renderers.PasswordRenderer = PasswordRenderer; Handosntable.renderers.registerRenderer('password', PasswordRenderer); })(Handsontable); (function (Handsontable) { function HtmlRenderer(instance, TD, row, col, prop, value, cellProperties){ Handsontable.renderers.cellDecorator.apply(this, arguments); Handsontable.Dom.fastInnerHTML(TD, value); } Handsontable.renderers.registerRenderer('html', HtmlRenderer); Handsontable.renderers.HtmlRenderer = HtmlRenderer; })(Handsontable); (function (Handsontable) { 'use strict'; Handsontable.EditorState = { VIRGIN: 'STATE_VIRGIN', //before editing EDITING: 'STATE_EDITING', WAITING: 'STATE_WAITING', //waiting for async validation FINISHED: 'STATE_FINISHED' }; function BaseEditor(instance) { this.instance = instance; this.state = Handsontable.EditorState.VIRGIN; this._opened = false; this._closeCallback = null; this.init(); } BaseEditor.prototype._fireCallbacks = function(result) { if(this._closeCallback){ this._closeCallback(result); this._closeCallback = null; } } BaseEditor.prototype.init = function(){}; BaseEditor.prototype.getValue = function(){ throw Error('Editor getValue() method unimplemented'); }; BaseEditor.prototype.setValue = function(newValue){ throw Error('Editor setValue() method unimplemented'); }; BaseEditor.prototype.open = function(){ throw Error('Editor open() method unimplemented'); }; BaseEditor.prototype.close = function(){ throw Error('Editor close() method unimplemented'); }; BaseEditor.prototype.prepare = function(row, col, prop, td, originalValue, cellProperties){ this.TD = td; this.row = row; this.col = col; this.prop = prop; this.originalValue = originalValue; this.cellProperties = cellProperties; this.state = Handsontable.EditorState.VIRGIN; }; BaseEditor.prototype.extend = function(){ var baseClass = this.constructor; function Editor(){ baseClass.apply(this, arguments); } function inherit(Child, Parent){ function Bridge() { } Bridge.prototype = Parent.prototype; Child.prototype = new Bridge(); Child.prototype.constructor = Child; return Child; } return inherit(Editor, baseClass); }; BaseEditor.prototype.saveValue = function (val, ctrlDown) { if (ctrlDown) { //if ctrl+enter and multiple cells selected, behave like Excel (finish editing and apply to all cells) var sel = this.instance.getSelected(); this.instance.populateFromArray(sel[0], sel[1], val, sel[2], sel[3], 'edit'); } else { this.instance.populateFromArray(this.row, this.col, val, null, null, 'edit'); } }; BaseEditor.prototype.beginEditing = function(initialValue){ if (this.state != Handsontable.EditorState.VIRGIN) { return; } if (this.cellProperties.readOnly) { return; } this.instance.view.scrollViewport({row: this.row, col: this.col}); this.instance.view.render(); this.state = Handsontable.EditorState.EDITING; initialValue = typeof initialValue == 'string' ? initialValue : this.originalValue; this.setValue(Handsontable.helper.stringify(initialValue)); this.open(); this._opened = true; this.focus(); this.instance.view.render(); //only rerender the selections (FillHandle should disappear when beginediting is triggered) }; BaseEditor.prototype.finishEditing = function (restoreOriginalValue, ctrlDown, callback) { if (callback) { var previousCloseCallback = this._closeCallback; this._closeCallback = function (result) { if(previousCloseCallback){ previousCloseCallback(result); } callback(result); }; } if (this.isWaiting()) { return; } if (this.state == Handsontable.EditorState.VIRGIN) { var that = this; setTimeout(function () { that._fireCallbacks(true); }); return; } if (this.state == Handsontable.EditorState.EDITING) { if (restoreOriginalValue) { this.cancelChanges(); return; } var val = [ [String.prototype.trim.call(this.getValue())] //String.prototype.trim is defined in Walkontable polyfill.js ]; this.state = Handsontable.EditorState.WAITING; this.saveValue(val, ctrlDown); if(this.instance.getCellValidator(this.cellProperties)){ var that = this; this.instance.addHookOnce('afterValidate', function (result) { that.state = Handsontable.EditorState.FINISHED; that.discardEditor(result); }); } else { this.state = Handsontable.EditorState.FINISHED; this.discardEditor(true); } } }; BaseEditor.prototype.cancelChanges = function () { this.state = Handsontable.EditorState.FINISHED; this.discardEditor(); }; BaseEditor.prototype.discardEditor = function (result) { if (this.state !== Handsontable.EditorState.FINISHED) { return; } if (result === false && this.cellProperties.allowInvalid !== true) { //validator was defined and failed this.instance.selectCell(this.row, this.col); this.focus(); this.state = Handsontable.EditorState.EDITING; this._fireCallbacks(false); } else { this.close(); this._opened = false; this.state = Handsontable.EditorState.VIRGIN; this._fireCallbacks(true); } }; BaseEditor.prototype.isOpened = function(){ return this._opened; }; BaseEditor.prototype.isWaiting = function () { return this.state === Handsontable.EditorState.WAITING; }; Handsontable.editors.BaseEditor = BaseEditor; })(Handsontable); (function(Handsontable){ var TextEditor = Handsontable.editors.BaseEditor.prototype.extend(); TextEditor.prototype.init = function(){ this.createElements(); this.bindEvents(); }; TextEditor.prototype.getValue = function(){ return this.TEXTAREA.value }; TextEditor.prototype.setValue = function(newValue){ this.TEXTAREA.value = newValue; }; var onBeforeKeyDown = function onBeforeKeyDown(event){ var instance = this; var that = instance.getActiveEditor(); var keyCodes = Handsontable.helper.keyCode; var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) //Process only events that have been fired in the editor if (event.target !== that.TEXTAREA || event.isImmediatePropagationStopped()){ return; } if (event.keyCode === 17 || event.keyCode === 224 || event.keyCode === 91 || event.keyCode === 93) { //when CTRL or its equivalent is pressed and cell is edited, don't prepare selectable text in textarea event.stopImmediatePropagation(); return; } switch (event.keyCode) { case keyCodes.ARROW_RIGHT: if (that.wtDom.getCaretPosition(that.TEXTAREA) !== that.TEXTAREA.value.length) { event.stopImmediatePropagation(); } break; case keyCodes.ARROW_LEFT: /* arrow left */ if (that.wtDom.getCaretPosition(that.TEXTAREA) !== 0) { event.stopImmediatePropagation(); } break; case keyCodes.ENTER: var selected = that.instance.getSelected(); var isMultipleSelection = !(selected[0] === selected[2] && selected[1] === selected[3]); if ((ctrlDown && !isMultipleSelection) || event.altKey) { //if ctrl+enter or alt+enter, add new line if(that.isOpened()){ that.setValue(that.getValue() + '\n'); that.focus(); } else { that.beginEditing(that.originalValue + '\n') } event.stopImmediatePropagation(); } event.preventDefault(); //don't add newline to field break; case keyCodes.A: case keyCodes.X: case keyCodes.C: case keyCodes.V: if(ctrlDown){ event.stopImmediatePropagation(); //CTRL+A, CTRL+C, CTRL+V, CTRL+X should only work locally when cell is edited (not in table context) break; } case keyCodes.BACKSPACE: case keyCodes.DELETE: case keyCodes.HOME: case keyCodes.END: event.stopImmediatePropagation(); //backspace, delete, home, end should only work locally when cell is edited (not in table context) break; } }; TextEditor.prototype.open = function(){ this.refreshDimensions(); //need it instantly, to prevent https://github.com/warpech/jquery-handsontable/issues/348 this.instance.addHook('beforeKeyDown', onBeforeKeyDown); }; TextEditor.prototype.close = function(){ this.textareaParentStyle.display = 'none'; if (document.activeElement === this.TEXTAREA) { this.instance.listen(); //don't refocus the table if user focused some cell outside of HT on purpose } this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; TextEditor.prototype.focus = function(){ this.TEXTAREA.focus(); this.wtDom.setCaretPosition(this.TEXTAREA, this.TEXTAREA.value.length); }; TextEditor.prototype.createElements = function () { this.$body = $(document.body); this.wtDom = new WalkontableDom(); this.TEXTAREA = document.createElement('TEXTAREA'); this.$textarea = $(this.TEXTAREA); this.wtDom.addClass(this.TEXTAREA, 'handsontableInput'); this.textareaStyle = this.TEXTAREA.style; this.textareaStyle.width = 0; this.textareaStyle.height = 0; this.TEXTAREA_PARENT = document.createElement('DIV'); this.wtDom.addClass(this.TEXTAREA_PARENT, 'handsontableInputHolder'); this.textareaParentStyle = this.TEXTAREA_PARENT.style; this.textareaParentStyle.top = 0; this.textareaParentStyle.left = 0; this.textareaParentStyle.display = 'none'; this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); this.instance.rootElement[0].appendChild(this.TEXTAREA_PARENT); var that = this; Handsontable.PluginHooks.add('afterRender', function () { that.instance.registerTimeout('refresh_editor_dimensions', function () { that.refreshDimensions(); }, 0); }); }; TextEditor.prototype.refreshDimensions = function () { if (this.state !== Handsontable.EditorState.EDITING) { return; } ///start prepare textarea position this.TD = this.instance.getCell(this.row, this.col); if (!this.TD) { //TD is outside of the viewport. Otherwise throws exception when scrolling the table while a cell is edited return; } var $td = $(this.TD); //because old td may have been scrolled out with scrollViewport var currentOffset = this.wtDom.offset(this.TD); var containerOffset = this.wtDom.offset(this.instance.rootElement[0]); var scrollTop = this.instance.rootElement.scrollTop(); var scrollLeft = this.instance.rootElement.scrollLeft(); var editTop = currentOffset.top - containerOffset.top + scrollTop - 1; var editLeft = currentOffset.left - containerOffset.left + scrollLeft - 1; var settings = this.instance.getSettings(); var rowHeadersCount = settings.rowHeaders === false ? 0 : 1; var colHeadersCount = settings.colHeaders === false ? 0 : 1; if (editTop < 0) { editTop = 0; } if (editLeft < 0) { editLeft = 0; } if (rowHeadersCount > 0 && parseInt($td.css('border-top-width'), 10) > 0) { editTop += 1; } if (colHeadersCount > 0 && parseInt($td.css('border-left-width'), 10) > 0) { editLeft += 1; } this.textareaParentStyle.top = editTop + 'px'; this.textareaParentStyle.left = editLeft + 'px'; ///end prepare textarea position var width = $td.width() , maxWidth = this.instance.view.maximumVisibleElementWidth(editLeft) - 10 //10 is TEXTAREAs border and padding , height = $td.outerHeight() - 4 , maxHeight = this.instance.view.maximumVisibleElementHeight(editTop) - 5; //10 is TEXTAREAs border and padding if (parseInt($td.css('border-top-width'), 10) > 0) { height -= 1; } if (parseInt($td.css('border-left-width'), 10) > 0) { if (rowHeadersCount > 0) { width -= 1; } } //in future may change to pure JS http://stackoverflow.com/questions/454202/creating-a-textarea-with-auto-resize this.$textarea.autoResize({ minHeight: Math.min(height, maxHeight), maxHeight: maxHeight, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar) minWidth: Math.min(width, maxWidth), maxWidth: maxWidth, //TEXTAREA should never be wider than visible part of the viewport (should not cover the scrollbar) animate: false, extraSpace: 0 }); this.textareaParentStyle.display = 'block'; }; TextEditor.prototype.bindEvents = function () { this.$textarea.on('cut.editor', function (event) { event.stopPropagation(); }); this.$textarea.on('paste.editor', function (event) { event.stopPropagation(); }); }; Handsontable.editors.TextEditor = TextEditor; Handsontable.editors.registerEditor('text', Handsontable.editors.TextEditor); })(Handsontable); (function(Handsontable){ //Blank editor, because all the work is done by renderer var CheckboxEditor = Handsontable.editors.BaseEditor.prototype.extend(); CheckboxEditor.prototype.beginEditing = function () { this.saveValue([ [!this.originalValue] ]); }; CheckboxEditor.prototype.finishEditing = function () {}; CheckboxEditor.prototype.init = function () {}; CheckboxEditor.prototype.open = function () {}; CheckboxEditor.prototype.close = function () {}; CheckboxEditor.prototype.getValue = function () {}; CheckboxEditor.prototype.setValue = function () {}; CheckboxEditor.prototype.focus = function () {}; Handsontable.editors.CheckboxEditor = CheckboxEditor; Handsontable.editors.registerEditor('checkbox', CheckboxEditor); })(Handsontable); (function (Handsontable) { var DateEditor = Handsontable.editors.TextEditor.prototype.extend(); DateEditor.prototype.init = function () { if (!$.datepicker) { throw new Error("jQuery UI Datepicker dependency not found. Did you forget to include jquery-ui.custom.js or its substitute?"); } Handsontable.editors.TextEditor.prototype.init.apply(this, arguments); this.isCellEdited = false; var that = this; this.instance.addHook('afterDestroy', function () { that.destroyElements(); }) }; DateEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); this.datePicker = document.createElement('DIV'); this.instance.view.wt.wtDom.addClass(this.datePicker, 'htDatepickerHolder'); this.datePickerStyle = this.datePicker.style; this.datePickerStyle.position = 'absolute'; this.datePickerStyle.top = 0; this.datePickerStyle.left = 0; this.datePickerStyle.zIndex = 99; document.body.appendChild(this.datePicker); this.$datePicker = $(this.datePicker); var that = this; var defaultOptions = { dateFormat: "yy-mm-dd", showButtonPanel: true, changeMonth: true, changeYear: true, altField: this.$textarea, onSelect: function () { that.finishEditing(false); } }; this.$datePicker.datepicker(defaultOptions); /** * Prevent recognizing clicking on jQuery Datepicker as clicking outside of table */ this.$datePicker.on('mousedown', function (event) { event.stopPropagation(); }); this.hideDatepicker(); }; DateEditor.prototype.destroyElements = function () { this.$datePicker.datepicker('destroy'); this.$datePicker.remove(); }; DateEditor.prototype.beginEditing = function (row, col, prop, useOriginalValue, suffix) { Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments); this.showDatepicker(); }; DateEditor.prototype.finishEditing = function (isCancelled, ctrlDown) { this.hideDatepicker(); Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments); }; DateEditor.prototype.showDatepicker = function () { var $td = $(this.TD); var offset = $td.offset(); this.datePickerStyle.top = (offset.top + $td.height()) + 'px'; this.datePickerStyle.left = offset.left + 'px'; var dateOptions = { defaultDate: this.originalValue || void 0 }; $.extend(dateOptions, this.cellProperties); this.$datePicker.datepicker("option", dateOptions); if (this.originalValue) { this.$datePicker.datepicker("setDate", this.originalValue); } this.datePickerStyle.display = 'block'; }; DateEditor.prototype.hideDatepicker = function () { this.datePickerStyle.display = 'none'; }; Handsontable.editors.DateEditor = DateEditor; Handsontable.editors.registerEditor('date', DateEditor); })(Handsontable); /** * This is inception. Using Handsontable as Handsontable editor */ (function (Handsontable) { "use strict"; var HandsontableEditor = Handsontable.editors.TextEditor.prototype.extend(); HandsontableEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); var DIV = document.createElement('DIV'); DIV.className = 'handsontableEditor'; this.TEXTAREA_PARENT.appendChild(DIV); this.$htContainer = $(DIV); this.$htContainer.handsontable(); }; HandsontableEditor.prototype.prepare = function (td, row, col, prop, value, cellProperties) { Handsontable.editors.TextEditor.prototype.prepare.apply(this, arguments); var parent = this; var options = { startRows: 0, startCols: 0, minRows: 0, minCols: 0, className: 'listbox', copyPaste: false, cells: function () { return { readOnly: true } }, fillHandle: false, afterOnCellMouseDown: function () { var value = this.getValue(); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value parent.setValue(value); } parent.instance.destroyEditor(); }, beforeOnKeyDown: function (event) { var instance = this; switch (event.keyCode) { case Handsontable.helper.keyCode.ESCAPE: parent.instance.destroyEditor(true); event.stopImmediatePropagation(); event.preventDefault(); break; case Handsontable.helper.keyCode.ENTER: //enter var sel = instance.getSelected(); var value = this.getDataAtCell(sel[0], sel[1]); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value parent.setValue(value); } parent.instance.destroyEditor(); break; case Handsontable.helper.keyCode.ARROW_UP: if (instance.getSelected() && instance.getSelected()[0] == 0 && !parent.cellProperties.strict){ instance.deselectCell(); parent.instance.listen(); parent.focus(); event.preventDefault(); event.stopImmediatePropagation(); } break; } } }; if (this.cellProperties.handsontable) { options = $.extend(options, cellProperties.handsontable); } this.$htContainer.handsontable('destroy'); this.$htContainer.handsontable(options); }; var onBeforeKeyDown = function (event) { if (event.isImmediatePropagationStopped()) { return; } var editor = this.getActiveEditor(); var innerHOT = editor.$htContainer.handsontable('getInstance'); if (event.keyCode == Handsontable.helper.keyCode.ARROW_DOWN) { if (!innerHOT.getSelected()){ innerHOT.selectCell(0, 0); } else { var selectedRow = innerHOT.getSelected()[0]; var rowToSelect = selectedRow < innerHOT.countRows() - 1 ? selectedRow + 1 : selectedRow; innerHOT.selectCell(rowToSelect, 0); } event.preventDefault(); event.stopImmediatePropagation(); } }; HandsontableEditor.prototype.open = function () { this.instance.addHook('beforeKeyDown', onBeforeKeyDown); Handsontable.editors.TextEditor.prototype.open.apply(this, arguments); this.$htContainer.handsontable('render'); if (this.cellProperties.strict) { this.$htContainer.handsontable('selectCell', 0, 0); this.$textarea[0].style.visibility = 'hidden'; } else { this.$htContainer.handsontable('deselectCell'); this.$textarea[0].style.visibility = 'visible'; } this.wtDom.setCaretPosition(this.$textarea[0], 0, this.$textarea[0].value.length); }; HandsontableEditor.prototype.close = function () { this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); this.instance.listen(); Handsontable.editors.TextEditor.prototype.close.apply(this, arguments); }; HandsontableEditor.prototype.focus = function () { this.instance.listen(); Handsontable.editors.TextEditor.prototype.focus.apply(this, arguments); }; HandsontableEditor.prototype.beginEditing = function (initialValue) { var onBeginEditing = this.instance.getSettings().onBeginEditing; if (onBeginEditing && onBeginEditing() === false) { return; } Handsontable.editors.TextEditor.prototype.beginEditing.apply(this, arguments); }; HandsontableEditor.prototype.finishEditing = function (isCancelled, ctrlDown) { if (this.$htContainer.handsontable('isListening')) { //if focus is still in the HOT editor this.instance.listen(); //return the focus to the parent HOT instance } if (this.$htContainer.handsontable('getSelected')) { var value = this.$htContainer.handsontable('getInstance').getValue(); if (value !== void 0) { //if the value is undefined then it means we don't want to set the value this.setValue(value); } } return Handsontable.editors.TextEditor.prototype.finishEditing.apply(this, arguments); }; Handsontable.editors.HandsontableEditor = HandsontableEditor; Handsontable.editors.registerEditor('handsontable', HandsontableEditor); })(Handsontable); (function (Handsontable) { var AutocompleteEditor = Handsontable.editors.HandsontableEditor.prototype.extend(); AutocompleteEditor.prototype.init = function () { Handsontable.editors.HandsontableEditor.prototype.init.apply(this, arguments); this.query = null; }; AutocompleteEditor.prototype.createElements = function(){ Handsontable.editors.HandsontableEditor.prototype.createElements.apply(this, arguments); this.$htContainer.addClass('autocompleteEditor'); }; AutocompleteEditor.prototype.bindEvents = function(){ var that = this; this.$textarea.on('keydown.autocompleteEditor', function(event){ if(!Handsontable.helper.isMetaKey(event.keyCode) || [Handsontable.helper.keyCode.BACKSPACE, Handsontable.helper.keyCode.DELETE].indexOf(event.keyCode) != -1){ setTimeout(function () { that.queryChoices(that.$textarea.val()); }); } else if (event.keyCode == Handsontable.helper.keyCode.ENTER && that.cellProperties.strict !== true){ that.$htContainer.handsontable('deselectCell'); } }); this.$htContainer.on('mouseenter', function () { that.$htContainer.handsontable('deselectCell'); }); this.$htContainer.on('mouseleave', function () { that.queryChoices(that.query); }); Handsontable.editors.HandsontableEditor.prototype.bindEvents.apply(this, arguments); }; AutocompleteEditor.prototype.beginEditing = function () { Handsontable.editors.HandsontableEditor.prototype.beginEditing.apply(this, arguments); var that = this; setTimeout(function () { that.queryChoices(that.TEXTAREA.value); }); var hot = this.$htContainer.handsontable('getInstance'); hot.updateSettings({ 'colWidths': [this.wtDom.outerWidth(this.TEXTAREA) - 2], afterRenderer: function (TD, row, col, prop, value, cellProperties) { var match = TD.innerHTML.match(new RegExp(that.query, 'i')); if(match){ TD.innerHTML = value.replace(match[0], '<strong>' + match[0] + '</strong>'); } } }); }; var onBeforeKeyDownInner; AutocompleteEditor.prototype.open = function () { var parent = this; onBeforeKeyDownInner = function (event) { var instance = this; if (event.keyCode == Handsontable.helper.keyCode.ARROW_UP){ if (instance.getSelected() && instance.getSelected()[0] == 0){ if(!parent.cellProperties.strict){ instance.deselectCell(); } parent.instance.listen(); parent.focus(); event.preventDefault(); event.stopImmediatePropagation(); } } }; this.$htContainer.handsontable('getInstance').addHook('beforeKeyDown', onBeforeKeyDownInner); Handsontable.editors.HandsontableEditor.prototype.open.apply(this, arguments); this.$textarea[0].style.visibility = 'visible'; parent.focus(); }; AutocompleteEditor.prototype.close = function () { this.$htContainer.handsontable('getInstance').removeHook('beforeKeyDown', onBeforeKeyDownInner); Handsontable.editors.HandsontableEditor.prototype.close.apply(this, arguments); }; AutocompleteEditor.prototype.queryChoices = function(query){ this.query = query; if (typeof this.cellProperties.source == 'function'){ var that = this; this.cellProperties.source(query, function(choices){ that.updateChoicesList(choices) }); } else if (Handsontable.helper.isArray(this.cellProperties.source)) { var choices; if(!query || this.cellProperties.filter === false){ choices = this.cellProperties.source; } else { var queryRegex = new RegExp(query, this.cellProperties.filteringCaseSensitive === true ? '' : 'i'); choices = this.cellProperties.source.filter(function(choice){ return queryRegex.test(choice); }); } this.updateChoicesList(choices) } else { this.updateChoicesList([]); } }; function findItemIndexToHighlight(items, value){ var bestMatch = {}; var valueLength = value.length; var currentItem; var indexOfValue; var charsLeft; for(var i = 0, len = items.length; i < len; i++){ currentItem = items[i]; if(valueLength > 0){ indexOfValue = currentItem.indexOf(value) } else { indexOfValue = currentItem === value ? 0 : -1; } if(indexOfValue == -1) continue; charsLeft = currentItem.length - indexOfValue - valueLength; if( typeof bestMatch.indexOfValue == 'undefined' || bestMatch.indexOfValue > indexOfValue || ( bestMatch.indexOfValue == indexOfValue && bestMatch.charsLeft > charsLeft ) ){ bestMatch.indexOfValue = indexOfValue; bestMatch.charsLeft = charsLeft; bestMatch.index = i; } } return bestMatch.index; } AutocompleteEditor.prototype.updateChoicesList = function (choices) { this.$htContainer.handsontable('loadData', Handsontable.helper.pivot([choices])); var value = this.getValue(); var rowToHighlight; if(this.cellProperties.strict === true){ rowToHighlight = findItemIndexToHighlight(choices, value); if ( typeof rowToHighlight == 'undefined'){ rowToHighlight = 0; } } if(typeof rowToHighlight == 'undefined'){ this.$htContainer.handsontable('deselectCell'); } else { this.$htContainer.handsontable('selectCell', rowToHighlight, 0); } this.focus(); }; Handsontable.editors.AutocompleteEditor = AutocompleteEditor; Handsontable.editors.registerEditor('autocomplete', AutocompleteEditor); })(Handsontable); (function(Handsontable){ var PasswordEditor = Handsontable.editors.TextEditor.prototype.extend(); var wtDom = new WalkontableDom(); PasswordEditor.prototype.createElements = function () { Handsontable.editors.TextEditor.prototype.createElements.apply(this, arguments); this.TEXTAREA = document.createElement('input'); this.TEXTAREA.setAttribute('type', 'password'); this.TEXTAREA.className = 'handsontableInput'; this.textareaStyle = this.TEXTAREA.style; this.textareaStyle.width = 0; this.textareaStyle.height = 0; this.$textarea = $(this.TEXTAREA); wtDom.empty(this.TEXTAREA_PARENT); this.TEXTAREA_PARENT.appendChild(this.TEXTAREA); }; Handsontable.editors.PasswordEditor = PasswordEditor; Handsontable.editors.registerEditor('password', PasswordEditor); })(Handsontable); (function (Handsontable) { var SelectEditor = Handsontable.editors.BaseEditor.prototype.extend(); SelectEditor.prototype.init = function(){ this.select = $('<select />') .addClass('htSelectEditor') .hide(); this.instance.rootElement.append(this.select); }; SelectEditor.prototype.prepare = function(){ Handsontable.editors.BaseEditor.prototype.prepare.apply(this, arguments); var selectOptions = this.cellProperties.selectOptions; var options; if (typeof selectOptions == 'function'){ options = this.prepareOptions(selectOptions(this.row, this.col, this.prop)) } else { options = this.prepareOptions(selectOptions); } var optionElements = []; for (var option in options){ if (options.hasOwnProperty(option)){ var optionElement = $('<option />'); optionElement.val(option); optionElement.html(options[option]); optionElements.push(optionElement); } } this.select.empty(); this.select.append(optionElements); }; SelectEditor.prototype.prepareOptions = function(optionsToPrepare){ var preparedOptions = {}; if (Handsontable.helper.isArray(optionsToPrepare)){ for(var i = 0, len = optionsToPrepare.length; i < len; i++){ preparedOptions[optionsToPrepare[i]] = optionsToPrepare[i]; } } else if (typeof optionsToPrepare == 'object') { preparedOptions = optionsToPrepare; } return preparedOptions; }; SelectEditor.prototype.getValue = function () { return this.select.val(); }; SelectEditor.prototype.setValue = function (value) { this.select.val(value); }; var onBeforeKeyDown = function (event) { var instance = this; var editor = instance.getActiveEditor(); switch (event.keyCode){ case Handsontable.helper.keyCode.ARROW_UP: var previousOption = editor.select.find('option:selected').prev(); if (previousOption.length == 1){ previousOption.prop('selected', true); } event.stopImmediatePropagation(); event.preventDefault(); break; case Handsontable.helper.keyCode.ARROW_DOWN: var nextOption = editor.select.find('option:selected').next(); if (nextOption.length == 1){ nextOption.prop('selected', true); } event.stopImmediatePropagation(); event.preventDefault(); break; } }; SelectEditor.prototype.open = function () { this.select.css({ height: $(this.TD).height(), 'min-width' : $(this.TD).outerWidth() }); this.select.show(); this.select.offset($(this.TD).offset()); this.instance.addHook('beforeKeyDown', onBeforeKeyDown); }; SelectEditor.prototype.close = function () { this.select.hide(); this.instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; SelectEditor.prototype.focus = function () { this.select.focus(); }; Handsontable.editors.SelectEditor = SelectEditor; Handsontable.editors.registerEditor('select', SelectEditor); })(Handsontable); (function (Handsontable) { var DropdownEditor = Handsontable.editors.AutocompleteEditor.prototype.extend(); DropdownEditor.prototype.prepare = function () { Handsontable.editors.AutocompleteEditor.prototype.prepare.apply(this, arguments); this.cellProperties.filter = false; this.cellProperties.strict = true; }; Handsontable.editors.DropdownEditor = DropdownEditor; Handsontable.editors.registerEditor('dropdown', DropdownEditor); })(Handsontable); /** * Numeric cell validator * @param {*} value - Value of edited cell * @param {*} callback - Callback called with validation result */ Handsontable.NumericValidator = function (value, callback) { if (value === null) { value = ''; } callback(/^-?\d*\.?\d*$/.test(value)); }; /** * Function responsible for validation of autocomplete value * @param {*} value - Value of edited cell * @param {*} calback - Callback called with validation result */ var process = function (value, callback) { var originalVal = value; var lowercaseVal = typeof originalVal === 'string' ? originalVal.toLowerCase() : null; return function (source) { var found = false; for (var s = 0, slen = source.length; s < slen; s++) { if (originalVal === source[s]) { found = true; //perfect match break; } else if (lowercaseVal === source[s].toLowerCase()) { // changes[i][3] = source[s]; //good match, fix the case << TODO? found = true; break; } } callback(found); } }; /** * Autocomplete cell validator * @param {*} value - Value of edited cell * @param {*} calback - Callback called with validation result */ Handsontable.AutocompleteValidator = function (value, callback) { if (this.strict && this.source) { typeof this.source === 'function' ? this.source(value, process(value, callback)) : process(value, callback)(this.source); } else { callback(true); } }; /** * Cell type is just a shortcut for setting bunch of cellProperties (used in getCellMeta) */ Handsontable.AutocompleteCell = { editor: Handsontable.editors.AutocompleteEditor, renderer: Handsontable.renderers.AutocompleteRenderer, validator: Handsontable.AutocompleteValidator }; Handsontable.CheckboxCell = { editor: Handsontable.editors.CheckboxEditor, renderer: Handsontable.renderers.CheckboxRenderer }; Handsontable.TextCell = { editor: Handsontable.editors.TextEditor, renderer: Handsontable.renderers.TextRenderer }; Handsontable.NumericCell = { editor: Handsontable.editors.TextEditor, renderer: Handsontable.renderers.NumericRenderer, validator: Handsontable.NumericValidator, dataType: 'number' }; Handsontable.DateCell = { editor: Handsontable.editors.DateEditor, renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell }; Handsontable.HandsontableCell = { editor: Handsontable.editors.HandsontableEditor, renderer: Handsontable.renderers.AutocompleteRenderer //displays small gray arrow on right side of the cell }; Handsontable.PasswordCell = { editor: Handsontable.editors.PasswordEditor, renderer: Handsontable.renderers.PasswordRenderer, copyable: false }; Handsontable.DropdownCell = { editor: Handsontable.editors.DropdownEditor, renderer: Handsontable.renderers.AutocompleteRenderer, //displays small gray arrow on right side of the cell validator: Handsontable.AutocompleteValidator }; //here setup the friendly aliases that are used by cellProperties.type Handsontable.cellTypes = { text: Handsontable.TextCell, date: Handsontable.DateCell, numeric: Handsontable.NumericCell, checkbox: Handsontable.CheckboxCell, autocomplete: Handsontable.AutocompleteCell, handsontable: Handsontable.HandsontableCell, password: Handsontable.PasswordCell, dropdown: Handsontable.DropdownCell }; //here setup the friendly aliases that are used by cellProperties.renderer and cellProperties.editor Handsontable.cellLookup = { validator: { numeric: Handsontable.NumericValidator, autocomplete: Handsontable.AutocompleteValidator } }; /* * jQuery.fn.autoResize 1.1+ * -- * https://github.com/warpech/jQuery.fn.autoResize * * This fork differs from others in a way that it autoresizes textarea in 2-dimensions (horizontally and vertically). * It was originally forked from alexbardas's repo but maybe should be merged with dpashkevich's repo in future. * * originally forked from: * https://github.com/jamespadolsey/jQuery.fn.autoResize * which is now located here: * https://github.com/alexbardas/jQuery.fn.autoResize * though the mostly maintained for is here: * https://github.com/dpashkevich/jQuery.fn.autoResize/network * * -- * This program is free software. It comes without any warranty, to * the extent permitted by applicable law. You can redistribute it * and/or modify it under the terms of the Do What The Fuck You Want * To Public License, Version 2, as published by Sam Hocevar. See * http://sam.zoy.org/wtfpl/COPYING for more details. */ (function($){ autoResize.defaults = { onResize: function(){}, animate: { duration: 200, complete: function(){} }, extraSpace: 50, minHeight: 'original', maxHeight: 500, minWidth: 'original', maxWidth: 500 }; autoResize.cloneCSSProperties = [ 'lineHeight', 'textDecoration', 'letterSpacing', 'fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust', 'padding' ]; autoResize.cloneCSSValues = { position: 'absolute', top: -9999, left: -9999, opacity: 0, overflow: 'hidden', overflowX: 'hidden', overflowY: 'hidden', border: '1px solid black', padding: '0.49em' //this must be about the width of caps W character }; autoResize.resizableFilterSelector = 'textarea,input:not(input[type]),input[type=text],input[type=password]'; autoResize.AutoResizer = AutoResizer; $.fn.autoResize = autoResize; function autoResize(config) { this.filter(autoResize.resizableFilterSelector).each(function(){ new AutoResizer( $(this), config ); }); return this; } function AutoResizer(el, config) { if(this.clones) return; this.config = $.extend({}, autoResize.defaults, config); this.el = el; this.nodeName = el[0].nodeName.toLowerCase(); this.previousScrollTop = null; if (config.maxWidth === 'original') config.maxWidth = el.width(); if (config.minWidth === 'original') config.minWidth = el.width(); if (config.maxHeight === 'original') config.maxHeight = el.height(); if (config.minHeight === 'original') config.minHeight = el.height(); if (this.nodeName === 'textarea') { el.css({ resize: 'none', overflowY: 'none' }); } el.data('AutoResizer', this); this.createClone(); this.injectClone(); this.bind(); } AutoResizer.prototype = { bind: function() { var check = $.proxy(function(){ this.check(); return true; }, this); this.unbind(); this.el .bind('keyup.autoResize', check) //.bind('keydown.autoResize', check) .bind('change.autoResize', check); this.check(null, true); }, unbind: function() { this.el.unbind('.autoResize'); }, createClone: function() { var el = this.el, self = this, config = this.config; this.clones = $(); if (config.minHeight !== 'original' || config.maxHeight !== 'original') { this.hClone = el.clone().height('auto'); this.clones = this.clones.add(this.hClone); } if (config.minWidth !== 'original' || config.maxWidth !== 'original') { this.wClone = $('<div/>').width('auto').css({ whiteSpace: 'nowrap', 'float': 'left' }); this.clones = this.clones.add(this.wClone); } $.each(autoResize.cloneCSSProperties, function(i, p){ self.clones.css(p, el.css(p)); }); this.clones .removeAttr('name') .removeAttr('id') .attr('tabIndex', -1) .css(autoResize.cloneCSSValues) .css('overflowY', 'scroll'); }, check: function(e, immediate) { var config = this.config, wClone = this.wClone, hClone = this.hClone, el = this.el, value = el.val(); if (wClone) { wClone.text(value); // Calculate new width + whether to change var cloneWidth = wClone.outerWidth(), newWidth = (cloneWidth + config.extraSpace) >= config.minWidth ? cloneWidth + config.extraSpace : config.minWidth, currentWidth = el.width(); newWidth = Math.min(newWidth, config.maxWidth); if ( (newWidth < currentWidth && newWidth >= config.minWidth) || (newWidth >= config.minWidth && newWidth <= config.maxWidth) ) { config.onResize.call(el); el.scrollLeft(0); config.animate && !immediate ? el.stop(1,1).animate({ width: newWidth }, config.animate) : el.width(newWidth); } } if (hClone) { if (newWidth) { hClone.width(newWidth); } hClone.height(0).val(value).scrollTop(10000); var scrollTop = hClone[0].scrollTop + config.extraSpace; // Don't do anything if scrollTop hasen't changed: if (this.previousScrollTop === scrollTop) { return; } this.previousScrollTop = scrollTop; if (scrollTop >= config.maxHeight) { scrollTop = config.maxHeight; } if (scrollTop < config.minHeight) { scrollTop = config.minHeight; } if(scrollTop == config.maxHeight && newWidth == config.maxWidth) { el.css('overflowY', 'scroll'); } else { el.css('overflowY', 'hidden'); } config.onResize.call(el); // Either animate or directly apply height: config.animate && !immediate ? el.stop(1,1).animate({ height: scrollTop }, config.animate) : el.height(scrollTop); } }, destroy: function() { this.unbind(); this.el.removeData('AutoResizer'); this.clones.remove(); delete this.el; delete this.hClone; delete this.wClone; delete this.clones; }, injectClone: function() { ( autoResize.cloneContainer || (autoResize.cloneContainer = $('<arclones/>').appendTo('body')) ).empty().append(this.clones); //this should be refactored so that a node is never cloned more than once } }; })(jQuery); /** * SheetClip - Spreadsheet Clipboard Parser * version 0.2 * * This tiny library transforms JavaScript arrays to strings that are pasteable by LibreOffice, OpenOffice, * Google Docs and Microsoft Excel. * * Copyright 2012, Marcin Warpechowski * Licensed under the MIT license. * http://github.com/warpech/sheetclip/ */ /*jslint white: true*/ (function (global) { "use strict"; function countQuotes(str) { return str.split('"').length - 1; } global.SheetClip = { parse: function (str) { var r, rlen, rows, arr = [], a = 0, c, clen, multiline, last; rows = str.split('\n'); if (rows.length > 1 && rows[rows.length - 1] === '') { rows.pop(); } for (r = 0, rlen = rows.length; r < rlen; r += 1) { rows[r] = rows[r].split('\t'); for (c = 0, clen = rows[r].length; c < clen; c += 1) { if (!arr[a]) { arr[a] = []; } if (multiline && c === 0) { last = arr[a].length - 1; arr[a][last] = arr[a][last] + '\n' + rows[r][0]; if (multiline && (countQuotes(rows[r][0]) & 1)) { //& 1 is a bitwise way of performing mod 2 multiline = false; arr[a][last] = arr[a][last].substring(0, arr[a][last].length - 1).replace(/""/g, '"'); } } else { if (c === clen - 1 && rows[r][c].indexOf('"') === 0) { arr[a].push(rows[r][c].substring(1).replace(/""/g, '"')); multiline = true; } else { arr[a].push(rows[r][c].replace(/""/g, '"')); multiline = false; } } } if (!multiline) { a += 1; } } return arr; }, stringify: function (arr) { var r, rlen, c, clen, str = '', val; for (r = 0, rlen = arr.length; r < rlen; r += 1) { for (c = 0, clen = arr[r].length; c < clen; c += 1) { if (c > 0) { str += '\t'; } val = arr[r][c]; if (typeof val === 'string') { if (val.indexOf('\n') > -1) { str += '"' + val.replace(/"/g, '""') + '"'; } else { str += val; } } else if (val === null || val === void 0) { //void 0 resolves to undefined str += ''; } else { str += val; } } str += '\n'; } return str; } }; }(window)); /** * CopyPaste.js * Creates a textarea that stays hidden on the page and gets focused when user presses CTRL while not having a form input focused * In future we may implement a better driver when better APIs are available * @constructor */ var CopyPaste = (function () { var instance; return { getInstance: function () { if (!instance) { instance = new CopyPasteClass(); } else if (instance.hasBeenDestroyed()){ instance.init(); } instance.refCounter++; return instance; } }; })(); function CopyPasteClass() { this.refCounter = 0; this.init(); } CopyPasteClass.prototype.init = function () { var that = this , style , parent; this.copyCallbacks = []; this.cutCallbacks = []; this.pasteCallbacks = []; this.listenerElement = document.documentElement; parent = document.body; if (document.getElementById('CopyPasteDiv')) { this.elDiv = document.getElementById('CopyPasteDiv'); this.elTextarea = this.elDiv.firstChild; } else { this.elDiv = document.createElement('DIV'); this.elDiv.id = 'CopyPasteDiv'; style = this.elDiv.style; style.position = 'fixed'; style.top = 0; style.left = 0; parent.appendChild(this.elDiv); this.elTextarea = document.createElement('TEXTAREA'); this.elTextarea.className = 'copyPaste'; style = this.elTextarea.style; style.width = '1px'; style.height = '1px'; this.elDiv.appendChild(this.elTextarea); if (typeof style.opacity !== 'undefined') { style.opacity = 0; } else { /*@cc_on @if (@_jscript) if(typeof style.filter === 'string') { style.filter = 'alpha(opacity=0)'; } @end @*/ } } this.keydownListener = function (event) { var isCtrlDown = false; if (event.metaKey) { //mac isCtrlDown = true; } else if (event.ctrlKey && navigator.userAgent.indexOf('Mac') === -1) { //pc isCtrlDown = true; } if (isCtrlDown) { if (document.activeElement !== that.elTextarea && (that.getSelectionText() != '' || ['INPUT', 'SELECT', 'TEXTAREA'].indexOf(document.activeElement.nodeName) != -1)) { return; //this is needed by fragmentSelection in Handsontable. Ignore copypaste.js behavior if fragment of cell text is selected } that.selectNodeText(that.elTextarea); setTimeout(function () { that.selectNodeText(that.elTextarea); }, 0); } /* 67 = c * 86 = v * 88 = x */ if (isCtrlDown && (event.keyCode === 67 || event.keyCode === 86 || event.keyCode === 88)) { // that.selectNodeText(that.elTextarea); if (event.keyCode === 88) { //works in all browsers, incl. Opera < 12.12 setTimeout(function () { that.triggerCut(event); }, 0); } else if (event.keyCode === 86) { setTimeout(function () { that.triggerPaste(event); }, 0); } } } this._bindEvent(this.listenerElement, 'keydown', this.keydownListener); }; //http://jsperf.com/textara-selection //http://stackoverflow.com/questions/1502385/how-can-i-make-this-code-work-in-ie CopyPasteClass.prototype.selectNodeText = function (el) { el.select(); }; //http://stackoverflow.com/questions/5379120/get-the-highlighted-selected-text CopyPasteClass.prototype.getSelectionText = function () { var text = ""; if (window.getSelection) { text = window.getSelection().toString(); } else if (document.selection && document.selection.type != "Control") { text = document.selection.createRange().text; } return text; }; CopyPasteClass.prototype.copyable = function (str) { if (typeof str !== 'string' && str.toString === void 0) { throw new Error('copyable requires string parameter'); } this.elTextarea.value = str; }; /*CopyPasteClass.prototype.onCopy = function (fn) { this.copyCallbacks.push(fn); };*/ CopyPasteClass.prototype.onCut = function (fn) { this.cutCallbacks.push(fn); }; CopyPasteClass.prototype.onPaste = function (fn) { this.pasteCallbacks.push(fn); }; CopyPasteClass.prototype.removeCallback = function (fn) { var i, ilen; for (i = 0, ilen = this.copyCallbacks.length; i < ilen; i++) { if (this.copyCallbacks[i] === fn) { this.copyCallbacks.splice(i, 1); return true; } } for (i = 0, ilen = this.cutCallbacks.length; i < ilen; i++) { if (this.cutCallbacks[i] === fn) { this.cutCallbacks.splice(i, 1); return true; } } for (i = 0, ilen = this.pasteCallbacks.length; i < ilen; i++) { if (this.pasteCallbacks[i] === fn) { this.pasteCallbacks.splice(i, 1); return true; } } return false; }; CopyPasteClass.prototype.triggerCut = function (event) { var that = this; if (that.cutCallbacks) { setTimeout(function () { for (var i = 0, ilen = that.cutCallbacks.length; i < ilen; i++) { that.cutCallbacks[i](event); } }, 50); } }; CopyPasteClass.prototype.triggerPaste = function (event, str) { var that = this; if (that.pasteCallbacks) { setTimeout(function () { var val = (str || that.elTextarea.value).replace(/\n$/, ''); //remove trailing newline for (var i = 0, ilen = that.pasteCallbacks.length; i < ilen; i++) { that.pasteCallbacks[i](val, event); } }, 50); } }; CopyPasteClass.prototype.destroy = function () { if(!this.hasBeenDestroyed() && --this.refCounter == 0){ if (this.elDiv && this.elDiv.parentNode) { this.elDiv.parentNode.removeChild(this.elDiv); } this._unbindEvent(this.listenerElement, 'keydown', this.keydownListener); } }; CopyPasteClass.prototype.hasBeenDestroyed = function () { return !this.refCounter; }; //old version used this: // - http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/ // - http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization //but that cannot work with jQuery.trigger CopyPasteClass.prototype._bindEvent = (function () { if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests) return function (elem, type, cb) { $(elem).on(type + '.copypaste', cb); }; } else { return function (elem, type, cb) { elem.addEventListener(type, cb, false); //sorry, IE8 will only work with jQuery }; } })(); CopyPasteClass.prototype._unbindEvent = (function () { if (window.jQuery) { //if jQuery exists, use jQuery event (for compatibility with $.trigger and $.triggerHandler, which can only trigger jQuery events - and we use that in tests) return function (elem, type, cb) { $(elem).off(type + '.copypaste', cb); }; } else { return function (elem, type, cb) { elem.removeEventListener(type, cb, false); //sorry, IE8 will only work with jQuery }; } })(); // json-patch-duplex.js 0.3.6 // (c) 2013 Joachim Wester // MIT license var jsonpatch; (function (jsonpatch) { var objOps = { add: function (obj, key) { obj[key] = this.value; return true; }, remove: function (obj, key) { delete obj[key]; return true; }, replace: function (obj, key) { obj[key] = this.value; return true; }, move: function (obj, key, tree) { var temp = { op: "_get", path: this.from }; apply(tree, [temp]); apply(tree, [ { op: "remove", path: this.from } ]); apply(tree, [ { op: "add", path: this.path, value: temp.value } ]); return true; }, copy: function (obj, key, tree) { var temp = { op: "_get", path: this.from }; apply(tree, [temp]); apply(tree, [ { op: "add", path: this.path, value: temp.value } ]); return true; }, test: function (obj, key) { return (JSON.stringify(obj[key]) === JSON.stringify(this.value)); }, _get: function (obj, key) { this.value = obj[key]; } }; var arrOps = { add: function (arr, i) { arr.splice(i, 0, this.value); return true; }, remove: function (arr, i) { arr.splice(i, 1); return true; }, replace: function (arr, i) { arr[i] = this.value; return true; }, move: objOps.move, copy: objOps.copy, test: objOps.test, _get: objOps._get }; var observeOps = { add: function (patches, path) { var patch = { op: "add", path: path + escapePathComponent(this.name), value: this.object[this.name] }; patches.push(patch); }, 'delete': function (patches, path) { var patch = { op: "remove", path: path + escapePathComponent(this.name) }; patches.push(patch); }, update: function (patches, path) { var patch = { op: "replace", path: path + escapePathComponent(this.name), value: this.object[this.name] }; patches.push(patch); } }; function escapePathComponent(str) { if (str.indexOf('/') === -1 && str.indexOf('~') === -1) return str; return str.replace(/~/g, '~0').replace(/\//g, '~1'); } function _getPathRecursive(root, obj) { var found; for (var key in root) { if (root.hasOwnProperty(key)) { if (root[key] === obj) { return escapePathComponent(key) + '/'; } else if (typeof root[key] === 'object') { found = _getPathRecursive(root[key], obj); if (found != '') { return escapePathComponent(key) + '/' + found; } } } } return ''; } function getPath(root, obj) { if (root === obj) { return '/'; } var path = _getPathRecursive(root, obj); if (path === '') { throw new Error("Object not found in root"); } return '/' + path; } var beforeDict = []; jsonpatch.intervals; var Mirror = (function () { function Mirror(obj) { this.observers = []; this.obj = obj; } return Mirror; })(); var ObserverInfo = (function () { function ObserverInfo(callback, observer) { this.callback = callback; this.observer = observer; } return ObserverInfo; })(); function getMirror(obj) { for (var i = 0, ilen = beforeDict.length; i < ilen; i++) { if (beforeDict[i].obj === obj) { return beforeDict[i]; } } } function getObserverFromMirror(mirror, callback) { for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) { if (mirror.observers[j].callback === callback) { return mirror.observers[j].observer; } } } function removeObserverFromMirror(mirror, observer) { for (var j = 0, jlen = mirror.observers.length; j < jlen; j++) { if (mirror.observers[j].observer === observer) { mirror.observers.splice(j, 1); return; } } } function unobserve(root, observer) { generate(observer); if (Object.observe) { _unobserve(observer, root); } else { clearTimeout(observer.next); } var mirror = getMirror(root); removeObserverFromMirror(mirror, observer); } jsonpatch.unobserve = unobserve; function observe(obj, callback) { var patches = []; var root = obj; var observer; var mirror = getMirror(obj); if (!mirror) { mirror = new Mirror(obj); beforeDict.push(mirror); } else { observer = getObserverFromMirror(mirror, callback); } if (observer) { return observer; } if (Object.observe) { observer = function (arr) { //This "refresh" is needed to begin observing new object properties _unobserve(observer, obj); _observe(observer, obj); var a = 0, alen = arr.length; while (a < alen) { if (!(arr[a].name === 'length' && _isArray(arr[a].object)) && !(arr[a].name === '__Jasmine_been_here_before__')) { var type = arr[a].type; switch (type) { case 'new': type = 'add'; break; case 'deleted': type = 'delete'; break; case 'updated': type = 'update'; break; } observeOps[type].call(arr[a], patches, getPath(root, arr[a].object)); } a++; } if (patches) { if (callback) { callback(patches); } } observer.patches = patches; patches = []; }; } else { observer = {}; mirror.value = JSON.parse(JSON.stringify(obj)); if (callback) { //callbacks.push(callback); this has no purpose observer.callback = callback; observer.next = null; var intervals = this.intervals || [100, 1000, 10000, 60000]; var currentInterval = 0; var dirtyCheck = function () { generate(observer); }; var fastCheck = function () { clearTimeout(observer.next); observer.next = setTimeout(function () { dirtyCheck(); currentInterval = 0; observer.next = setTimeout(slowCheck, intervals[currentInterval++]); }, 0); }; var slowCheck = function () { dirtyCheck(); if (currentInterval == intervals.length) currentInterval = intervals.length - 1; observer.next = setTimeout(slowCheck, intervals[currentInterval++]); }; if (typeof window !== 'undefined') { if (window.addEventListener) { window.addEventListener('mousedown', fastCheck); window.addEventListener('mouseup', fastCheck); window.addEventListener('keydown', fastCheck); } else { window.attachEvent('onmousedown', fastCheck); window.attachEvent('onmouseup', fastCheck); window.attachEvent('onkeydown', fastCheck); } } observer.next = setTimeout(slowCheck, intervals[currentInterval++]); } } observer.patches = patches; observer.object = obj; mirror.observers.push(new ObserverInfo(callback, observer)); return _observe(observer, obj); } jsonpatch.observe = observe; /// Listen to changes on an object tree, accumulate patches function _observe(observer, obj) { if (Object.observe) { Object.observe(obj, observer); for (var key in obj) { if (obj.hasOwnProperty(key)) { var v = obj[key]; if (v && typeof (v) === "object") { _observe(observer, v); } } } } return observer; } function _unobserve(observer, obj) { if (Object.observe) { Object.unobserve(obj, observer); for (var key in obj) { if (obj.hasOwnProperty(key)) { var v = obj[key]; if (v && typeof (v) === "object") { _unobserve(observer, v); } } } } return observer; } function generate(observer) { if (Object.observe) { Object.deliverChangeRecords(observer); } else { var mirror; for (var i = 0, ilen = beforeDict.length; i < ilen; i++) { if (beforeDict[i].obj === observer.object) { mirror = beforeDict[i]; break; } } _generate(mirror.value, observer.object, observer.patches, ""); } var temp = observer.patches; if (temp.length > 0) { observer.patches = []; if (observer.callback) { observer.callback(temp); } } return temp; } jsonpatch.generate = generate; var _objectKeys; if (Object.keys) { _objectKeys = Object.keys; } else { _objectKeys = function (obj) { var keys = []; for (var o in obj) { if (obj.hasOwnProperty(o)) { keys.push(o); } } return keys; }; } // Dirty check if obj is different from mirror, generate patches and update mirror function _generate(mirror, obj, patches, path) { var newKeys = _objectKeys(obj); var oldKeys = _objectKeys(mirror); var changed = false; var deleted = false; for (var t = oldKeys.length - 1; t >= 0; t--) { var key = oldKeys[t]; var oldVal = mirror[key]; if (obj.hasOwnProperty(key)) { var newVal = obj[key]; if (oldVal instanceof Object) { _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key)); } else { if (oldVal != newVal) { changed = true; patches.push({ op: "replace", path: path + "/" + escapePathComponent(key), value: newVal }); mirror[key] = newVal; } } } else { patches.push({ op: "remove", path: path + "/" + escapePathComponent(key) }); delete mirror[key]; deleted = true; } } if (!deleted && newKeys.length == oldKeys.length) { return; } for (var t = 0; t < newKeys.length; t++) { var key = newKeys[t]; if (!mirror.hasOwnProperty(key)) { patches.push({ op: "add", path: path + "/" + escapePathComponent(key), value: obj[key] }); mirror[key] = JSON.parse(JSON.stringify(obj[key])); } } } var _isArray; if (Array.isArray) { _isArray = Array.isArray; } else { _isArray = function (obj) { return obj.push && typeof obj.length === 'number'; }; } /// Apply a json-patch operation on an object tree function apply(tree, patches) { var result = false, p = 0, plen = patches.length, patch; while (p < plen) { patch = patches[p]; // Find the object var keys = patch.path.split('/'); var obj = tree; var t = 1; var len = keys.length; while (true) { if (_isArray(obj)) { var index = parseInt(keys[t], 10); t++; if (t >= len) { result = arrOps[patch.op].call(patch, obj, index, tree); break; } obj = obj[index]; } else { var key = keys[t]; if (key.indexOf('~') != -1) key = key.replace(/~1/g, '/').replace(/~0/g, '~'); t++; if (t >= len) { result = objOps[patch.op].call(patch, obj, key, tree); break; } obj = obj[key]; } } p++; } return result; } jsonpatch.apply = apply; })(jsonpatch || (jsonpatch = {})); if (typeof exports !== "undefined") { exports.apply = jsonpatch.apply; exports.observe = jsonpatch.observe; exports.unobserve = jsonpatch.unobserve; exports.generate = jsonpatch.generate; } Handsontable.PluginHookClass = (function () { var Hooks = function () { return { // Hooks beforeInitWalkontable: [], beforeInit: [], beforeRender: [], beforeChange: [], beforeRemoveCol: [], beforeRemoveRow: [], beforeValidate: [], beforeGet: [], beforeSet: [], beforeGetCellMeta: [], beforeAutofill: [], beforeKeyDown: [], beforeColumnSort: [], afterInit : [], afterLoadData : [], afterUpdateSettings: [], afterRender : [], afterRenderer : [], afterChange : [], afterValidate: [], afterGetCellMeta: [], afterGetColHeader: [], afterGetColWidth: [], afterDestroy: [], afterRemoveRow: [], afterCreateRow: [], afterRemoveCol: [], afterCreateCol: [], afterColumnResize: [], afterColumnMove: [], afterColumnSort: [], afterDeselect: [], afterSelection: [], afterSelectionByProp: [], afterSelectionEnd: [], afterSelectionEndByProp: [], afterCopyLimit: [], afterOnCellMouseDown: [], afterOnCellMouseOver: [], afterOnCellCornerMouseDown: [], afterScrollVertically: [], afterScrollHorizontally: [], // Modifiers modifyCol: [] } }; var legacy = { onBeforeChange: "beforeChange", onChange: "afterChange", onCreateRow: "afterCreateRow", onCreateCol: "afterCreateCol", onSelection: "afterSelection", onCopyLimit: "afterCopyLimit", onSelectionEnd: "afterSelectionEnd", onSelectionByProp: "afterSelectionByProp", onSelectionEndByProp: "afterSelectionEndByProp" }; function PluginHookClass() { this.hooks = Hooks(); this.legacy = legacy; } PluginHookClass.prototype.add = function (key, fn) { // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } if (typeof this.hooks[key] === "undefined") { this.hooks[key] = []; } if (Handsontable.helper.isArray(fn)) { for (var i = 0, len = fn.length; i < len; i++) { this.hooks[key].push(fn[i]); } } else { if (this.hooks[key].indexOf(fn) > -1) { throw new Error("Seems that you are trying to set the same plugin hook twice (" + key + ", " + fn + ")"); //error here should help writing bug-free plugins } this.hooks[key].push(fn); } return this; }; PluginHookClass.prototype.once = function(key, fn){ if(Handsontable.helper.isArray(fn)){ for(var i = 0, len = fn.length; i < len; i++){ fn[i].runOnce = true; this.add(key, fn[i]); } } else { fn.runOnce = true; this.add(key, fn); } }; PluginHookClass.prototype.remove = function (key, fn) { var status = false; // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } if (typeof this.hooks[key] !== 'undefined') { for (var i = 0, leni = this.hooks[key].length; i < leni; i++) { if (this.hooks[key][i] == fn) { delete this.hooks[key][i].runOnce; this.hooks[key].splice(i, 1); status = true; break; } } } return status; }; PluginHookClass.prototype.run = function (instance, key, p1, p2, p3, p4, p5) { // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } //performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture if (typeof this.hooks[key] !== 'undefined') { //Make a copy of handler array var handlers = Array.prototype.slice.call(this.hooks[key]); for (var i = 0, leni = handlers.length; i < leni; i++) { handlers[i].call(instance, p1, p2, p3, p4, p5); if(handlers[i].runOnce){ this.remove(key, handlers[i]); } } } }; PluginHookClass.prototype.execute = function (instance, key, p1, p2, p3, p4, p5) { var res, handlers; // provide support for old versions of HOT if (key in legacy) { key = legacy[key]; } //performance considerations - http://jsperf.com/call-vs-apply-for-a-plugin-architecture if (typeof this.hooks[key] !== 'undefined') { handlers = Array.prototype.slice.call(this.hooks[key]); for (var i = 0, leni = handlers.length; i < leni; i++) { res = handlers[i].call(instance, p1, p2, p3, p4, p5); if (res !== void 0) { p1 = res; } if(handlers[i].runOnce){ this.remove(key, handlers[i]); } if(res === false){ //if any handler returned false return false; //event has been cancelled and further execution of handler queue is being aborted } } } return p1; }; return PluginHookClass; })(); Handsontable.PluginHooks = new Handsontable.PluginHookClass(); (function (Handsontable) { function HandsontableAutoColumnSize() { var plugin = this , sampleCount = 5; //number of samples to take of each value length this.beforeInit = function () { var instance = this; instance.autoColumnWidths = []; if (instance.getSettings().autoColumnSize !== false) { if (!instance.autoColumnSizeTmp) { instance.autoColumnSizeTmp = { table: null, tableStyle: null, theadTh: null, tbody: null, container: null, containerStyle: null, determineBeforeNextRender: true }; instance.addHook('beforeRender', htAutoColumnSize.determineIfChanged); instance.addHook('afterGetColWidth', htAutoColumnSize.getColWidth); instance.addHook('afterDestroy', htAutoColumnSize.afterDestroy); instance.determineColumnWidth = plugin.determineColumnWidth; } } else { if (instance.autoColumnSizeTmp) { instance.removeHook('beforeRender', htAutoColumnSize.determineIfChanged); instance.removeHook('afterGetColWidth', htAutoColumnSize.getColWidth); instance.removeHook('afterDestroy', htAutoColumnSize.afterDestroy); delete instance.determineColumnWidth; plugin.afterDestroy.call(instance); } } }; this.determineIfChanged = function (force) { if (force) { htAutoColumnSize.determineColumnsWidth.apply(this, arguments); } }; this.determineColumnWidth = function (col) { var instance = this , tmp = instance.autoColumnSizeTmp; if (!tmp.container) { createTmpContainer.call(tmp, instance); } tmp.container.className = instance.rootElement[0].className + ' htAutoColumnSize'; tmp.table.className = instance.$table[0].className; var rows = instance.countRows(); var samples = {}; var maxLen = 0; for (var r = 0; r < rows; r++) { var value = Handsontable.helper.stringify(instance.getDataAtCell(r, col)); var len = value.length; if (len > maxLen) { maxLen = len; } if (!samples[len]) { samples[len] = { needed: sampleCount, strings: [] }; } if (samples[len].needed) { samples[len].strings.push({value: value, row: r}); samples[len].needed--; } } var settings = instance.getSettings(); if (settings.colHeaders) { instance.view.appendColHeader(col, tmp.theadTh); //TH innerHTML } instance.view.wt.wtDom.empty(tmp.tbody); for (var i in samples) { if (samples.hasOwnProperty(i)) { for (var j = 0, jlen = samples[i].strings.length; j < jlen; j++) { var row = samples[i].strings[j].row; var cellProperties = instance.getCellMeta(row, col); cellProperties.col = col; cellProperties.row = row; var renderer = instance.getCellRenderer(cellProperties); var tr = document.createElement('tr'); var td = document.createElement('td'); renderer(instance, td, row, col, instance.colToProp(col), samples[i].strings[j].value, cellProperties); r++; tr.appendChild(td); tmp.tbody.appendChild(tr); } } } var parent = instance.rootElement[0].parentNode; parent.appendChild(tmp.container); var width = instance.view.wt.wtDom.outerWidth(tmp.table); parent.removeChild(tmp.container); if (!settings.nativeScrollbars) { //with native scrollbars a cell size can safely exceed the width of the viewport var maxWidth = instance.view.wt.wtViewport.getViewportWidth() - 2; //2 is some overhead for cell border if (width > maxWidth) { width = maxWidth; } } return width; }; this.determineColumnsWidth = function () { var instance = this; var settings = this.getSettings(); if (settings.autoColumnSize || !settings.colWidths) { var cols = this.countCols(); for (var c = 0; c < cols; c++) { if (!instance._getColWidthFromSettings(c)) { this.autoColumnWidths[c] = plugin.determineColumnWidth.call(instance, c); } } } }; this.getColWidth = function (col, response) { if (this.autoColumnWidths[col] && this.autoColumnWidths[col] > response.width) { response.width = this.autoColumnWidths[col]; } }; this.afterDestroy = function () { var instance = this; if (instance.autoColumnSizeTmp && instance.autoColumnSizeTmp.container && instance.autoColumnSizeTmp.container.parentNode) { instance.autoColumnSizeTmp.container.parentNode.removeChild(instance.autoColumnSizeTmp.container); } instance.autoColumnSizeTmp = null; }; function createTmpContainer(instance) { var d = document , tmp = this; tmp.table = d.createElement('table'); tmp.theadTh = d.createElement('th'); tmp.table.appendChild(d.createElement('thead')).appendChild(d.createElement('tr')).appendChild(tmp.theadTh); tmp.tableStyle = tmp.table.style; tmp.tableStyle.tableLayout = 'auto'; tmp.tableStyle.width = 'auto'; tmp.tbody = d.createElement('tbody'); tmp.table.appendChild(tmp.tbody); tmp.container = d.createElement('div'); tmp.container.className = instance.rootElement[0].className + ' hidden'; tmp.containerStyle = tmp.container.style; tmp.container.appendChild(tmp.table); } } var htAutoColumnSize = new HandsontableAutoColumnSize(); Handsontable.PluginHooks.add('beforeInit', htAutoColumnSize.beforeInit); Handsontable.PluginHooks.add('afterUpdateSettings', htAutoColumnSize.beforeInit); })(Handsontable); /** * This plugin sorts the view by a column (but does not sort the data source!) * @constructor */ function HandsontableColumnSorting() { var plugin = this; this.init = function (source) { var instance = this; var sortingSettings = instance.getSettings().columnSorting; var sortingColumn, sortingOrder; instance.sortingEnabled = !!(sortingSettings); if (instance.sortingEnabled) { instance.sortIndex = []; var loadedSortingState = loadSortingState.call(instance); if (typeof loadedSortingState != 'undefined') { sortingColumn = loadedSortingState.sortColumn; sortingOrder = loadedSortingState.sortOrder; } else { sortingColumn = sortingSettings.column; sortingOrder = sortingSettings.sortOrder; } plugin.sortByColumn.call(instance, sortingColumn, sortingOrder); instance.sort = function(){ var args = Array.prototype.slice.call(arguments); return plugin.sortByColumn.apply(instance, args) }; if (typeof instance.getSettings().observeChanges == 'undefined'){ enableObserveChangesPlugin.call(instance); } if (source == 'afterInit') { bindColumnSortingAfterClick.call(instance); instance.addHook('afterCreateRow', plugin.afterCreateRow); instance.addHook('afterRemoveRow', plugin.afterRemoveRow); instance.addHook('afterLoadData', plugin.init); } } else { delete instance.sort; instance.removeHook('afterCreateRow', plugin.afterCreateRow); instance.removeHook('afterRemoveRow', plugin.afterRemoveRow); instance.removeHook('afterLoadData', plugin.init); } }; this.setSortingColumn = function (col, order) { var instance = this; if (typeof col == 'undefined') { delete instance.sortColumn; delete instance.sortOrder; return; } else if (instance.sortColumn === col && typeof order == 'undefined') { instance.sortOrder = !instance.sortOrder; } else { instance.sortOrder = typeof order != 'undefined' ? order : true; } instance.sortColumn = col; }; this.sortByColumn = function (col, order) { var instance = this; plugin.setSortingColumn.call(instance, col, order); if(typeof instance.sortColumn == 'undefined'){ return; } instance.PluginHooks.run('beforeColumnSort', instance.sortColumn, instance.sortOrder); plugin.sort.call(instance); instance.render(); saveSortingState.call(instance); instance.PluginHooks.run('afterColumnSort', instance.sortColumn, instance.sortOrder); }; var saveSortingState = function () { var instance = this; var sortingState = {}; if (typeof instance.sortColumn != 'undefined') { sortingState.sortColumn = instance.sortColumn; } if (typeof instance.sortOrder != 'undefined') { sortingState.sortOrder = instance.sortOrder; } if (sortingState.hasOwnProperty('sortColumn') || sortingState.hasOwnProperty('sortOrder')) { instance.PluginHooks.run('persistentStateSave', 'columnSorting', sortingState); } }; var loadSortingState = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'columnSorting', storedState); return storedState.value; }; var bindColumnSortingAfterClick = function () { var instance = this; instance.rootElement.on('click.handsontable', '.columnSorting', function (e) { if (instance.view.wt.wtDom.hasClass(e.target, 'columnSorting')) { var col = getColumn(e.target); plugin.sortByColumn.call(instance, col); } }); function countRowHeaders() { var THs = instance.view.TBODY.querySelector('tr').querySelectorAll('th'); return THs.length; } function getColumn(target) { var TH = instance.view.wt.wtDom.closest(target, 'TH'); return instance.view.wt.wtDom.index(TH) - countRowHeaders(); } }; function enableObserveChangesPlugin () { var instance = this; instance.registerTimeout('enableObserveChanges', function(){ instance.updateSettings({ observeChanges: true }); }, 0); } function defaultSort(sortOrder) { return function (a, b) { if (a[1] === b[1]) { return 0; } if (a[1] === null) { return 1; } if (b[1] === null) { return -1; } if (a[1] < b[1]) return sortOrder ? -1 : 1; if (a[1] > b[1]) return sortOrder ? 1 : -1; return 0; } } function dateSort(sortOrder) { return function (a, b) { if (a[1] === b[1]) { return 0; } if (a[1] === null) { return 1; } if (b[1] === null) { return -1; } var aDate = new Date(a[1]); var bDate = new Date(b[1]); if (aDate < bDate) return sortOrder ? -1 : 1; if (aDate > bDate) return sortOrder ? 1 : -1; return 0; } } this.sort = function () { var instance = this; if (typeof instance.sortOrder == 'undefined') { return; } instance.sortingEnabled = false; //this is required by translateRow plugin hook instance.sortIndex.length = 0; var colOffset = this.colOffset(); for (var i = 0, ilen = this.countRows() - instance.getSettings()['minSpareRows']; i < ilen; i++) { this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]); } var colMeta = instance.getCellMeta(0, instance.sortColumn); var sortFunction; switch (colMeta.type) { case 'date': sortFunction = dateSort; break; default: sortFunction = defaultSort; } this.sortIndex.sort(sortFunction(instance.sortOrder)); //Append spareRows for(var i = this.sortIndex.length; i < instance.countRows(); i++){ this.sortIndex.push([i, instance.getDataAtCell(i, this.sortColumn + colOffset)]); } instance.sortingEnabled = true; //this is required by translateRow plugin hook }; this.translateRow = function (row) { var instance = this; if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length && instance.sortIndex[row]) { return instance.sortIndex[row][0]; } return row; }; this.onBeforeGetSet = function (getVars) { var instance = this; getVars.row = plugin.translateRow.call(instance, getVars.row); }; this.untranslateRow = function (row) { var instance = this; if (instance.sortingEnabled && instance.sortIndex && instance.sortIndex.length) { for (var i = 0; i < instance.sortIndex.length; i++) { if (instance.sortIndex[i][0] == row) { return i; } } } }; this.getColHeader = function (col, TH) { if (this.getSettings().columnSorting) { this.view.wt.wtDom.addClass(TH.querySelector('.colHeader'), 'columnSorting'); } }; function isSorted(instance){ return typeof instance.sortColumn != 'undefined'; } this.afterCreateRow = function(index, amount){ var instance = this; if(!isSorted(instance)){ return; } for(var i = 0; i < instance.sortIndex.length; i++){ if (instance.sortIndex[i][0] >= index){ instance.sortIndex[i][0] += amount; } } for(var i=0; i < amount; i++){ instance.sortIndex.splice(index+i, 0, [index+i, instance.getData()[index+i][instance.sortColumn + instance.colOffset()]]); } saveSortingState.call(instance); }; this.afterRemoveRow = function(index, amount){ var instance = this; if(!isSorted(instance)){ return; } var physicalRemovedIndex = plugin.translateRow.call(instance, index); instance.sortIndex.splice(index, amount); for(var i = 0; i < instance.sortIndex.length; i++){ if (instance.sortIndex[i][0] > physicalRemovedIndex){ instance.sortIndex[i][0] -= amount; } } saveSortingState.call(instance); }; this.afterChangeSort = function (changes/*, source*/) { var instance = this; var sortColumnChanged = false; var selection = {}; if (!changes) { return; } for (var i = 0; i < changes.length; i++) { if (changes[i][1] == instance.sortColumn) { sortColumnChanged = true; selection.row = plugin.translateRow.call(instance, changes[i][0]); selection.col = changes[i][1]; break; } } if (sortColumnChanged) { setTimeout(function () { plugin.sort.call(instance); instance.render(); instance.selectCell(plugin.untranslateRow.call(instance, selection.row), selection.col); }, 0); } }; } var htSortColumn = new HandsontableColumnSorting(); Handsontable.PluginHooks.add('afterInit', function () { htSortColumn.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htSortColumn.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('beforeGet', htSortColumn.onBeforeGetSet); Handsontable.PluginHooks.add('beforeSet', htSortColumn.onBeforeGetSet); Handsontable.PluginHooks.add('afterGetColHeader', htSortColumn.getColHeader); (function (Handsontable) { 'use strict'; function ContextMenu(instance, customOptions){ this.instance = instance; var contextMenu = this; this.menu = createMenu(); this.enabled = true; this.bindMouseEvents(); this.bindTableEvents(); this.instance.addHook('afterDestroy', function () { contextMenu.destroy(); }); this.defaultOptions = { items: { 'row_above': { name: 'Insert row above', callback: function(key, selection){ this.alter("insert_row", selection.start.row()); }, disabled: function () { return this.countRows() >= this.getSettings().maxRows; } }, 'row_below': { name: 'Insert row below', callback: function(key, selection){ this.alter("insert_row", selection.end.row() + 1); }, disabled: function () { return this.countRows() >= this.getSettings().maxRows; } }, "hsep1": ContextMenu.SEPARATOR, 'col_left': { name: 'Insert column on the left', callback: function(key, selection){ this.alter("insert_col", selection.start.col()); }, disabled: function () { return this.countCols() >= this.getSettings().maxCols; } }, 'col_right': { name: 'Insert column on the right', callback: function(key, selection){ this.alter("insert_col", selection.end.col() + 1); }, disabled: function () { return this.countCols() >= this.getSettings().maxCols; } }, "hsep2": ContextMenu.SEPARATOR, 'remove_row': { name: 'Remove row', callback: function(key, selection){ var amount = selection.end.row() - selection.start.row() + 1; this.alter("remove_row", selection.start.row(), amount); } }, 'remove_col': { name: 'Remove column', callback: function(key, selection){ var amount = selection.end.col() - selection.start.col() + 1; this.alter("remove_col", selection.start.col(), amount); } }, "hsep3": ContextMenu.SEPARATOR, 'undo': { name: 'Undo', callback: function(){ this.undo(); }, disabled: function () { return this.undoRedo && !this.undoRedo.isUndoAvailable(); } }, 'redo': { name: 'Redo', callback: function(){ this.redo(); }, disabled: function () { return this.undoRedo && !this.undoRedo.isRedoAvailable(); } } } }; this.options = {}; Handsontable.helper.extend(this.options, this.defaultOptions); this.updateOptions(customOptions); function createMenu(){ var menu = $('body > .htContextMenu')[0]; if(!menu){ menu = document.createElement('DIV'); Handsontable.Dom.addClass(menu, 'htContextMenu'); document.getElementsByTagName('body')[0].appendChild(menu); } return menu; } } ContextMenu.prototype.bindMouseEvents = function (){ function contextMenuOpenListener(event){ event.preventDefault(); if(event.target.nodeName != 'TD' && !(Handsontable.Dom.hasClass(event.target, 'current') && Handsontable.Dom.hasClass(event.target, 'wtBorder'))){ return; } this.show(event.pageY, event.pageX); $(document).on('mousedown.htContextMenu', Handsontable.helper.proxy(ContextMenu.prototype.close, this)); } this.instance.rootElement.on('contextmenu.htContextMenu', Handsontable.helper.proxy(contextMenuOpenListener, this)); }; ContextMenu.prototype.bindTableEvents = function () { var that = this; this._afterScrollCallback = function () { that.close(); }; this.instance.addHook('afterScrollVertically', this._afterScrollCallback); this.instance.addHook('afterScrollHorizontally', this._afterScrollCallback); }; ContextMenu.prototype.unbindTableEvents = function () { var that = this; if(this._afterScrollCallback){ this.instance.removeHook('afterScrollVertically', this._afterScrollCallback); this.instance.removeHook('afterScrollHorizontally', this._afterScrollCallback); this._afterScrollCallback = null; } }; ContextMenu.prototype.performAction = function (){ var hot = $(this.menu).handsontable('getInstance'); var selectedItemIndex = hot.getSelected()[0]; var selectedItem = hot.getData()[selectedItemIndex]; if (selectedItem.disabled === true || (typeof selectedItem.disabled == 'function' && selectedItem.disabled.call(this.instance) === true)){ return; } if(typeof selectedItem.callback != 'function'){ return; } var corners = this.instance.getSelected(); var normalizedSelection = ContextMenu.utils.normalizeSelection(corners); selectedItem.callback.call(this.instance, selectedItem.key, normalizedSelection); }; ContextMenu.prototype.unbindMouseEvents = function () { this.instance.rootElement.off('contextmenu.htContextMenu'); $(document).off('mousedown.htContextMenu'); }; ContextMenu.prototype.show = function(top, left){ this.menu.style.display = 'block'; $(this.menu) .off('mousedown.htContextMenu') .on('mousedown.htContextMenu', Handsontable.helper.proxy(this.performAction, this)); $(this.menu).handsontable({ data: ContextMenu.utils.convertItemsToArray(this.getItems()), colHeaders: false, colWidths: [160], readOnly: true, copyPaste: false, columns: [ { data: 'name', renderer: Handsontable.helper.proxy(this.renderer, this) } ], beforeKeyDown: Handsontable.helper.proxy(this.onBeforeKeyDown, this) }); this.bindTableEvents(); this.setMenuPosition(top, left); $(this.menu).handsontable('listen'); }; ContextMenu.prototype.close = function () { this.hide(); $(document).off('mousedown.htContextMenu'); this.unbindTableEvents(); this.instance.listen(); }; ContextMenu.prototype.hide = function(){ this.menu.style.display = 'none'; $(this.menu).handsontable('destroy'); }; ContextMenu.prototype.renderer = function(instance, TD, row, col, prop, value, cellProperties){ var contextMenu = this; var item = instance.getData()[row]; var wrapper = document.createElement('DIV'); Handsontable.Dom.empty(TD); TD.appendChild(wrapper); if(itemIsSeparator(item)){ Handsontable.Dom.addClass(TD, 'htSeparator'); } else { Handsontable.Dom.fastInnerText(wrapper, value); } if (itemIsDisabled(item, contextMenu.instance)){ Handsontable.Dom.addClass(TD, 'htDisabled'); $(wrapper).on('mouseenter', function () { instance.deselectCell(); }); } else { Handsontable.Dom.removeClass(TD, 'htDisabled'); $(wrapper).on('mouseenter', function () { instance.selectCell(row, col); }); } function itemIsSeparator(item){ return new RegExp(ContextMenu.SEPARATOR, 'i').test(item.name); } function itemIsDisabled(item, instance){ return item.disabled === true || (typeof item.disabled == 'function' && item.disabled.call(contextMenu.instance) === true); } }; ContextMenu.prototype.onBeforeKeyDown = function (event) { var contextMenu = this; var instance = $(contextMenu.menu).handsontable('getInstance'); var selection = instance.getSelected(); switch(event.keyCode){ case Handsontable.helper.keyCode.ESCAPE: contextMenu.close(); event.preventDefault(); event.stopImmediatePropagation(); break; case Handsontable.helper.keyCode.ENTER: if(instance.getSelected()){ contextMenu.performAction(); contextMenu.close(); } break; case Handsontable.helper.keyCode.ARROW_DOWN: if(!selection){ selectFirstCell(instance); } else { selectNextCell(selection[0], selection[1], instance); } event.preventDefault(); event.stopImmediatePropagation(); break; case Handsontable.helper.keyCode.ARROW_UP: if(!selection){ selectLastCell(instance); } else { selectPrevCell(selection[0], selection[1], instance); } event.preventDefault(); event.stopImmediatePropagation(); break; } function selectFirstCell(instance) { var firstCell = instance.getCell(0, 0); if(ContextMenu.utils.isSeparator(firstCell) || ContextMenu.utils.isDisabled(firstCell)){ selectNextCell(0, 0, instance); } else { instance.selectCell(0, 0); } } function selectLastCell(instance) { var lastRow = instance.countRows() - 1; var lastCell = instance.getCell(lastRow, 0); if(ContextMenu.utils.isSeparator(lastCell) || ContextMenu.utils.isDisabled(lastCell)){ selectPrevCell(lastRow, 0, instance); } else { instance.selectCell(lastRow, 0); } } function selectNextCell(row, col, instance){ var nextRow = row + 1; var nextCell = nextRow < instance.countRows() ? instance.getCell(nextRow, col) : null; if(!nextCell){ return; } if(ContextMenu.utils.isSeparator(nextCell) || ContextMenu.utils.isDisabled(nextCell)){ selectNextCell(nextRow, col, instance); } else { instance.selectCell(nextRow, col); } } function selectPrevCell(row, col, instance) { var prevRow = row - 1; var prevCell = prevRow >= 0 ? instance.getCell(prevRow, col) : null; if (!prevCell) { return; } if(ContextMenu.utils.isSeparator(prevCell) || ContextMenu.utils.isDisabled(prevCell)){ selectPrevCell(prevRow, col, instance); } else { instance.selectCell(prevRow, col); } } }; ContextMenu.prototype.getItems = function () { var items = {}; function Item(rawItem){ if(typeof rawItem == 'string'){ this.name = rawItem; } else { Handsontable.helper.extend(this, rawItem); } } Item.prototype = this.options; for(var itemName in this.options.items){ if(this.options.items.hasOwnProperty(itemName) && (!this.itemsFilter || this.itemsFilter.indexOf(itemName) != -1)){ items[itemName] = new Item(this.options.items[itemName]); } } return items; }; ContextMenu.prototype.updateOptions = function(newOptions){ newOptions = newOptions || {}; if(newOptions.items){ for(var itemName in newOptions.items){ var item = {}; if(newOptions.items.hasOwnProperty(itemName)) { if(this.defaultOptions.items.hasOwnProperty(itemName) && Handsontable.helper.isObject(newOptions.items[itemName])){ Handsontable.helper.extend(item, this.defaultOptions.items[itemName]); Handsontable.helper.extend(item, newOptions.items[itemName]); newOptions.items[itemName] = item; } } } } Handsontable.helper.extend(this.options, newOptions); }; ContextMenu.prototype.setMenuPosition = function (cursorY, cursorX) { var cursor = { top: cursorY, topRelative: cursorY - document.documentElement.scrollTop, left: cursorX, leftRelative:cursorX - document.documentElement.scrollLeft }; if(this.menuFitsBelowCursor(cursor)){ this.positionMenuBelowCursor(cursor); } else { this.positionMenuAboveCursor(cursor); } if(this.menuFitsOnRightOfCursor(cursor)){ this.positionMenuOnRightOfCursor(cursor); } else { this.positionMenuOnLeftOfCursor(cursor); } }; ContextMenu.prototype.menuFitsBelowCursor = function (cursor) { return cursor.topRelative + this.menu.offsetHeight <= document.documentElement.scrollTop + document.documentElement.clientHeight; }; ContextMenu.prototype.menuFitsOnRightOfCursor = function (cursor) { return cursor.leftRelative + this.menu.offsetWidth <= document.documentElement.scrollLeft + document.documentElement.clientWidth; }; ContextMenu.prototype.positionMenuBelowCursor = function (cursor) { this.menu.style.top = cursor.top + 'px'; }; ContextMenu.prototype.positionMenuAboveCursor = function (cursor) { this.menu.style.top = (cursor.top - this.menu.offsetHeight) + 'px'; }; ContextMenu.prototype.positionMenuOnRightOfCursor = function (cursor) { this.menu.style.left = cursor.left + 'px'; }; ContextMenu.prototype.positionMenuOnLeftOfCursor = function (cursor) { this.menu.style.left = (cursor.left - this.menu.offsetWidth) + 'px'; }; ContextMenu.utils = {}; ContextMenu.utils.convertItemsToArray = function (items) { var itemArray = []; var item; for(var itemName in items){ if(items.hasOwnProperty(itemName)){ if(typeof items[itemName] == 'string'){ item = {name: items[itemName]}; } else if (items[itemName].visible !== false) { item = items[itemName]; } else { continue; } item.key = itemName; itemArray.push(item); } } return itemArray; }; ContextMenu.utils.normalizeSelection = function(corners){ var selection = { start: new Handsontable.SelectionPoint(), end: new Handsontable.SelectionPoint() }; selection.start.row(Math.min(corners[0], corners[2])); selection.start.col(Math.min(corners[1], corners[3])); selection.end.row(Math.max(corners[0], corners[2])); selection.end.col(Math.max(corners[1], corners[3])); return selection; }; ContextMenu.utils.isSeparator = function (cell) { return Handsontable.Dom.hasClass(cell, 'htSeparator'); }; ContextMenu.utils.isDisabled = function (cell) { return Handsontable.Dom.hasClass(cell, 'htDisabled'); }; ContextMenu.prototype.enable = function () { if(!this.enabled){ this.enabled = true; this.bindMouseEvents(); } }; ContextMenu.prototype.disable = function () { if(this.enabled){ this.enabled = false; this.close(); this.unbindMouseEvents(); this.unbindTableEvents(); } }; ContextMenu.prototype.destroy = function () { this.close(); this.unbindMouseEvents(); this.unbindTableEvents(); if(!this.isMenuEnabledByOtherHotInstance()){ this.removeMenu(); } }; ContextMenu.prototype.isMenuEnabledByOtherHotInstance = function () { var hotContainers = $('.handsontable'); var menuEnabled = false; for(var i = 0, len = hotContainers.length; i < len; i++){ var instance = $(hotContainers[i]).handsontable('getInstance'); if(instance && instance.getSettings().contextMenu){ menuEnabled = true; break; } } return menuEnabled; }; ContextMenu.prototype.removeMenu = function () { if(this.menu.parentNode){ this.menu.parentNode.removeChild(this.menu); } } ContextMenu.prototype.filterItems = function(itemsToLeave){ this.itemsFilter = itemsToLeave; }; ContextMenu.SEPARATOR = "---------"; function init(){ var instance = this; var contextMenuSetting = instance.getSettings().contextMenu; var customOptions = Handsontable.helper.isObject(contextMenuSetting) ? contextMenuSetting : {}; if(contextMenuSetting){ if(!instance.contextMenu){ instance.contextMenu = new ContextMenu(instance, customOptions); } instance.contextMenu.enable(); if(Handsontable.helper.isArray(contextMenuSetting)){ instance.contextMenu.filterItems(contextMenuSetting); } } else if(instance.contextMenu){ instance.contextMenu.destroy(); delete instance.contextMenu; } } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); Handsontable.ContextMenu = ContextMenu; })(Handsontable); /** * This plugin adds support for legacy features, deprecated APIs, etc. */ /** * Support for old autocomplete syntax * For old syntax, see: https://github.com/warpech/jquery-handsontable/blob/8c9e701d090ea4620fe08b6a1a048672fadf6c7e/README.md#defining-autocomplete */ Handsontable.PluginHooks.add('beforeGetCellMeta', function (row, col, cellProperties) { //isWritable - deprecated since 0.8.0 cellProperties.isWritable = !cellProperties.readOnly; //autocomplete - deprecated since 0.7.1 (see CHANGELOG.md) if (cellProperties.autoComplete) { throw new Error("Support for legacy autocomplete syntax was removed in Handsontable 0.10.0. Please remove the property named 'autoComplete' from your config. For replacement instructions, see wiki page https://github.com/warpech/jquery-handsontable/wiki/Migration-guide-to-0.10.x"); } }); function HandsontableManualColumnMove() { var pressed , startCol , endCol , startX , startOffset; var ghost = document.createElement('DIV') , ghostStyle = ghost.style; ghost.className = 'ghost'; ghostStyle.position = 'absolute'; ghostStyle.top = '25px'; ghostStyle.left = 0; ghostStyle.width = '10px'; ghostStyle.height = '10px'; ghostStyle.backgroundColor = '#CCC'; ghostStyle.opacity = 0.7; var saveManualColumnPositions = function () { var instance = this; instance.PluginHooks.run('persistentStateSave', 'manualColumnPositions', instance.manualColumnPositions); }; var loadManualColumnPositions = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'manualColumnPositions', storedState); return storedState.value; }; var bindMoveColEvents = function () { var instance = this; instance.rootElement.on('mousemove.manualColumnMove', function (e) { if (pressed) { ghostStyle.left = startOffset + e.pageX - startX + 6 + 'px'; if (ghostStyle.display === 'none') { ghostStyle.display = 'block'; } } }); instance.rootElement.on('mouseup.manualColumnMove', function () { if (pressed) { if (startCol < endCol) { endCol--; } if (instance.getSettings().rowHeaders) { startCol--; endCol--; } instance.manualColumnPositions.splice(endCol, 0, instance.manualColumnPositions.splice(startCol, 1)[0]); $('.manualColumnMover.active').removeClass('active'); pressed = false; instance.forceFullRender = true; instance.view.render(); //updates all ghostStyle.display = 'none'; saveManualColumnPositions.call(instance); instance.PluginHooks.run('afterColumnMove', startCol, endCol); } }); instance.rootElement.on('mousedown.manualColumnMove', '.manualColumnMover', function (e) { var mover = e.currentTarget; var TH = instance.view.wt.wtDom.closest(mover, 'TH'); startCol = instance.view.wt.wtDom.index(TH) + instance.colOffset(); endCol = startCol; pressed = true; startX = e.pageX; var TABLE = instance.$table[0]; TABLE.parentNode.appendChild(ghost); ghostStyle.width = instance.view.wt.wtDom.outerWidth(TH) + 'px'; ghostStyle.height = instance.view.wt.wtDom.outerHeight(TABLE) + 'px'; startOffset = parseInt(instance.view.wt.wtDom.offset(TH).left - instance.view.wt.wtDom.offset(TABLE).left, 10); ghostStyle.left = startOffset + 6 + 'px'; }); instance.rootElement.on('mouseenter.manualColumnMove', 'td, th', function () { if (pressed) { var active = instance.view.THEAD.querySelector('.manualColumnMover.active'); if (active) { instance.view.wt.wtDom.removeClass(active, 'active'); } endCol = instance.view.wt.wtDom.index(this) + instance.colOffset(); var THs = instance.view.THEAD.querySelectorAll('th'); var mover = THs[endCol].querySelector('.manualColumnMover'); instance.view.wt.wtDom.addClass(mover, 'active'); } }); instance.addHook('afterDestroy', unbindMoveColEvents); }; var unbindMoveColEvents = function(){ var instance = this; instance.rootElement.off('mouseup.manualColumnMove'); instance.rootElement.off('mousemove.manualColumnMove'); instance.rootElement.off('mousedown.manualColumnMove'); instance.rootElement.off('mouseenter.manualColumnMove'); }; this.beforeInit = function () { this.manualColumnPositions = []; }; this.init = function (source) { var instance = this; var manualColMoveEnabled = !!(this.getSettings().manualColumnMove); if (manualColMoveEnabled) { var initialManualColumnPositions = this.getSettings().manualColumnMove; var loadedManualColumnPositions = loadManualColumnPositions.call(instance); if (typeof loadedManualColumnPositions != 'undefined') { this.manualColumnPositions = loadedManualColumnPositions; } else if (initialManualColumnPositions instanceof Array) { this.manualColumnPositions = initialManualColumnPositions; } else { this.manualColumnPositions = []; } instance.forceFullRender = true; if (source == 'afterInit') { bindMoveColEvents.call(this); if (this.manualColumnPositions.length > 0) { this.forceFullRender = true; this.render(); } } } else { unbindMoveColEvents.call(this); this.manualColumnPositions = []; } }; this.modifyCol = function (col) { //TODO test performance: http://jsperf.com/object-wrapper-vs-primitive/2 if (this.getSettings().manualColumnMove) { if (typeof this.manualColumnPositions[col] === 'undefined') { this.manualColumnPositions[col] = col; } return this.manualColumnPositions[col]; } return col; }; this.getColHeader = function (col, TH) { if (this.getSettings().manualColumnMove) { var DIV = document.createElement('DIV'); DIV.className = 'manualColumnMover'; TH.firstChild.appendChild(DIV); } }; } var htManualColumnMove = new HandsontableManualColumnMove(); Handsontable.PluginHooks.add('beforeInit', htManualColumnMove.beforeInit); Handsontable.PluginHooks.add('afterInit', function () { htManualColumnMove.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htManualColumnMove.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('afterGetColHeader', htManualColumnMove.getColHeader); Handsontable.PluginHooks.add('modifyCol', htManualColumnMove.modifyCol); function HandsontableManualColumnResize() { var pressed , currentTH , currentCol , currentWidth , instance , newSize , startX , startWidth , startOffset , resizer = document.createElement('DIV') , handle = document.createElement('DIV') , line = document.createElement('DIV') , lineStyle = line.style; resizer.className = 'manualColumnResizer'; handle.className = 'manualColumnResizerHandle'; resizer.appendChild(handle); line.className = 'manualColumnResizerLine'; resizer.appendChild(line); var $document = $(document); $document.mousemove(function (e) { if (pressed) { currentWidth = startWidth + (e.pageX - startX); newSize = setManualSize(currentCol, currentWidth); //save col width resizer.style.left = startOffset + currentWidth + 'px'; } }); $document.mouseup(function () { if (pressed) { instance.view.wt.wtDom.removeClass(resizer, 'active'); pressed = false; if(newSize != startWidth){ instance.forceFullRender = true; instance.view.render(); //updates all saveManualColumnWidths.call(instance); instance.PluginHooks.run('afterColumnResize', currentCol, newSize); } refreshResizerPosition.call(instance, currentTH); } }); var saveManualColumnWidths = function () { var instance = this; instance.PluginHooks.run('persistentStateSave', 'manualColumnWidths', instance.manualColumnWidths); }; var loadManualColumnWidths = function () { var instance = this; var storedState = {}; instance.PluginHooks.run('persistentStateLoad', 'manualColumnWidths', storedState); return storedState.value; }; function refreshResizerPosition(TH) { instance = this; currentTH = TH; var col = this.view.wt.wtTable.getCoords(TH)[1]; //getCoords returns array [row, col] if (col >= 0) { //if not row header currentCol = col; var rootOffset = this.view.wt.wtDom.offset(this.rootElement[0]).left; var thOffset = this.view.wt.wtDom.offset(TH).left; startOffset = (thOffset - rootOffset) - 6; resizer.style.left = startOffset + parseInt(this.view.wt.wtDom.outerWidth(TH), 10) + 'px'; this.rootElement[0].appendChild(resizer); } } function refreshLinePosition() { var instance = this; startWidth = parseInt(this.view.wt.wtDom.outerWidth(currentTH), 10); instance.view.wt.wtDom.addClass(resizer, 'active'); lineStyle.height = instance.view.wt.wtDom.outerHeight(instance.$table[0]) + 'px'; pressed = instance; } var bindManualColumnWidthEvents = function () { var instance = this; var dblclick = 0; var autoresizeTimeout = null; this.rootElement.on('mouseenter.handsontable', 'th', function (e) { if (!pressed) { refreshResizerPosition.call(instance, e.currentTarget); } }); this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function () { if (autoresizeTimeout == null) { autoresizeTimeout = setTimeout(function () { if (dblclick >= 2) { newSize = instance.determineColumnWidth.call(instance, currentCol); setManualSize(currentCol, newSize); instance.forceFullRender = true; instance.view.render(); //updates all instance.PluginHooks.run('afterColumnResize', currentCol, newSize); } dblclick = 0; autoresizeTimeout = null; }, 500); } dblclick++; }); this.rootElement.on('mousedown.handsontable', '.manualColumnResizer', function (e) { startX = e.pageX; refreshLinePosition.call(instance); newSize = startWidth; }); }; this.beforeInit = function () { this.manualColumnWidths = []; }; this.init = function (source) { var instance = this; var manualColumnWidthEnabled = !!(this.getSettings().manualColumnResize); if (manualColumnWidthEnabled) { var initialColumnWidths = this.getSettings().manualColumnResize; var loadedManualColumnWidths = loadManualColumnWidths.call(instance); if (typeof loadedManualColumnWidths != 'undefined') { this.manualColumnWidths = loadedManualColumnWidths; } else if (initialColumnWidths instanceof Array) { this.manualColumnWidths = initialColumnWidths; } else { this.manualColumnWidths = []; } if (source == 'afterInit') { bindManualColumnWidthEvents.call(this); instance.forceFullRender = true; instance.render(); } } }; var setManualSize = function (col, width) { width = Math.max(width, 20); /** * We need to run col through modifyCol hook, in case the order of displayed columns is different than the order * in data source. For instance, this order can be modified by manualColumnMove plugin. */ col = instance.PluginHooks.execute('modifyCol', col); instance.manualColumnWidths[col] = width; return width; }; this.getColWidth = function (col, response) { if (this.getSettings().manualColumnResize && this.manualColumnWidths[col]) { response.width = this.manualColumnWidths[col]; } }; } var htManualColumnResize = new HandsontableManualColumnResize(); Handsontable.PluginHooks.add('beforeInit', htManualColumnResize.beforeInit); Handsontable.PluginHooks.add('afterInit', function () { htManualColumnResize.init.call(this, 'afterInit') }); Handsontable.PluginHooks.add('afterUpdateSettings', function () { htManualColumnResize.init.call(this, 'afterUpdateSettings') }); Handsontable.PluginHooks.add('afterGetColWidth', htManualColumnResize.getColWidth); (function HandsontableObserveChanges() { Handsontable.PluginHooks.add('afterLoadData', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); function init() { var instance = this; var pluginEnabled = instance.getSettings().observeChanges; if (pluginEnabled) { if(instance.observer) { destroy.call(instance); //destroy observer for old data object } createObserver.call(instance); bindEvents.call(instance); } else if (!pluginEnabled){ destroy.call(instance); } } function createObserver(){ var instance = this; instance.observeChangesActive = true; instance.pauseObservingChanges = function(){ instance.observeChangesActive = false; }; instance.resumeObservingChanges = function(){ instance.observeChangesActive = true; }; instance.observedData = instance.getData(); instance.observer = jsonpatch.observe(instance.observedData, function (patches) { if(instance.observeChangesActive){ runHookForOperation.call(instance, patches); instance.render(); } instance.runHooks('afterChangesObserved'); }); } function runHookForOperation(rawPatches){ var instance = this; var patches = cleanPatches(rawPatches); for(var i = 0, len = patches.length; i < len; i++){ var patch = patches[i]; var parsedPath = parsePath(patch.path); switch(patch.op){ case 'add': if(isNaN(parsedPath.col)){ instance.runHooks('afterCreateRow', parsedPath.row); } else { instance.runHooks('afterCreateCol', parsedPath.col); } break; case 'remove': if(isNaN(parsedPath.col)){ instance.runHooks('afterRemoveRow', parsedPath.row, 1); } else { instance.runHooks('afterRemoveCol', parsedPath.col, 1); } break; case 'replace': instance.runHooks('afterChange', [parsedPath.row, parsedPath.col, null, patch.value], 'external'); break; } } function cleanPatches(rawPatches){ var patches; patches = removeLengthRelatedPatches(rawPatches); patches = removeMultipleAddOrRemoveColPatches(patches); return patches; } /** * Removing or adding column will produce one patch for each table row. * This function leaves only one patch for each column add/remove operation */ function removeMultipleAddOrRemoveColPatches(rawPatches){ var newOrRemovedColumns = []; return rawPatches.filter(function(patch){ var parsedPath = parsePath(patch.path); if(['add', 'remove'].indexOf(patch.op) != -1 && !isNaN(parsedPath.col)){ if(newOrRemovedColumns.indexOf(parsedPath.col) != -1){ return false; } else { newOrRemovedColumns.push(parsedPath.col); } } return true; }); } /** * If observeChanges uses native Object.observe method, then it produces patches for length property. * This function removes them. */ function removeLengthRelatedPatches(rawPatches){ return rawPatches.filter(function(patch){ return !/[/]length/ig.test(patch.path); }) } function parsePath(path){ var match = path.match(/^\/(\d+)\/?(.*)?$/); return { row: parseInt(match[1], 10), col: /^\d*$/.test(match[2]) ? parseInt(match[2], 10) : match[2] } } } function destroy(){ var instance = this; if (instance.observer){ destroyObserver.call(instance); unbindEvents.call(instance); } } function destroyObserver(){ var instance = this; jsonpatch.unobserve(instance.observedData, instance.observer); delete instance.observeChangesActive; delete instance.pauseObservingChanges; delete instance.resumeObservingChanges; } function bindEvents(){ var instance = this; instance.addHook('afterDestroy', destroy); instance.addHook('afterCreateRow', afterTableAlter); instance.addHook('afterRemoveRow', afterTableAlter); instance.addHook('afterCreateCol', afterTableAlter); instance.addHook('afterRemoveCol', afterTableAlter); instance.addHook('afterChange', function(changes, source){ if(source != 'loadData'){ afterTableAlter.call(this); } }); } function unbindEvents(){ var instance = this; instance.removeHook('afterDestroy', destroy); instance.removeHook('afterCreateRow', afterTableAlter); instance.removeHook('afterRemoveRow', afterTableAlter); instance.removeHook('afterCreateCol', afterTableAlter); instance.removeHook('afterRemoveCol', afterTableAlter); instance.removeHook('afterChange', afterTableAlter); } function afterTableAlter(){ var instance = this; instance.pauseObservingChanges(); instance.addHookOnce('afterChangesObserved', function(){ instance.resumeObservingChanges(); }); } })(); /* * * Plugin enables saving table state * * */ function Storage(prefix) { var savedKeys; var saveSavedKeys = function () { window.localStorage[prefix + '__' + 'persistentStateKeys'] = JSON.stringify(savedKeys); }; var loadSavedKeys = function () { var keysJSON = window.localStorage[prefix + '__' + 'persistentStateKeys']; var keys = typeof keysJSON == 'string' ? JSON.parse(keysJSON) : void 0; savedKeys = keys ? keys : []; }; var clearSavedKeys = function () { savedKeys = []; saveSavedKeys(); }; loadSavedKeys(); this.saveValue = function (key, value) { window.localStorage[prefix + '_' + key] = JSON.stringify(value); if (savedKeys.indexOf(key) == -1) { savedKeys.push(key); saveSavedKeys(); } }; this.loadValue = function (key, defaultValue) { key = typeof key != 'undefined' ? key : defaultValue; var value = window.localStorage[prefix + '_' + key]; return typeof value == "undefined" ? void 0 : JSON.parse(value); }; this.reset = function (key) { window.localStorage.removeItem(prefix + '_' + key); }; this.resetAll = function () { for (var index = 0; index < savedKeys.length; index++) { window.localStorage.removeItem(prefix + '_' + savedKeys[index]); } clearSavedKeys(); }; } (function (StorageClass) { function HandsontablePersistentState() { var plugin = this; this.init = function () { var instance = this, pluginSettings = instance.getSettings()['persistentState']; plugin.enabled = !!(pluginSettings); if (!plugin.enabled) { removeHooks.call(instance); return; } if (!instance.storage) { instance.storage = new StorageClass(instance.rootElement[0].id); } instance.resetState = plugin.resetValue; addHooks.call(instance); }; this.saveValue = function (key, value) { var instance = this; instance.storage.saveValue(key, value); }; this.loadValue = function (key, saveTo) { var instance = this; saveTo.value = instance.storage.loadValue(key); }; this.resetValue = function (key) { var instance = this; if (typeof key != 'undefined') { instance.storage.reset(key); } else { instance.storage.resetAll(); } }; var hooks = { 'persistentStateSave': plugin.saveValue, 'persistentStateLoad': plugin.loadValue, 'persistentStateReset': plugin.resetValue }; function addHooks() { var instance = this; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName) && !hookExists.call(instance, hookName)) { instance.PluginHooks.add(hookName, hooks[hookName]); } } } function removeHooks() { var instance = this; for (var hookName in hooks) { if (hooks.hasOwnProperty(hookName) && hookExists.call(instance, hookName)) { instance.PluginHooks.remove(hookName, hooks[hookName]); } } } function hookExists(hookName) { var instance = this; return instance.PluginHooks.hooks.hasOwnProperty(hookName); } } var htPersistentState = new HandsontablePersistentState(); Handsontable.PluginHooks.add('beforeInit', htPersistentState.init); Handsontable.PluginHooks.add('afterUpdateSettings', htPersistentState.init); })(Storage); /** * Handsontable UndoRedo class */ (function(Handsontable){ Handsontable.UndoRedo = function (instance) { var plugin = this; this.instance = instance; this.doneActions = []; this.undoneActions = []; this.ignoreNewActions = false; instance.addHook("afterChange", function (changes, origin) { if(changes){ var action = new Handsontable.UndoRedo.ChangeAction(changes); plugin.done(action); } }); instance.addHook("afterCreateRow", function (index, amount) { var action = new Handsontable.UndoRedo.CreateRowAction(index, amount); plugin.done(action); }); instance.addHook("beforeRemoveRow", function (index, amount) { var originalData = plugin.instance.getData(); index = ( originalData.length + index ) % originalData.length; var removedData = originalData.slice(index, index + amount); var action = new Handsontable.UndoRedo.RemoveRowAction(index, removedData); plugin.done(action); }); instance.addHook("afterCreateCol", function (index, amount) { var action = new Handsontable.UndoRedo.CreateColumnAction(index, amount); plugin.done(action); }); instance.addHook("beforeRemoveCol", function (index, amount) { var originalData = plugin.instance.getData(); index = ( plugin.instance.countCols() + index ) % plugin.instance.countCols(); var removedData = []; for (var i = 0, len = originalData.length; i < len; i++) { removedData[i] = originalData[i].slice(index, index + amount); } var headers; if(Handsontable.helper.isArray(instance.getSettings().colHeaders)){ headers = instance.getSettings().colHeaders.slice(index, index + removedData.length); } var action = new Handsontable.UndoRedo.RemoveColumnAction(index, removedData, headers); plugin.done(action); }); }; Handsontable.UndoRedo.prototype.done = function (action) { if (!this.ignoreNewActions) { this.doneActions.push(action); this.undoneActions.length = 0; } }; /** * Undo operation from current revision */ Handsontable.UndoRedo.prototype.undo = function () { if (this.isUndoAvailable()) { var action = this.doneActions.pop(); this.ignoreNewActions = true; action.undo(this.instance); this.ignoreNewActions = false; this.undoneActions.push(action); } }; /** * Redo operation from current revision */ Handsontable.UndoRedo.prototype.redo = function () { if (this.isRedoAvailable()) { var action = this.undoneActions.pop(); this.ignoreNewActions = true; action.redo(this.instance); this.ignoreNewActions = true; this.doneActions.push(action); } }; /** * Returns true if undo point is available * @return {Boolean} */ Handsontable.UndoRedo.prototype.isUndoAvailable = function () { return this.doneActions.length > 0; }; /** * Returns true if redo point is available * @return {Boolean} */ Handsontable.UndoRedo.prototype.isRedoAvailable = function () { return this.undoneActions.length > 0; }; /** * Clears undo history */ Handsontable.UndoRedo.prototype.clear = function () { this.doneActions.length = 0; this.undoneActions.length = 0; }; Handsontable.UndoRedo.Action = function () { }; Handsontable.UndoRedo.Action.prototype.undo = function () { }; Handsontable.UndoRedo.Action.prototype.redo = function () { }; Handsontable.UndoRedo.ChangeAction = function (changes) { this.changes = changes; }; Handsontable.helper.inherit(Handsontable.UndoRedo.ChangeAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.ChangeAction.prototype.undo = function (instance) { var data = $.extend(true, [], this.changes); for (var i = 0, len = data.length; i < len; i++) { data[i].splice(3, 1); } instance.setDataAtRowProp(data, null, null, 'undo'); }; Handsontable.UndoRedo.ChangeAction.prototype.redo = function (instance) { var data = $.extend(true, [], this.changes); for (var i = 0, len = data.length; i < len; i++) { data[i].splice(2, 1); } instance.setDataAtRowProp(data, null, null, 'redo'); }; Handsontable.UndoRedo.CreateRowAction = function (index, amount) { this.index = index; this.amount = amount; }; Handsontable.helper.inherit(Handsontable.UndoRedo.CreateRowAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.CreateRowAction.prototype.undo = function (instance) { instance.alter('remove_row', this.index, this.amount); }; Handsontable.UndoRedo.CreateRowAction.prototype.redo = function (instance) { instance.alter('insert_row', this.index + 1, this.amount); }; Handsontable.UndoRedo.RemoveRowAction = function (index, data) { this.index = index; this.data = data; }; Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveRowAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.RemoveRowAction.prototype.undo = function (instance) { var spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.data); Array.prototype.splice.apply(instance.getData(), spliceArgs); instance.render(); }; Handsontable.UndoRedo.RemoveRowAction.prototype.redo = function (instance) { instance.alter('remove_row', this.index, this.data.length); }; Handsontable.UndoRedo.CreateColumnAction = function (index, amount) { this.index = index; this.amount = amount; }; Handsontable.helper.inherit(Handsontable.UndoRedo.CreateColumnAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.CreateColumnAction.prototype.undo = function (instance) { instance.alter('remove_col', this.index, this.amount); }; Handsontable.UndoRedo.CreateColumnAction.prototype.redo = function (instance) { instance.alter('insert_col', this.index + 1, this.amount); }; Handsontable.UndoRedo.RemoveColumnAction = function (index, data, headers) { this.index = index; this.data = data; this.amount = this.data[0].length; this.headers = headers; }; Handsontable.helper.inherit(Handsontable.UndoRedo.RemoveColumnAction, Handsontable.UndoRedo.Action); Handsontable.UndoRedo.RemoveColumnAction.prototype.undo = function (instance) { var row, spliceArgs; for (var i = 0, len = instance.getData().length; i < len; i++) { row = instance.getDataAtRow(i); spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.data[i]); Array.prototype.splice.apply(row, spliceArgs); } if(typeof this.headers != 'undefined'){ spliceArgs = [this.index, 0]; Array.prototype.push.apply(spliceArgs, this.headers); Array.prototype.splice.apply(instance.getSettings().colHeaders, spliceArgs); } instance.render(); }; Handsontable.UndoRedo.RemoveColumnAction.prototype.redo = function (instance) { instance.alter('remove_col', this.index, this.amount); }; })(Handsontable); (function(Handsontable){ function init(){ var instance = this; var pluginEnabled = typeof instance.getSettings().undo == 'undefined' || instance.getSettings().undo; if(pluginEnabled){ if(!instance.undoRedo){ instance.undoRedo = new Handsontable.UndoRedo(instance); exposeUndoRedoMethods(instance); instance.addHook('beforeKeyDown', onBeforeKeyDown); instance.addHook('afterChange', onAfterChange); } } else { if(instance.undoRedo){ delete instance.undoRedo; removeExposedUndoRedoMethods(instance); instance.removeHook('beforeKeyDown', onBeforeKeyDown); instance.removeHook('afterChange', onAfterChange); } } } function onBeforeKeyDown(event){ var instance = this; var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; if(ctrlDown){ if (event.keyCode === 89 || (event.shiftKey && event.keyCode === 90)) { //CTRL + Y or CTRL + SHIFT + Z instance.undoRedo.redo(); event.stopImmediatePropagation(); } else if (event.keyCode === 90) { //CTRL + Z instance.undoRedo.undo(); event.stopImmediatePropagation(); } } } function onAfterChange(changes, source){ var instance = this; if (source == 'loadData'){ return instance.undoRedo.clear(); } } function exposeUndoRedoMethods(instance){ instance.undo = function(){ return instance.undoRedo.undo(); }; instance.redo = function(){ return instance.undoRedo.redo(); }; instance.isUndoAvailable = function(){ return instance.undoRedo.isUndoAvailable(); }; instance.isRedoAvailable = function(){ return instance.undoRedo.isRedoAvailable(); }; instance.clearUndo = function(){ return instance.undoRedo.clear(); }; } function removeExposedUndoRedoMethods(instance){ delete instance.undo; delete instance.redo; delete instance.isUndoAvailable; delete instance.isRedoAvailable; delete instance.clearUndo; } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); })(Handsontable); /** * Plugin used to scroll Handsontable by selecting a cell and dragging outside of visible viewport * @constructor */ function DragToScroll() { this.boundaries = null; this.callback = null; } /** * @param boundaries {Object} compatible with getBoundingClientRect */ DragToScroll.prototype.setBoundaries = function (boundaries) { this.boundaries = boundaries; }; /** * @param callback {Function} */ DragToScroll.prototype.setCallback = function (callback) { this.callback = callback; }; /** * Check if mouse position (x, y) is outside of the viewport * @param x * @param y */ DragToScroll.prototype.check = function (x, y) { var diffX = 0; var diffY = 0; if (y < this.boundaries.top) { //y is less than top diffY = y - this.boundaries.top; } else if (y > this.boundaries.bottom) { //y is more than bottom diffY = y - this.boundaries.bottom; } if (x < this.boundaries.left) { //x is less than left diffX = x - this.boundaries.left; } else if (x > this.boundaries.right) { //x is more than right diffX = x - this.boundaries.right; } this.callback(diffX, diffY); }; var listening = false; var dragToScroll; var instance; if (typeof Handsontable !== 'undefined') { var setupListening = function (instance) { var scrollHandler = instance.view.wt.wtScrollbars.vertical.scrollHandler; //native scroll dragToScroll = new DragToScroll(); if (scrollHandler === window) { //not much we can do currently return; } else if (scrollHandler) { dragToScroll.setBoundaries(scrollHandler.getBoundingClientRect()); } else { dragToScroll.setBoundaries(instance.$table[0].getBoundingClientRect()); } dragToScroll.setCallback(function (scrollX, scrollY) { if (scrollX < 0) { if (scrollHandler) { scrollHandler.scrollLeft -= 50; } else { instance.view.wt.scrollHorizontal(-1).draw(); } } else if (scrollX > 0) { if (scrollHandler) { scrollHandler.scrollLeft += 50; } else { instance.view.wt.scrollHorizontal(1).draw(); } } if (scrollY < 0) { if (scrollHandler) { scrollHandler.scrollTop -= 20; } else { instance.view.wt.scrollVertical(-1).draw(); } } else if (scrollY > 0) { if (scrollHandler) { scrollHandler.scrollTop += 20; } else { instance.view.wt.scrollVertical(1).draw(); } } }); listening = true; }; Handsontable.PluginHooks.add('afterInit', function () { $(document).on('mouseup.' + this.guid, function () { listening = false; }); $(document).on('mousemove.' + this.guid, function (event) { if (listening) { dragToScroll.check(event.clientX, event.clientY); } }); }); Handsontable.PluginHooks.add('destroy', function () { $(document).off('.' + this.guid); }); Handsontable.PluginHooks.add('afterOnCellMouseDown', function () { setupListening(this); }); Handsontable.PluginHooks.add('afterOnCellCornerMouseDown', function () { setupListening(this); }); } (function (Handsontable, CopyPaste, SheetClip) { function CopyPastePlugin(instance) { this.copyPasteInstance = CopyPaste.getInstance(); this.copyPasteInstance.onCut(onCut); this.copyPasteInstance.onPaste(onPaste); var plugin = this; instance.addHook('beforeKeyDown', onBeforeKeyDown); function onCut() { if (!instance.isListening()) { return; } instance.selection.empty(); } function onPaste(str) { if (!instance.isListening() || !instance.selection.isSelected()) { return; } var input = str.replace(/^[\r\n]*/g, '').replace(/[\r\n]*$/g, '') //remove newline from the start and the end of the input , inputArray = SheetClip.parse(input) , selected = instance.getSelected() , coords = instance.getCornerCoords([{row: selected[0], col: selected[1]}, {row: selected[2], col: selected[3]}]) , areaStart = coords.TL , areaEnd = { row: Math.max(coords.BR.row, inputArray.length - 1 + coords.TL.row), col: Math.max(coords.BR.col, inputArray[0].length - 1 + coords.TL.col) }; instance.PluginHooks.once('afterChange', function (changes, source) { if (changes && changes.length) { this.selectCell(areaStart.row, areaStart.col, areaEnd.row, areaEnd.col); } }); instance.populateFromArray(areaStart.row, areaStart.col, inputArray, areaEnd.row, areaEnd.col, 'paste', instance.getSettings().pasteMode); }; function onBeforeKeyDown (event) { if (Handsontable.helper.isCtrlKey(event.keyCode) && instance.getSelected()) { //when CTRL is pressed, prepare selectable text in textarea //http://stackoverflow.com/questions/3902635/how-does-one-capture-a-macs-command-key-via-javascript plugin.setCopyableText(); event.stopImmediatePropagation(); return; } var ctrlDown = (event.ctrlKey || event.metaKey) && !event.altKey; //catch CTRL but not right ALT (which in some systems triggers ALT+CTRL) if (event.keyCode == Handsontable.helper.keyCode.A && ctrlDown) { setTimeout(Handsontable.helper.proxy(plugin.setCopyableText, plugin)); } } this.destroy = function () { this.copyPasteInstance.removeCallback(onCut); this.copyPasteInstance.removeCallback(onPaste); this.copyPasteInstance.destroy(); instance.removeHook('beforeKeyDown', onBeforeKeyDown); }; instance.addHook('afterDestroy', Handsontable.helper.proxy(this.destroy, this)); this.triggerPaste = Handsontable.helper.proxy(this.copyPasteInstance.triggerPaste, this.copyPasteInstance); this.triggerCut = Handsontable.helper.proxy(this.copyPasteInstance.triggerCut, this.copyPasteInstance); /** * Prepares copyable text in the invisible textarea */ this.setCopyableText = function () { var selection = instance.getSelected(); var settings = instance.getSettings(); var copyRowsLimit = settings.copyRowsLimit; var copyColsLimit = settings.copyColsLimit; var startRow = Math.min(selection[0], selection[2]); var startCol = Math.min(selection[1], selection[3]); var endRow = Math.max(selection[0], selection[2]); var endCol = Math.max(selection[1], selection[3]); var finalEndRow = Math.min(endRow, startRow + copyRowsLimit - 1); var finalEndCol = Math.min(endCol, startCol + copyColsLimit - 1); instance.copyPaste.copyPasteInstance.copyable(instance.getCopyableData(startRow, startCol, finalEndRow, finalEndCol)); if (endRow !== finalEndRow || endCol !== finalEndCol) { instance.PluginHooks.run("afterCopyLimit", endRow - startRow + 1, endCol - startCol + 1, copyRowsLimit, copyColsLimit); } }; } function init() { var instance = this; var pluginEnabled = instance.getSettings().copyPaste !== false; if(pluginEnabled && !instance.copyPaste){ instance.copyPaste = new CopyPastePlugin(instance); } else if (!pluginEnabled && instance.copyPaste) { instance.copyPaste.destroy(); delete instance.copyPaste; } } Handsontable.PluginHooks.add('afterInit', init); Handsontable.PluginHooks.add('afterUpdateSettings', init); })(Handsontable, CopyPaste, SheetClip); /** * Creates an overlay over the original Walkontable instance. The overlay renders the clone of the original Walkontable * and (optionally) implements behavior needed for native horizontal and vertical scrolling */ function WalkontableOverlay() { this.maxOuts = 10; //max outs in one direction (before and after table) } /* Possible optimizations: [x] don't rerender if scroll delta is smaller than the fragment outside of the viewport [ ] move .style.top change before .draw() [ ] put .draw() in requestAnimationFrame [ ] don't rerender rows that remain visible after the scroll */ WalkontableOverlay.prototype.init = function () { this.TABLE = this.instance.wtTable.TABLE; this.fixed = this.instance.wtTable.hider; this.fixedContainer = this.instance.wtTable.holder; this.fixed.style.position = 'absolute'; this.fixed.style.left = '0'; this.scrollHandler = this.getScrollableElement(this.TABLE); this.$scrollHandler = $(this.scrollHandler); //in future remove jQuery from here }; WalkontableOverlay.prototype.makeClone = function (direction) { var clone = document.createElement('DIV'); clone.className = 'ht_clone_' + direction + ' handsontable'; clone.style.position = 'fixed'; clone.style.overflow = 'hidden'; var table2 = document.createElement('TABLE'); table2.className = this.instance.wtTable.TABLE.className; clone.appendChild(table2); this.instance.wtTable.holder.parentNode.appendChild(clone); return new Walkontable({ cloneSource: this.instance, cloneOverlay: this, table: table2 }); }; WalkontableOverlay.prototype.getScrollableElement = function (TABLE) { var el = TABLE.parentNode; while (el && el.style) { if (el.style.overflow !== 'visible' && el.style.overflow !== '') { return el; } if (this instanceof WalkontableHorizontalScrollbarNative && el.style.overflowX !== 'visible' && el.style.overflowX !== '') { return el; } el = el.parentNode; } return window; }; WalkontableOverlay.prototype.prepare = function () { }; WalkontableOverlay.prototype.onScroll = function (forcePosition) { this.windowScrollPosition = this.getScrollPosition(); this.readSettings(); //read window scroll position if (forcePosition) { this.windowScrollPosition = forcePosition; } this.resetFixedPosition(); //may be redundant }; WalkontableOverlay.prototype.availableSize = function () { var availableSize; if (this.windowScrollPosition > this.tableParentOffset /*&& last > -1*/) { //last -1 means that viewport is scrolled behind the table if (this.instance.wtTable.getLastVisibleRow() === this.total - 1) { availableSize = this.instance.wtDom.outerHeight(this.TABLE); } else { availableSize = this.windowSize; } } else { availableSize = this.windowSize - (this.tableParentOffset); } return availableSize; }; WalkontableOverlay.prototype.refresh = function (selectionsOnly) { var last = this.getLastCell(); this.measureBefore = this.sumCellSizes(0, this.offset); if (last === -1) { //last -1 means that viewport is scrolled behind the table this.measureAfter = 0; } else { this.measureAfter = this.sumCellSizes(last, this.total - last); } this.applyToDOM(); this.clone && this.clone.draw(selectionsOnly); }; WalkontableOverlay.prototype.destroy = function () { this.$scrollHandler.off('.' + this.instance.guid); $(window).off('.' + this.instance.guid); $(document).off('.' + this.instance.guid); }; function WalkontableBorder(instance, settings) { var style; //reference to instance this.instance = instance; this.settings = settings; this.wtDom = this.instance.wtDom; this.main = document.createElement("div"); style = this.main.style; style.position = 'absolute'; style.top = 0; style.left = 0; // style.visibility = 'hidden'; for (var i = 0; i < 5; i++) { var DIV = document.createElement('DIV'); DIV.className = 'wtBorder ' + (settings.className || ''); style = DIV.style; style.backgroundColor = settings.border.color; style.height = settings.border.width + 'px'; style.width = settings.border.width + 'px'; this.main.appendChild(DIV); } this.top = this.main.childNodes[0]; this.left = this.main.childNodes[1]; this.bottom = this.main.childNodes[2]; this.right = this.main.childNodes[3]; /*$(this.top).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.left).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.bottom).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); }); $(this.right).on(sss, function(event) { event.preventDefault(); event.stopImmediatePropagation(); $(this).hide(); });*/ this.topStyle = this.top.style; this.leftStyle = this.left.style; this.bottomStyle = this.bottom.style; this.rightStyle = this.right.style; this.corner = this.main.childNodes[4]; this.corner.className += ' corner'; this.cornerStyle = this.corner.style; this.cornerStyle.width = '5px'; this.cornerStyle.height = '5px'; this.cornerStyle.border = '2px solid #FFF'; this.disappear(); if (!instance.wtTable.bordersHolder) { instance.wtTable.bordersHolder = document.createElement('div'); instance.wtTable.bordersHolder.className = 'htBorders'; instance.wtTable.hider.appendChild(instance.wtTable.bordersHolder); } instance.wtTable.bordersHolder.appendChild(this.main); var down = false; var $body = $(document.body); $body.on('mousedown.walkontable.' + instance.guid, function () { down = true; }); $body.on('mouseup.walkontable.' + instance.guid, function () { down = false }); $(this.main.childNodes).on('mouseenter', function (event) { if (!down || !instance.getSetting('hideBorderOnMouseDownOver')) { return; } event.preventDefault(); event.stopImmediatePropagation(); var bounds = this.getBoundingClientRect(); var $this = $(this); $this.hide(); var isOutside = function (event) { if (event.clientY < Math.floor(bounds.top)) { return true; } if (event.clientY > Math.ceil(bounds.top + bounds.height)) { return true; } if (event.clientX < Math.floor(bounds.left)) { return true; } if (event.clientX > Math.ceil(bounds.left + bounds.width)) { return true; } }; $body.on('mousemove.border.' + instance.guid, function (event) { if (isOutside(event)) { $body.off('mousemove.border.' + instance.guid); $this.show(); } }); }); } /** * Show border around one or many cells * @param {Array} corners */ WalkontableBorder.prototype.appear = function (corners) { var isMultiple, fromTD, toTD, fromOffset, toOffset, containerOffset, top, minTop, left, minLeft, height, width; if (this.disabled) { return; } var instance = this.instance , fromRow , fromColumn , toRow , toColumn , hideTop = false , hideLeft = false , hideBottom = false , hideRight = false , i , ilen , s; if (!instance.wtTable.isRowInViewport(corners[0])) { hideTop = true; } if (!instance.wtTable.isRowInViewport(corners[2])) { hideBottom = true; } ilen = instance.wtTable.rowStrategy.countVisible(); for (i = 0; i < ilen; i++) { s = instance.wtTable.rowFilter.visibleToSource(i); if (s >= corners[0] && s <= corners[2]) { fromRow = s; break; } } for (i = ilen - 1; i >= 0; i--) { s = instance.wtTable.rowFilter.visibleToSource(i); if (s >= corners[0] && s <= corners[2]) { toRow = s; break; } } if (hideTop && hideBottom) { hideLeft = true; hideRight = true; } else { if (!instance.wtTable.isColumnInViewport(corners[1])) { hideLeft = true; } if (!instance.wtTable.isColumnInViewport(corners[3])) { hideRight = true; } ilen = instance.wtTable.columnStrategy.countVisible(); for (i = 0; i < ilen; i++) { s = instance.wtTable.columnFilter.visibleToSource(i); if (s >= corners[1] && s <= corners[3]) { fromColumn = s; break; } } for (i = ilen - 1; i >= 0; i--) { s = instance.wtTable.columnFilter.visibleToSource(i); if (s >= corners[1] && s <= corners[3]) { toColumn = s; break; } } } if (fromRow !== void 0 && fromColumn !== void 0) { isMultiple = (fromRow !== toRow || fromColumn !== toColumn); fromTD = instance.wtTable.getCell([fromRow, fromColumn]); toTD = isMultiple ? instance.wtTable.getCell([toRow, toColumn]) : fromTD; fromOffset = this.wtDom.offset(fromTD); toOffset = isMultiple ? this.wtDom.offset(toTD) : fromOffset; containerOffset = this.wtDom.offset(instance.wtTable.TABLE); minTop = fromOffset.top; height = toOffset.top + this.wtDom.outerHeight(toTD) - minTop; minLeft = fromOffset.left; width = toOffset.left + this.wtDom.outerWidth(toTD) - minLeft; top = minTop - containerOffset.top - 1; left = minLeft - containerOffset.left - 1; var style = this.wtDom.getComputedStyle(fromTD); if (parseInt(style['borderTopWidth'], 10) > 0) { top += 1; height = height > 0 ? height - 1 : 0; } if (parseInt(style['borderLeftWidth'], 10) > 0) { left += 1; width = width > 0 ? width - 1 : 0; } } else { this.disappear(); return; } if (hideTop) { this.topStyle.display = 'none'; } else { this.topStyle.top = top + 'px'; this.topStyle.left = left + 'px'; this.topStyle.width = width + 'px'; this.topStyle.display = 'block'; } if (hideLeft) { this.leftStyle.display = 'none'; } else { this.leftStyle.top = top + 'px'; this.leftStyle.left = left + 'px'; this.leftStyle.height = height + 'px'; this.leftStyle.display = 'block'; } var delta = Math.floor(this.settings.border.width / 2); if (hideBottom) { this.bottomStyle.display = 'none'; } else { this.bottomStyle.top = top + height - delta + 'px'; this.bottomStyle.left = left + 'px'; this.bottomStyle.width = width + 'px'; this.bottomStyle.display = 'block'; } if (hideRight) { this.rightStyle.display = 'none'; } else { this.rightStyle.top = top + 'px'; this.rightStyle.left = left + width - delta + 'px'; this.rightStyle.height = height + 1 + 'px'; this.rightStyle.display = 'block'; } if (hideBottom || hideRight || !this.hasSetting(this.settings.border.cornerVisible)) { this.cornerStyle.display = 'none'; } else { this.cornerStyle.top = top + height - 4 + 'px'; this.cornerStyle.left = left + width - 4 + 'px'; this.cornerStyle.display = 'block'; } }; /** * Hide border */ WalkontableBorder.prototype.disappear = function () { this.topStyle.display = 'none'; this.leftStyle.display = 'none'; this.bottomStyle.display = 'none'; this.rightStyle.display = 'none'; this.cornerStyle.display = 'none'; }; WalkontableBorder.prototype.hasSetting = function (setting) { if (typeof setting === 'function') { return setting(); } return !!setting; }; /** * WalkontableCellFilter * @constructor */ function WalkontableCellFilter() { this.offset = 0; this.total = 0; this.fixedCount = 0; } WalkontableCellFilter.prototype.source = function (n) { return n; }; WalkontableCellFilter.prototype.offsetted = function (n) { return n + this.offset; }; WalkontableCellFilter.prototype.unOffsetted = function (n) { return n - this.offset; }; WalkontableCellFilter.prototype.fixed = function (n) { if (n < this.fixedCount) { return n - this.offset; } else { return n; } }; WalkontableCellFilter.prototype.unFixed = function (n) { if (n < this.fixedCount) { return n + this.offset; } else { return n; } }; WalkontableCellFilter.prototype.visibleToSource = function (n) { return this.source(this.offsetted(this.fixed(n))); }; WalkontableCellFilter.prototype.sourceToVisible = function (n) { return this.source(this.unOffsetted(this.unFixed(n))); }; /** * WalkontableCellStrategy * @constructor */ function WalkontableCellStrategy(instance) { this.instance = instance; } WalkontableCellStrategy.prototype.getSize = function (index) { return this.cellSizes[index]; }; WalkontableCellStrategy.prototype.getContainerSize = function (proposedSize) { return typeof this.containerSizeFn === 'function' ? this.containerSizeFn(proposedSize) : this.containerSizeFn; }; WalkontableCellStrategy.prototype.countVisible = function () { return this.cellCount; }; WalkontableCellStrategy.prototype.isLastIncomplete = function () { if(this.instance.getSetting('nativeScrollbars')){ var nativeScrollbar = this.instance.cloneFrom ? this.instance.cloneFrom.wtScrollbars.vertical : this.instance.wtScrollbars.vertical; return this.remainingSize > nativeScrollbar.sumCellSizes(nativeScrollbar.offset, nativeScrollbar.offset + nativeScrollbar.curOuts + 1); } else { return this.remainingSize > 0; } }; /** * WalkontableClassNameList * @constructor */ function WalkontableClassNameCache() { this.cache = []; } WalkontableClassNameCache.prototype.add = function (r, c, cls) { if (!this.cache[r]) { this.cache[r] = []; } if (!this.cache[r][c]) { this.cache[r][c] = []; } this.cache[r][c][cls] = true; }; WalkontableClassNameCache.prototype.test = function (r, c, cls) { return (this.cache[r] && this.cache[r][c] && this.cache[r][c][cls]); }; /** * WalkontableColumnFilter * @constructor */ function WalkontableColumnFilter() { this.countTH = 0; } WalkontableColumnFilter.prototype = new WalkontableCellFilter(); WalkontableColumnFilter.prototype.readSettings = function (instance) { this.offset = instance.wtSettings.settings.offsetColumn; this.total = instance.getSetting('totalColumns'); this.fixedCount = instance.getSetting('fixedColumnsLeft'); this.countTH = instance.getSetting('rowHeaders').length; }; WalkontableColumnFilter.prototype.offsettedTH = function (n) { return n - this.countTH; }; WalkontableColumnFilter.prototype.unOffsettedTH = function (n) { return n + this.countTH; }; WalkontableColumnFilter.prototype.visibleRowHeadedColumnToSourceColumn = function (n) { return this.visibleToSource(this.offsettedTH(n)); }; WalkontableColumnFilter.prototype.sourceColumnToVisibleRowHeadedColumn = function (n) { return this.unOffsettedTH(this.sourceToVisible(n)); }; /** * WalkontableColumnStrategy * @param containerSizeFn * @param sizeAtIndex * @param strategy - all, last, none * @constructor */ function WalkontableColumnStrategy(instance, containerSizeFn, sizeAtIndex, strategy) { var size , i = 0; WalkontableCellStrategy.apply(this, arguments); this.containerSizeFn = containerSizeFn; this.cellSizesSum = 0; this.cellSizes = []; this.cellStretch = []; this.cellCount = 0; this.remainingSize = 0; this.strategy = strategy; //step 1 - determine cells that fit containerSize and cache their widths while (true) { size = sizeAtIndex(i); if (size === void 0) { break; //total columns exceeded } if (this.cellSizesSum >= this.getContainerSize(this.cellSizesSum + size)) { break; //total width exceeded } this.cellSizes.push(size); this.cellSizesSum += size; this.cellCount++; i++; } var containerSize = this.getContainerSize(this.cellSizesSum); this.remainingSize = this.cellSizesSum - containerSize; //negative value means the last cell is fully visible and there is some space left for stretching //positive value means the last cell is not fully visible } WalkontableColumnStrategy.prototype = new WalkontableCellStrategy(); WalkontableColumnStrategy.prototype.getSize = function (index) { return this.cellSizes[index] + (this.cellStretch[index] || 0); }; WalkontableColumnStrategy.prototype.stretch = function () { //step 2 - apply stretching strategy var containerSize = this.getContainerSize(this.cellSizesSum) , i = 0; this.remainingSize = this.cellSizesSum - containerSize; this.cellStretch.length = 0; //clear previous stretch if (this.strategy === 'all') { if (this.remainingSize < 0) { var ratio = containerSize / this.cellSizesSum; var newSize; while (i < this.cellCount - 1) { //"i < this.cellCount - 1" is needed because last cellSize is adjusted after the loop newSize = Math.floor(ratio * this.cellSizes[i]); this.remainingSize += newSize - this.cellSizes[i]; this.cellStretch[i] = newSize - this.cellSizes[i]; i++; } this.cellStretch[this.cellCount - 1] = -this.remainingSize; this.remainingSize = 0; } } else if (this.strategy === 'last') { if (this.remainingSize < 0 && containerSize !== Infinity) { //Infinity is with native scroll when the table is wider than the viewport (TODO: test) this.cellStretch[this.cellCount - 1] = -this.remainingSize; this.remainingSize = 0; } } }; function Walkontable(settings) { var that = this, originalHeaders = []; this.guid = 'wt_' + walkontableRandomString(); //this is the namespace for global events //bootstrap from settings this.wtDom = new WalkontableDom(); if (settings.cloneSource) { this.cloneSource = settings.cloneSource; this.cloneOverlay = settings.cloneOverlay; this.wtSettings = settings.cloneSource.wtSettings; this.wtTable = new WalkontableTable(this, settings.table); this.wtScroll = new WalkontableScroll(this); this.wtViewport = settings.cloneSource.wtViewport; } else { this.wtSettings = new WalkontableSettings(this, settings); this.wtTable = new WalkontableTable(this, settings.table); this.wtScroll = new WalkontableScroll(this); this.wtViewport = new WalkontableViewport(this); this.wtScrollbars = new WalkontableScrollbars(this); this.wtWheel = new WalkontableWheel(this); this.wtEvent = new WalkontableEvent(this); } //find original headers if (this.wtTable.THEAD.childNodes.length && this.wtTable.THEAD.childNodes[0].childNodes.length) { for (var c = 0, clen = this.wtTable.THEAD.childNodes[0].childNodes.length; c < clen; c++) { originalHeaders.push(this.wtTable.THEAD.childNodes[0].childNodes[c].innerHTML); } if (!this.getSetting('columnHeaders').length) { this.update('columnHeaders', [function (column, TH) { that.wtDom.fastInnerText(TH, originalHeaders[column]); }]); } } //initialize selections this.selections = {}; var selectionsSettings = this.getSetting('selections'); if (selectionsSettings) { for (var i in selectionsSettings) { if (selectionsSettings.hasOwnProperty(i)) { this.selections[i] = new WalkontableSelection(this, selectionsSettings[i]); } } } this.drawn = false; this.drawInterrupted = false; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table /*if (window.Handsontable) { Handsontable.PluginHooks.add('beforeChange', function () { if (that.rowHeightCache) { that.rowHeightCache.length = 0; } }); }*/ } Walkontable.prototype.draw = function (selectionsOnly) { this.drawInterrupted = false; if (!selectionsOnly && !this.wtDom.isVisible(this.wtTable.TABLE)) { this.drawInterrupted = true; //draw interrupted because TABLE is not visible return; } this.getSetting('beforeDraw', !selectionsOnly); selectionsOnly = selectionsOnly && this.getSetting('offsetRow') === this.lastOffsetRow && this.getSetting('offsetColumn') === this.lastOffsetColumn; if (this.drawn) { //fix offsets that might have changed this.scrollVertical(0); this.scrollHorizontal(0); } this.lastOffsetRow = this.getSetting('offsetRow'); this.lastOffsetColumn = this.getSetting('offsetColumn'); this.wtTable.draw(selectionsOnly); if (!this.cloneSource) { this.getSetting('onDraw', !selectionsOnly); } return this; }; Walkontable.prototype.update = function (settings, value) { return this.wtSettings.update(settings, value); }; Walkontable.prototype.scrollVertical = function (delta) { var result = this.wtScroll.scrollVertical(delta); this.getSetting('onScrollVertically'); return result; }; Walkontable.prototype.scrollHorizontal = function (delta) { var result = this.wtScroll.scrollHorizontal(delta); this.getSetting('onScrollHorizontally'); return result; }; Walkontable.prototype.scrollViewport = function (coords) { this.wtScroll.scrollViewport(coords); return this; }; Walkontable.prototype.getViewport = function () { return [ this.wtTable.rowFilter.visibleToSource(0), this.wtTable.columnFilter.visibleToSource(0), this.wtTable.getLastVisibleRow(), this.wtTable.getLastVisibleColumn() ]; }; Walkontable.prototype.getSetting = function (key, param1, param2, param3) { return this.wtSettings.getSetting(key, param1, param2, param3); }; Walkontable.prototype.hasSetting = function (key) { return this.wtSettings.has(key); }; Walkontable.prototype.destroy = function () { $(document.body).off('.' + this.guid); this.wtScrollbars.destroy(); clearTimeout(this.wheelTimeout); this.wtEvent && this.wtEvent.destroy(); }; /** * A overlay that renders ALL available rows & columns positioned on top of the original Walkontable instance and all other overlays. * Used for debugging purposes to see if the other overlays (that render only part of the rows & columns) are positioned correctly * @param instance * @constructor */ function WalkontableDebugOverlay(instance) { this.instance = instance; this.init(); this.clone = this.makeClone('debug'); this.clone.wtTable.holder.style.opacity = 0.4; this.clone.wtTable.holder.style.textShadow = '0 0 2px #ff0000'; var that = this; var lastTimeout; var lastX = 0; var lastY = 0; var overlayContainer = that.clone.wtTable.holder.parentNode; $(document.body).on('mousemove.' + this.instance.guid, function (event) { if (!that.instance.wtTable.holder.parentNode) { return; //removed from DOM } if ((event.clientX - lastX > -5 && event.clientX - lastX < 5) && (event.clientY - lastY > -5 && event.clientY - lastY < 5)) { return; //ignore minor mouse movement } lastX = event.clientX; lastY = event.clientY; WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugHidden'); WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugVisible'); clearTimeout(lastTimeout); lastTimeout = setTimeout(function () { WalkontableDom.prototype.removeClass(overlayContainer, 'wtDebugHidden'); WalkontableDom.prototype.addClass(overlayContainer, 'wtDebugVisible'); }, 1000); }); } WalkontableDebugOverlay.prototype = new WalkontableOverlay(); WalkontableDebugOverlay.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box = this.instance.wtTable.holder.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; }; WalkontableDebugOverlay.prototype.prepare = function () { }; WalkontableDebugOverlay.prototype.refresh = function (selectionsOnly) { this.clone && this.clone.draw(selectionsOnly); }; WalkontableDebugOverlay.prototype.getScrollPosition = function () { }; WalkontableDebugOverlay.prototype.getLastCell = function () { }; WalkontableDebugOverlay.prototype.applyToDOM = function () { }; WalkontableDebugOverlay.prototype.scrollTo = function () { }; WalkontableDebugOverlay.prototype.readWindowSize = function () { }; WalkontableDebugOverlay.prototype.readSettings = function () { }; function WalkontableDom() { } //goes up the DOM tree (including given element) until it finds an element that matches the nodeName WalkontableDom.prototype.closest = function (elem, nodeNames, until) { while (elem != null && elem !== until) { if (elem.nodeType === 1 && nodeNames.indexOf(elem.nodeName) > -1) { return elem; } elem = elem.parentNode; } return null; }; //goes up the DOM tree and checks if element is child of another element WalkontableDom.prototype.isChildOf = function (child, parent) { var node = child.parentNode; while (node != null) { if (node == parent) { return true; } node = node.parentNode; } return false; }; /** * Counts index of element within its parent * WARNING: for performance reasons, assumes there are only element nodes (no text nodes). This is true for Walkotnable * Otherwise would need to check for nodeType or use previousElementSibling * @see http://jsperf.com/sibling-index/10 * @param {Element} elem * @return {Number} */ WalkontableDom.prototype.index = function (elem) { var i = 0; while (elem = elem.previousSibling) { ++i } return i; }; if (document.documentElement.classList) { // HTML5 classList API WalkontableDom.prototype.hasClass = function (ele, cls) { return ele.classList.contains(cls); }; WalkontableDom.prototype.addClass = function (ele, cls) { ele.classList.add(cls); }; WalkontableDom.prototype.removeClass = function (ele, cls) { ele.classList.remove(cls); }; } else { //http://snipplr.com/view/3561/addclass-removeclass-hasclass/ WalkontableDom.prototype.hasClass = function (ele, cls) { return ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)')); }; WalkontableDom.prototype.addClass = function (ele, cls) { if (!this.hasClass(ele, cls)) ele.className += " " + cls; }; WalkontableDom.prototype.removeClass = function (ele, cls) { if (this.hasClass(ele, cls)) { //is this really needed? var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)'); ele.className = ele.className.replace(reg, ' ').trim(); //String.prototype.trim is defined in polyfill.js } }; } /*//http://net.tutsplus.com/tutorials/javascript-ajax/javascript-from-null-cross-browser-event-binding/ WalkontableDom.prototype.addEvent = (function () { var that = this; if (document.addEventListener) { return function (elem, type, cb) { if ((elem && !elem.length) || elem === window) { elem.addEventListener(type, cb, false); } else if (elem && elem.length) { var len = elem.length; for (var i = 0; i < len; i++) { that.addEvent(elem[i], type, cb); } } }; } else { return function (elem, type, cb) { if ((elem && !elem.length) || elem === window) { elem.attachEvent('on' + type, function () { //normalize //http://stackoverflow.com/questions/4643249/cross-browser-event-object-normalization var e = window['event']; e.target = e.srcElement; //e.offsetX = e.layerX; //e.offsetY = e.layerY; e.relatedTarget = e.relatedTarget || e.type == 'mouseover' ? e.fromElement : e.toElement; if (e.target.nodeType === 3) e.target = e.target.parentNode; //Safari bug return cb.call(elem, e) }); } else if (elem.length) { var len = elem.length; for (var i = 0; i < len; i++) { that.addEvent(elem[i], type, cb); } } }; } })(); WalkontableDom.prototype.triggerEvent = function (element, eventName, target) { var event; if (document.createEvent) { event = document.createEvent("MouseEvents"); event.initEvent(eventName, true, true); } else { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; event.target = target; if (document.createEvent) { target.dispatchEvent(event); } else { target.fireEvent("on" + event.eventType, event); } };*/ WalkontableDom.prototype.removeTextNodes = function (elem, parent) { if (elem.nodeType === 3) { parent.removeChild(elem); //bye text nodes! } else if (['TABLE', 'THEAD', 'TBODY', 'TFOOT', 'TR'].indexOf(elem.nodeName) > -1) { var childs = elem.childNodes; for (var i = childs.length - 1; i >= 0; i--) { this.removeTextNodes(childs[i], elem); } } }; /** * Remove childs function * WARNING - this doesn't unload events and data attached by jQuery * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/9 * http://jsperf.com/jquery-html-vs-empty-vs-innerhtml/11 - no siginificant improvement with Chrome remove() method * @param element * @returns {void} */ // WalkontableDom.prototype.empty = function (element) { var child; while (child = element.lastChild) { element.removeChild(child); } }; WalkontableDom.prototype.HTML_CHARACTERS = /(<(.*)>|&(.*);)/; /** * Insert content into element trying avoid innerHTML method. * @return {void} */ WalkontableDom.prototype.fastInnerHTML = function (element, content) { if (this.HTML_CHARACTERS.test(content)) { element.innerHTML = content; } else { this.fastInnerText(element, content); } }; /** * Insert text content into element * @return {void} */ if (document.createTextNode('test').textContent) { //STANDARDS WalkontableDom.prototype.fastInnerText = function (element, content) { var child = element.firstChild; if (child && child.nodeType === 3 && child.nextSibling === null) { //fast lane - replace existing text node //http://jsperf.com/replace-text-vs-reuse child.textContent = content; } else { //slow lane - empty element and insert a text node this.empty(element); element.appendChild(document.createTextNode(content)); } }; } else { //IE8 WalkontableDom.prototype.fastInnerText = function (element, content) { var child = element.firstChild; if (child && child.nodeType === 3 && child.nextSibling === null) { //fast lane - replace existing text node //http://jsperf.com/replace-text-vs-reuse child.data = content; } else { //slow lane - empty element and insert a text node this.empty(element); element.appendChild(document.createTextNode(content)); } }; } /** * Returns true/false depending if element has offset parent * @param elem * @returns {boolean} */ /*if (document.createTextNode('test').textContent) { //STANDARDS WalkontableDom.prototype.hasOffsetParent = function (elem) { return !!elem.offsetParent; } } else { WalkontableDom.prototype.hasOffsetParent = function (elem) { try { if (!elem.offsetParent) { return false; } } catch (e) { return false; //IE8 throws "Unspecified error" when offsetParent is not found - we catch it here } return true; } }*/ /** * Returns true if element is attached to the DOM and visible, false otherwise * @param elem * @returns {boolean} */ WalkontableDom.prototype.isVisible = function (elem) { //fast method according to benchmarks, but requires layout so slow in our case /* if (!WalkontableDom.prototype.hasOffsetParent(elem)) { return false; //fixes problem with UI Bootstrap <tabs> directive } // if (elem.offsetWidth > 0 || (elem.parentNode && elem.parentNode.offsetWidth > 0)) { //IE10 was mistaken here if (elem.offsetWidth > 0) { return true; } */ //slow method var next = elem; while (next !== document.documentElement) { //until <html> reached if (next === null) { //parent detached from DOM return false; } else if (next.nodeType === 11) { //nodeType == 1 -> DOCUMENT_FRAGMENT_NODE if (next.host) { //this is Web Components Shadow DOM //see: http://w3c.github.io/webcomponents/spec/shadow/#encapsulation //according to spec, should be if (next.ownerDocument !== window.document), but that doesn't work yet if (next.host.impl) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features disabled return WalkontableDom.prototype.isVisible(next.host.impl); } else if (next.host) { //Chrome 33.0.1723.0 canary (2013-11-29) Web Platform features enabled return WalkontableDom.prototype.isVisible(next.host); } else { throw new Error("Lost in Web Components world"); } } else { return false; //this is a node detached from document in IE8 } } else if (next.style.display === 'none') { return false; } next = next.parentNode; } return true; }; /** * Returns elements top and left offset relative to the document. In our usage case compatible with jQuery but 2x faster * @param {HTMLElement} elem * @return {Object} */ WalkontableDom.prototype.offset = function (elem) { if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { //fixes problem with Firefox ignoring <caption> in TABLE offset (see also WalkontableDom.prototype.outerHeight) //http://jsperf.com/offset-vs-getboundingclientrect/8 var box = elem.getBoundingClientRect(); return { top: box.top + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0), left: box.left + (window.pageXOffset || document.documentElement.scrollLeft) - (document.documentElement.clientLeft || 0) }; } var offsetLeft = elem.offsetLeft , offsetTop = elem.offsetTop , lastElem = elem; while (elem = elem.offsetParent) { if (elem === document.body) { //from my observation, document.body always has scrollLeft/scrollTop == 0 break; } offsetLeft += elem.offsetLeft; offsetTop += elem.offsetTop; lastElem = elem; } if (lastElem && lastElem.style.position === 'fixed') { //slow - http://jsperf.com/offset-vs-getboundingclientrect/6 //if(lastElem !== document.body) { //faster but does gives false positive in Firefox offsetLeft += window.pageXOffset || document.documentElement.scrollLeft; offsetTop += window.pageYOffset || document.documentElement.scrollTop; } return { left: offsetLeft, top: offsetTop }; }; WalkontableDom.prototype.getComputedStyle = function (elem) { return elem.currentStyle || document.defaultView.getComputedStyle(elem); }; WalkontableDom.prototype.outerWidth = function (elem) { return elem.offsetWidth; }; WalkontableDom.prototype.outerHeight = function (elem) { if (this.hasCaptionProblem() && elem.firstChild && elem.firstChild.nodeName === 'CAPTION') { //fixes problem with Firefox ignoring <caption> in TABLE.offsetHeight //jQuery (1.10.1) still has this unsolved //may be better to just switch to getBoundingClientRect //http://bililite.com/blog/2009/03/27/finding-the-size-of-a-table/ //http://lists.w3.org/Archives/Public/www-style/2009Oct/0089.html //http://bugs.jquery.com/ticket/2196 //http://lists.w3.org/Archives/Public/www-style/2009Oct/0140.html#start140 return elem.offsetHeight + elem.firstChild.offsetHeight; } else { return elem.offsetHeight; } }; (function () { var hasCaptionProblem; function detectCaptionProblem() { var TABLE = document.createElement('TABLE'); TABLE.style.borderSpacing = 0; TABLE.style.borderWidth = 0; TABLE.style.padding = 0; var TBODY = document.createElement('TBODY'); TABLE.appendChild(TBODY); TBODY.appendChild(document.createElement('TR')); TBODY.firstChild.appendChild(document.createElement('TD')); TBODY.firstChild.firstChild.innerHTML = '<tr><td>t<br>t</td></tr>'; var CAPTION = document.createElement('CAPTION'); CAPTION.innerHTML = 'c<br>c<br>c<br>c'; CAPTION.style.padding = 0; CAPTION.style.margin = 0; TABLE.insertBefore(CAPTION, TBODY); document.body.appendChild(TABLE); hasCaptionProblem = (TABLE.offsetHeight < 2 * TABLE.lastChild.offsetHeight); //boolean document.body.removeChild(TABLE); } WalkontableDom.prototype.hasCaptionProblem = function () { if (hasCaptionProblem === void 0) { detectCaptionProblem(); } return hasCaptionProblem; }; /** * Returns caret position in text input * @author http://stackoverflow.com/questions/263743/how-to-get-caret-position-in-textarea * @return {Number} */ WalkontableDom.prototype.getCaretPosition = function (el) { if (el.selectionStart) { return el.selectionStart; } else if (document.selection) { //IE8 el.focus(); var r = document.selection.createRange(); if (r == null) { return 0; } var re = el.createTextRange(), rc = re.duplicate(); re.moveToBookmark(r.getBookmark()); rc.setEndPoint('EndToStart', re); return rc.text.length; } return 0; }; /** * Sets caret position in text input * @author http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ * @param {Element} el * @param {Number} pos * @param {Number} endPos */ WalkontableDom.prototype.setCaretPosition = function (el, pos, endPos) { if (endPos === void 0) { endPos = pos; } if (el.setSelectionRange) { el.focus(); el.setSelectionRange(pos, endPos); } else if (el.createTextRange) { //IE8 var range = el.createTextRange(); range.collapse(true); range.moveEnd('character', endPos); range.moveStart('character', pos); range.select(); } }; var cachedScrollbarWidth; //http://stackoverflow.com/questions/986937/how-can-i-get-the-browsers-scrollbar-sizes function walkontableCalculateScrollbarWidth() { var inner = document.createElement('p'); inner.style.width = "100%"; inner.style.height = "200px"; var outer = document.createElement('div'); outer.style.position = "absolute"; outer.style.top = "0px"; outer.style.left = "0px"; outer.style.visibility = "hidden"; outer.style.width = "200px"; outer.style.height = "150px"; outer.style.overflow = "hidden"; outer.appendChild(inner); (document.body || document.documentElement).appendChild(outer); var w1 = inner.offsetWidth; outer.style.overflow = 'scroll'; var w2 = inner.offsetWidth; if (w1 == w2) w2 = outer.clientWidth; (document.body || document.documentElement).removeChild(outer); return (w1 - w2); } /** * Returns the computed width of the native browser scroll bar * @return {Number} width */ WalkontableDom.prototype.getScrollbarWidth = function () { if (cachedScrollbarWidth === void 0) { cachedScrollbarWidth = walkontableCalculateScrollbarWidth(); } return cachedScrollbarWidth; } })(); function WalkontableEvent(instance) { var that = this; //reference to instance this.instance = instance; this.wtDom = this.instance.wtDom; var dblClickOrigin = [null, null]; var dblClickTimeout = [null, null]; var onMouseDown = function (event) { var cell = that.parentCell(event.target); if (that.wtDom.hasClass(event.target, 'corner')) { that.instance.getSetting('onCellCornerMouseDown', event, event.target); } else if (cell.TD && cell.TD.nodeName === 'TD') { if (that.instance.hasSetting('onCellMouseDown')) { that.instance.getSetting('onCellMouseDown', event, cell.coords, cell.TD); } } if (event.button !== 2) { //if not right mouse button if (cell.TD && cell.TD.nodeName === 'TD') { dblClickOrigin[0] = cell.TD; clearTimeout(dblClickTimeout[0]); dblClickTimeout[0] = setTimeout(function () { dblClickOrigin[0] = null; }, 1000); } } }; var lastMouseOver; var onMouseOver = function (event) { if (that.instance.hasSetting('onCellMouseOver')) { var TABLE = that.instance.wtTable.TABLE; var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE); if (TD && TD !== lastMouseOver && that.wtDom.isChildOf(TD, TABLE)) { lastMouseOver = TD; if (TD.nodeName === 'TD') { that.instance.getSetting('onCellMouseOver', event, that.instance.wtTable.getCoords(TD), TD); } } } }; /* var lastMouseOut; var onMouseOut = function (event) { if (that.instance.hasSetting('onCellMouseOut')) { var TABLE = that.instance.wtTable.TABLE; var TD = that.wtDom.closest(event.target, ['TD', 'TH'], TABLE); if (TD && TD !== lastMouseOut && that.wtDom.isChildOf(TD, TABLE)) { lastMouseOut = TD; if (TD.nodeName === 'TD') { that.instance.getSetting('onCellMouseOut', event, that.instance.wtTable.getCoords(TD), TD); } } } };*/ var onMouseUp = function (event) { if (event.button !== 2) { //if not right mouse button var cell = that.parentCell(event.target); if (cell.TD === dblClickOrigin[0] && cell.TD === dblClickOrigin[1]) { if (that.wtDom.hasClass(event.target, 'corner')) { that.instance.getSetting('onCellCornerDblClick', event, cell.coords, cell.TD); } else if (cell.TD) { that.instance.getSetting('onCellDblClick', event, cell.coords, cell.TD); } dblClickOrigin[0] = null; dblClickOrigin[1] = null; } else if (cell.TD === dblClickOrigin[0]) { dblClickOrigin[1] = cell.TD; clearTimeout(dblClickTimeout[1]); dblClickTimeout[1] = setTimeout(function () { dblClickOrigin[1] = null; }, 500); } } }; $(this.instance.wtTable.holder).on('mousedown', onMouseDown); $(this.instance.wtTable.TABLE).on('mouseover', onMouseOver); // $(this.instance.wtTable.TABLE).on('mouseout', onMouseOut); $(this.instance.wtTable.holder).on('mouseup', onMouseUp); } WalkontableEvent.prototype.parentCell = function (elem) { var cell = {}; var TABLE = this.instance.wtTable.TABLE; var TD = this.wtDom.closest(elem, ['TD', 'TH'], TABLE); if (TD && this.wtDom.isChildOf(TD, TABLE)) { cell.coords = this.instance.wtTable.getCoords(TD); cell.TD = TD; } else if (this.wtDom.hasClass(elem, 'wtBorder') && this.wtDom.hasClass(elem, 'current')) { cell.coords = this.instance.selections.current.selected[0]; cell.TD = this.instance.wtTable.getCell(cell.coords); } return cell; }; WalkontableEvent.prototype.destroy = function () { clearTimeout(this.dblClickTimeout0); clearTimeout(this.dblClickTimeout1); }; function walkontableRangesIntersect() { var from = arguments[0]; var to = arguments[1]; for (var i = 1, ilen = arguments.length / 2; i < ilen; i++) { if (from <= arguments[2 * i + 1] && to >= arguments[2 * i]) { return true; } } return false; } /** * Generates a random hex string. Used as namespace for Walkontable instance events. * @return {String} - 16 character random string: "92b1bfc74ec4" */ function walkontableRandomString() { function s4() { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } return s4() + s4() + s4() + s4(); } /** * http://notes.jetienne.com/2011/05/18/cancelRequestAnimFrame-for-paul-irish-requestAnimFrame.html */ window.requestAnimFrame = (function () { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (/* function */ callback, /* DOMElement */ element) { return window.setTimeout(callback, 1000 / 60); }; })(); window.cancelRequestAnimFrame = (function () { return window.cancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || window.oCancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || clearTimeout })(); //http://snipplr.com/view/13523/ //modified for speed //http://jsperf.com/getcomputedstyle-vs-style-vs-css/8 if (!window.getComputedStyle) { (function () { var elem; var styleObj = { getPropertyValue: function getPropertyValue(prop) { if (prop == 'float') prop = 'styleFloat'; return elem.currentStyle[prop.toUpperCase()] || null; } }; window.getComputedStyle = function (el) { elem = el; return styleObj; } })(); } /** * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim */ if (!String.prototype.trim) { var trimRegex = /^\s+|\s+$/g; String.prototype.trim = function () { return this.replace(trimRegex, ''); }; } /** * WalkontableRowFilter * @constructor */ function WalkontableRowFilter() { } WalkontableRowFilter.prototype = new WalkontableCellFilter(); WalkontableRowFilter.prototype.readSettings = function (instance) { if (instance.cloneOverlay instanceof WalkontableDebugOverlay) { this.offset = 0; } else { this.offset = instance.wtSettings.settings.offsetRow; } this.total = instance.getSetting('totalRows'); this.fixedCount = instance.getSetting('fixedRowsTop'); }; /** * WalkontableRowStrategy * @param containerSizeFn * @param sizeAtIndex * @constructor */ function WalkontableRowStrategy(instance, containerSizeFn, sizeAtIndex) { WalkontableCellStrategy.apply(this, arguments); this.containerSizeFn = containerSizeFn; this.sizeAtIndex = sizeAtIndex; this.cellSizesSum = 0; this.cellSizes = []; this.cellCount = 0; this.remainingSize = -Infinity; } WalkontableRowStrategy.prototype = new WalkontableCellStrategy(); WalkontableRowStrategy.prototype.add = function (i, TD, reverse) { if (!this.isLastIncomplete() && this.remainingSize != 0) { var size = this.sizeAtIndex(i, TD); if (size === void 0) { return false; //total rows exceeded } var containerSize = this.getContainerSize(this.cellSizesSum + size); if (reverse) { this.cellSizes.unshift(size); } else { this.cellSizes.push(size); } this.cellSizesSum += size; this.cellCount++; this.remainingSize = this.cellSizesSum - containerSize; if (reverse && this.isLastIncomplete()) { //something is outside of the screen, maybe even some full rows? return false; } return true; } return false; }; WalkontableRowStrategy.prototype.remove = function () { var size = this.cellSizes.pop(); this.cellSizesSum -= size; this.cellCount--; this.remainingSize -= size; }; WalkontableRowStrategy.prototype.removeOutstanding = function () { while (this.cellCount > 0 && this.cellSizes[this.cellCount - 1] < this.remainingSize) { //this row is completely off screen! this.remove(); } }; function WalkontableScroll(instance) { this.instance = instance; } WalkontableScroll.prototype.scrollVertical = function (delta) { if (!this.instance.drawn) { throw new Error('scrollVertical can only be called after table was drawn to DOM'); } var instance = this.instance , newOffset , offset = instance.getSetting('offsetRow') , fixedCount = instance.getSetting('fixedRowsTop') , total = instance.getSetting('totalRows') , maxSize = instance.wtViewport.getViewportHeight(); if (total > 0) { newOffset = this.scrollLogicVertical(delta, offset, total, fixedCount, maxSize, function (row) { if (row - offset < fixedCount && row - offset >= 0) { return instance.getSetting('rowHeight', row - offset); } else { return instance.getSetting('rowHeight', row); } }, function (isReverse) { instance.wtTable.verticalRenderReverse = isReverse; }); } else { newOffset = 0; } if (newOffset !== offset) { this.instance.wtScrollbars.vertical.scrollTo(newOffset); } return instance; }; WalkontableScroll.prototype.scrollHorizontal = function (delta) { if (!this.instance.drawn) { throw new Error('scrollHorizontal can only be called after table was drawn to DOM'); } var instance = this.instance , newOffset , offset = instance.getSetting('offsetColumn') , fixedCount = instance.getSetting('fixedColumnsLeft') , total = instance.getSetting('totalColumns') , maxSize = instance.wtViewport.getViewportWidth(); if (total > 0) { newOffset = this.scrollLogicHorizontal(delta, offset, total, fixedCount, maxSize, function (col) { if (col - offset < fixedCount && col - offset >= 0) { return instance.getSetting('columnWidth', col - offset); } else { return instance.getSetting('columnWidth', col); } }); } else { newOffset = 0; } if (newOffset !== offset) { this.instance.wtScrollbars.horizontal.scrollTo(newOffset); } return instance; }; WalkontableScroll.prototype.scrollLogicVertical = function (delta, offset, total, fixedCount, maxSize, cellSizeFn, setReverseRenderFn) { var newOffset = offset + delta; if (newOffset >= total - fixedCount) { newOffset = total - fixedCount - 1; setReverseRenderFn(true); } if (newOffset < 0) { newOffset = 0; } return newOffset; }; WalkontableScroll.prototype.scrollLogicHorizontal = function (delta, offset, total, fixedCount, maxSize, cellSizeFn) { var newOffset = offset + delta , sum = 0 , col; if (newOffset > fixedCount) { if (newOffset >= total - fixedCount) { newOffset = total - fixedCount - 1; } col = newOffset; while (sum < maxSize && col < total) { sum += cellSizeFn(col); col++; } if (sum < maxSize) { while (newOffset > 0) { //if sum still less than available width, we cannot scroll that far (must move offset to the left) sum += cellSizeFn(newOffset - 1); if (sum < maxSize) { newOffset--; } else { break; } } } } else if (newOffset < 0) { newOffset = 0; } return newOffset; }; /** * Scrolls viewport to a cell by minimum number of cells */ WalkontableScroll.prototype.scrollViewport = function (coords) { if (!this.instance.drawn) { return; } var offsetRow = this.instance.getSetting('offsetRow') , offsetColumn = this.instance.getSetting('offsetColumn') , lastVisibleRow = this.instance.wtTable.getLastVisibleRow() , totalRows = this.instance.getSetting('totalRows') , totalColumns = this.instance.getSetting('totalColumns') , fixedRowsTop = this.instance.getSetting('fixedRowsTop') , fixedColumnsLeft = this.instance.getSetting('fixedColumnsLeft'); if (this.instance.getSetting('nativeScrollbars')) { var TD = this.instance.wtTable.getCell(coords); if (typeof TD === 'object') { var offset = WalkontableDom.prototype.offset(TD); var outerWidth = WalkontableDom.prototype.outerWidth(TD); var outerHeight = WalkontableDom.prototype.outerHeight(TD); var scrollX = this.instance.wtScrollbars.horizontal.getScrollPosition(); var scrollY = this.instance.wtScrollbars.vertical.getScrollPosition(); var clientWidth = WalkontableDom.prototype.outerWidth(this.instance.wtScrollbars.horizontal.scrollHandler); var clientHeight = WalkontableDom.prototype.outerHeight(this.instance.wtScrollbars.vertical.scrollHandler); if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) { offset.left = offset.left - WalkontableDom.prototype.offset(this.instance.wtScrollbars.horizontal.scrollHandler).left; } if (this.instance.wtScrollbars.vertical.scrollHandler !== window) { offset.top = offset.top - WalkontableDom.prototype.offset(this.instance.wtScrollbars.vertical.scrollHandler).top; } clientWidth -= 20; clientHeight -= 20; if (outerWidth < clientWidth) { if (offset.left < scrollX) { this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left); } else if (offset.left + outerWidth > scrollX + clientWidth) { this.instance.wtScrollbars.horizontal.setScrollPosition(offset.left - clientWidth + outerWidth); } } if (outerHeight < clientHeight) { if (offset.top < scrollY) { this.instance.wtScrollbars.vertical.setScrollPosition(offset.top); } else if (offset.top + outerHeight > scrollY + clientHeight) { this.instance.wtScrollbars.vertical.setScrollPosition(offset.top - clientHeight + outerHeight); } } return; } } if (coords[0] < 0 || coords[0] > totalRows - 1) { throw new Error('row ' + coords[0] + ' does not exist'); } else if (coords[1] < 0 || coords[1] > totalColumns - 1) { throw new Error('column ' + coords[1] + ' does not exist'); } if (coords[0] > lastVisibleRow) { // this.scrollVertical(coords[0] - lastVisibleRow + 1); this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); this.instance.wtTable.verticalRenderReverse = true; } else if (coords[0] === lastVisibleRow && this.instance.wtTable.rowStrategy.isLastIncomplete()) { // this.scrollVertical(coords[0] - lastVisibleRow + 1); this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); this.instance.wtTable.verticalRenderReverse = true; } else if (coords[0] - fixedRowsTop < offsetRow) { this.scrollVertical(coords[0] - fixedRowsTop - offsetRow); } else { this.scrollVertical(0); //Craig's issue: remove row from the last scroll page should scroll viewport a row up if needed } if (this.instance.wtTable.isColumnBeforeViewport(coords[1])) { //scroll left this.instance.wtScrollbars.horizontal.scrollTo(coords[1] - fixedColumnsLeft); } else if (this.instance.wtTable.isColumnAfterViewport(coords[1]) || (this.instance.wtTable.getLastVisibleColumn() === coords[1] && !this.instance.wtTable.isLastColumnFullyVisible())) { //scroll right var sum = 0; for (var i = 0; i < fixedColumnsLeft; i++) { sum += this.instance.getSetting('columnWidth', i); } var scrollTo = coords[1]; sum += this.instance.getSetting('columnWidth', scrollTo); var available = this.instance.wtViewport.getViewportWidth(); if (sum < available) { var next = this.instance.getSetting('columnWidth', scrollTo - 1); while (sum + next <= available && scrollTo >= fixedColumnsLeft) { scrollTo--; sum += next; next = this.instance.getSetting('columnWidth', scrollTo - 1); } } this.instance.wtScrollbars.horizontal.scrollTo(scrollTo - fixedColumnsLeft); } /*else { //no scroll }*/ return this.instance; }; function WalkontableScrollbar() { } WalkontableScrollbar.prototype.init = function () { var that = this; //reference to instance this.$table = $(this.instance.wtTable.TABLE); //create elements this.slider = document.createElement('DIV'); this.sliderStyle = this.slider.style; this.sliderStyle.position = 'absolute'; this.sliderStyle.top = '0'; this.sliderStyle.left = '0'; this.sliderStyle.display = 'none'; this.slider.className = 'dragdealer ' + this.type; this.handle = document.createElement('DIV'); this.handleStyle = this.handle.style; this.handle.className = 'handle'; this.slider.appendChild(this.handle); this.container = this.instance.wtTable.holder; this.container.appendChild(this.slider); var firstRun = true; this.dragTimeout = null; var dragDelta; var dragRender = function () { that.onScroll(dragDelta); }; this.dragdealer = new Dragdealer(this.slider, { vertical: (this.type === 'vertical'), horizontal: (this.type === 'horizontal'), slide: false, speed: 100, animationCallback: function (x, y) { if (firstRun) { firstRun = false; return; } that.skipRefresh = true; dragDelta = that.type === 'vertical' ? y : x; if (that.dragTimeout === null) { that.dragTimeout = setInterval(dragRender, 100); dragRender(); } }, callback: function (x, y) { that.skipRefresh = false; clearInterval(that.dragTimeout); that.dragTimeout = null; dragDelta = that.type === 'vertical' ? y : x; that.onScroll(dragDelta); } }); this.skipRefresh = false; }; WalkontableScrollbar.prototype.onScroll = function (delta) { if (this.instance.drawn) { this.readSettings(); if (this.total > this.visibleCount) { var newOffset = Math.round(this.handlePosition * this.total / this.sliderSize); if (delta === 1) { if (this.type === 'vertical') { this.instance.scrollVertical(Infinity).draw(); } else { this.instance.scrollHorizontal(Infinity).draw(); } } else if (newOffset !== this.offset) { //is new offset different than old offset if (this.type === 'vertical') { this.instance.scrollVertical(newOffset - this.offset).draw(); } else { this.instance.scrollHorizontal(newOffset - this.offset).draw(); } } else { this.refresh(); } } } }; /** * Returns what part of the scroller should the handle take * @param viewportCount {Number} number of visible rows or columns * @param totalCount {Number} total number of rows or columns * @return {Number} 0..1 */ WalkontableScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) { if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) { return 1; } return 1 / totalCount; }; WalkontableScrollbar.prototype.prepare = function () { if (this.skipRefresh) { return; } var ratio = this.getHandleSizeRatio(this.visibleCount, this.total); if (((ratio === 1 || isNaN(ratio)) && this.scrollMode === 'auto') || this.scrollMode === 'none') { //isNaN is needed because ratio equals NaN when totalRows/totalColumns equals 0 this.visible = false; } else { this.visible = true; } }; WalkontableScrollbar.prototype.refresh = function () { if (this.skipRefresh) { return; } else if (!this.visible) { this.sliderStyle.display = 'none'; return; } var ratio , sliderSize , handleSize , handlePosition , visibleCount = this.visibleCount , tableWidth = this.instance.wtViewport.getWorkspaceWidth() , tableHeight = this.instance.wtViewport.getWorkspaceHeight(); if (tableWidth === Infinity) { tableWidth = this.instance.wtViewport.getWorkspaceActualWidth(); } if (tableHeight === Infinity) { tableHeight = this.instance.wtViewport.getWorkspaceActualHeight(); } if (this.type === 'vertical') { if (this.instance.wtTable.rowStrategy.isLastIncomplete()) { visibleCount--; } sliderSize = tableHeight - 2; //2 is sliders border-width this.sliderStyle.top = this.instance.wtDom.offset(this.$table[0]).top - this.instance.wtDom.offset(this.container).top + 'px'; this.sliderStyle.left = tableWidth - 1 + 'px'; //1 is sliders border-width this.sliderStyle.height = Math.max(sliderSize, 0) + 'px'; } else { //horizontal sliderSize = tableWidth - 2; //2 is sliders border-width this.sliderStyle.left = this.instance.wtDom.offset(this.$table[0]).left - this.instance.wtDom.offset(this.container).left + 'px'; this.sliderStyle.top = tableHeight - 1 + 'px'; //1 is sliders border-width this.sliderStyle.width = Math.max(sliderSize, 0) + 'px'; } ratio = this.getHandleSizeRatio(visibleCount, this.total); handleSize = Math.round(sliderSize * ratio); if (handleSize < 10) { handleSize = 15; } handlePosition = Math.floor(sliderSize * (this.offset / this.total)); if (handleSize + handlePosition > sliderSize) { handlePosition = sliderSize - handleSize; } if (this.type === 'vertical') { this.handleStyle.height = handleSize + 'px'; this.handleStyle.top = handlePosition + 'px'; } else { //horizontal this.handleStyle.width = handleSize + 'px'; this.handleStyle.left = handlePosition + 'px'; } this.sliderStyle.display = 'block'; }; WalkontableScrollbar.prototype.destroy = function () { clearInterval(this.dragdealer.interval); }; /// var WalkontableVerticalScrollbar = function (instance) { this.instance = instance; this.type = 'vertical'; this.init(); }; WalkontableVerticalScrollbar.prototype = new WalkontableScrollbar(); WalkontableVerticalScrollbar.prototype.scrollTo = function (cell) { this.instance.update('offsetRow', cell); }; WalkontableVerticalScrollbar.prototype.readSettings = function () { this.scrollMode = this.instance.getSetting('scrollV'); this.offset = this.instance.getSetting('offsetRow'); this.total = this.instance.getSetting('totalRows'); this.visibleCount = this.instance.wtTable.rowStrategy.countVisible(); if(this.visibleCount > 1 && this.instance.wtTable.rowStrategy.isLastIncomplete()) { this.visibleCount--; } this.handlePosition = parseInt(this.handleStyle.top, 10); this.sliderSize = parseInt(this.sliderStyle.height, 10); this.fixedCount = this.instance.getSetting('fixedRowsTop'); }; /// var WalkontableHorizontalScrollbar = function (instance) { this.instance = instance; this.type = 'horizontal'; this.init(); }; WalkontableHorizontalScrollbar.prototype = new WalkontableScrollbar(); WalkontableHorizontalScrollbar.prototype.scrollTo = function (cell) { this.instance.update('offsetColumn', cell); }; WalkontableHorizontalScrollbar.prototype.readSettings = function () { this.scrollMode = this.instance.getSetting('scrollH'); this.offset = this.instance.getSetting('offsetColumn'); this.total = this.instance.getSetting('totalColumns'); this.visibleCount = this.instance.wtTable.columnStrategy.countVisible(); if(this.visibleCount > 1 && this.instance.wtTable.columnStrategy.isLastIncomplete()) { this.visibleCount--; } this.handlePosition = parseInt(this.handleStyle.left, 10); this.sliderSize = parseInt(this.sliderStyle.width, 10); this.fixedCount = this.instance.getSetting('fixedColumnsLeft'); }; WalkontableHorizontalScrollbar.prototype.getHandleSizeRatio = function (viewportCount, totalCount) { if (!totalCount || viewportCount > totalCount || viewportCount == totalCount) { return 1; } return viewportCount / totalCount; }; function WalkontableCornerScrollbarNative(instance) { this.instance = instance; this.init(); this.clone = this.makeClone('corner'); } WalkontableCornerScrollbarNative.prototype = new WalkontableOverlay(); WalkontableCornerScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var top = Math.ceil(box.top, 10); var bottom = Math.ceil(box.bottom, 10); if (top < 0 && bottom > 0) { elem.style.top = '0'; } else { elem.style.top = top + 'px'; } var left = Math.ceil(box.left, 10); var right = Math.ceil(box.right, 10); if (left < 0 && right > 0) { elem.style.left = '0'; } else { elem.style.left = left + 'px'; } } else { box = this.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } elem.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px'; }; WalkontableCornerScrollbarNative.prototype.prepare = function () { }; WalkontableCornerScrollbarNative.prototype.refresh = function (selectionsOnly) { this.measureBefore = 0; this.measureAfter = 0; this.clone && this.clone.draw(selectionsOnly); }; WalkontableCornerScrollbarNative.prototype.getScrollPosition = function () { }; WalkontableCornerScrollbarNative.prototype.getLastCell = function () { }; WalkontableCornerScrollbarNative.prototype.applyToDOM = function () { }; WalkontableCornerScrollbarNative.prototype.scrollTo = function () { }; WalkontableCornerScrollbarNative.prototype.readWindowSize = function () { }; WalkontableCornerScrollbarNative.prototype.readSettings = function () { }; function WalkontableHorizontalScrollbarNative(instance) { this.instance = instance; this.type = 'horizontal'; this.cellSize = 50; this.init(); this.clone = this.makeClone('left'); } WalkontableHorizontalScrollbarNative.prototype = new WalkontableOverlay(); //resetFixedPosition (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var left = Math.ceil(box.left, 10); var right = Math.ceil(box.right, 10); if (left < 0 && right > 0) { elem.style.left = '0'; } else { elem.style.left = left + 'px'; } } else { box = this.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } }; //react on movement of the other dimension scrollbar (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.react = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var overlayContainer = this.clone.wtTable.holder.parentNode; if (this.instance.wtScrollbars.vertical.scrollHandler === window) { var box = this.instance.wtTable.hider.getBoundingClientRect(); overlayContainer.style.top = Math.ceil(box.top, 10) + 'px'; overlayContainer.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 'px'; } else { this.clone.wtTable.holder.style.top = -(this.instance.wtScrollbars.vertical.windowScrollPosition - this.instance.wtScrollbars.vertical.measureBefore) + 'px'; overlayContainer.style.height = this.instance.wtViewport.getWorkspaceHeight() + 'px' } overlayContainer.style.width = WalkontableDom.prototype.outerWidth(this.clone.wtTable.TABLE) + 4 + 'px'; //4 is for the box shadow }; WalkontableHorizontalScrollbarNative.prototype.prepare = function () { }; WalkontableHorizontalScrollbarNative.prototype.refresh = function (selectionsOnly) { this.measureBefore = 0; this.measureAfter = 0; this.clone && this.clone.draw(selectionsOnly); }; WalkontableHorizontalScrollbarNative.prototype.getScrollPosition = function () { if (this.scrollHandler === window) { return this.scrollHandler.scrollX; } else { return this.scrollHandler.scrollLeft; } }; WalkontableHorizontalScrollbarNative.prototype.setScrollPosition = function (pos) { this.scrollHandler.scrollLeft = pos; }; WalkontableHorizontalScrollbarNative.prototype.onScroll = function () { WalkontableOverlay.prototype.onScroll.apply(this, arguments); this.instance.getSetting('onScrollHorizontally'); }; WalkontableHorizontalScrollbarNative.prototype.getLastCell = function () { return this.instance.wtTable.getLastVisibleColumn(); }; //applyToDOM (in future merge it with this.refresh?) WalkontableHorizontalScrollbarNative.prototype.applyToDOM = function () { this.fixedContainer.style.paddingLeft = this.measureBefore + 'px'; this.fixedContainer.style.paddingRight = this.measureAfter + 'px'; }; WalkontableHorizontalScrollbarNative.prototype.scrollTo = function (cell) { this.$scrollHandler.scrollLeft(this.tableParentOffset + cell * this.cellSize); }; //readWindowSize (in future merge it with this.prepare?) WalkontableHorizontalScrollbarNative.prototype.readWindowSize = function () { if (this.scrollHandler === window) { this.windowSize = document.documentElement.clientWidth; this.tableParentOffset = this.instance.wtTable.holderOffset.left; } else { this.windowSize = WalkontableDom.prototype.outerWidth(this.scrollHandler); this.tableParentOffset = 0; } this.windowScrollPosition = this.getScrollPosition(); }; //readSettings (in future merge it with this.prepare?) WalkontableHorizontalScrollbarNative.prototype.readSettings = function () { this.offset = this.instance.getSetting('offsetColumn'); this.total = this.instance.getSetting('totalColumns'); }; function WalkontableVerticalScrollbarNative(instance) { this.instance = instance; this.type = 'vertical'; this.cellSize = 23; this.init(); this.clone = this.makeClone('top'); } WalkontableVerticalScrollbarNative.prototype = new WalkontableOverlay(); //resetFixedPosition (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.resetFixedPosition = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } var elem = this.clone.wtTable.holder.parentNode; var box; if (this.scrollHandler === window) { box = this.instance.wtTable.hider.getBoundingClientRect(); var top = Math.ceil(box.top, 10); var bottom = Math.ceil(box.bottom, 10); if (top < 0 && bottom > 0) { elem.style.top = '0'; } else { elem.style.top = top + 'px'; } } else { box = this.instance.wtScrollbars.horizontal.scrollHandler.getBoundingClientRect(); elem.style.top = Math.ceil(box.top, 10) + 'px'; elem.style.left = Math.ceil(box.left, 10) + 'px'; } if (this.instance.wtScrollbars.horizontal.scrollHandler === window) { elem.style.width = this.instance.wtViewport.getWorkspaceActualWidth() + 'px'; } else { elem.style.width = WalkontableDom.prototype.outerWidth(this.instance.wtTable.holder.parentNode) + 'px'; } elem.style.height = WalkontableDom.prototype.outerHeight(this.clone.wtTable.TABLE) + 4 + 'px'; }; //react on movement of the other dimension scrollbar (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.react = function () { if (!this.instance.wtTable.holder.parentNode) { return; //removed from DOM } if (this.instance.wtScrollbars.horizontal.scrollHandler !== window) { var elem = this.clone.wtTable.holder.parentNode; elem.firstChild.style.left = -this.instance.wtScrollbars.horizontal.windowScrollPosition + 'px'; } }; WalkontableVerticalScrollbarNative.prototype.getScrollPosition = function () { if (this.scrollHandler === window) { return this.scrollHandler.scrollY; } else { return this.scrollHandler.scrollTop; } }; WalkontableVerticalScrollbarNative.prototype.setScrollPosition = function (pos) { this.scrollHandler.scrollTop = pos; }; WalkontableVerticalScrollbarNative.prototype.onScroll = function (forcePosition) { WalkontableOverlay.prototype.onScroll.apply(this, arguments); var scrollDelta; var newOffset = 0; if (1 == 1 || this.windowScrollPosition > this.tableParentOffset) { scrollDelta = this.windowScrollPosition - this.tableParentOffset; partialOffset = 0; if (scrollDelta > 0) { var sum = 0; var last; for (var i = 0; i < this.total; i++) { last = this.instance.getSetting('rowHeight', i); sum += last; if (sum > scrollDelta) { break; } } if (this.offset > 0) { partialOffset = (sum - scrollDelta); } newOffset = i; newOffset = Math.min(newOffset, this.total); } } this.curOuts = newOffset > this.maxOuts ? this.maxOuts : newOffset; newOffset -= this.curOuts; this.instance.update('offsetRow', newOffset); this.readSettings(); //read new offset this.instance.draw(); this.instance.getSetting('onScrollVertically'); }; WalkontableVerticalScrollbarNative.prototype.getLastCell = function () { return this.instance.getSetting('offsetRow') + this.instance.wtTable.tbodyChildrenLength - 1; }; var partialOffset = 0; WalkontableVerticalScrollbarNative.prototype.sumCellSizes = function (from, length) { var sum = 0; while (from < length) { sum += this.instance.getSetting('rowHeight', from); from++; } return sum; }; //applyToDOM (in future merge it with this.refresh?) WalkontableVerticalScrollbarNative.prototype.applyToDOM = function () { var headerSize = this.instance.wtViewport.getColumnHeaderHeight(); this.fixedContainer.style.height = headerSize + this.sumCellSizes(0, this.total) + 4 + 'px'; //+4 is needed, otherwise vertical scroll appears in Chrome (window scroll mode) - maybe because of fill handle in last row or because of box shadow this.fixed.style.top = this.measureBefore + 'px'; this.fixed.style.bottom = ''; }; WalkontableVerticalScrollbarNative.prototype.scrollTo = function (cell) { var newY = this.tableParentOffset + cell * this.cellSize; this.$scrollHandler.scrollTop(newY); this.onScroll(newY); }; //readWindowSize (in future merge it with this.prepare?) WalkontableVerticalScrollbarNative.prototype.readWindowSize = function () { if (this.scrollHandler === window) { this.windowSize = document.documentElement.clientHeight; this.tableParentOffset = this.instance.wtTable.holderOffset.top; } else { //this.windowSize = WalkontableDom.prototype.outerHeight(this.scrollHandler); this.windowSize = this.scrollHandler.clientHeight; //returns height without DIV scrollbar this.tableParentOffset = 0; } this.windowScrollPosition = this.getScrollPosition(); }; //readSettings (in future merge it with this.prepare?) WalkontableVerticalScrollbarNative.prototype.readSettings = function () { this.offset = this.instance.getSetting('offsetRow'); this.total = this.instance.getSetting('totalRows'); }; function WalkontableScrollbars(instance) { this.instance = instance; if (instance.getSetting('nativeScrollbars')) { instance.update('scrollbarWidth', instance.wtDom.getScrollbarWidth()); instance.update('scrollbarHeight', instance.wtDom.getScrollbarWidth()); this.vertical = new WalkontableVerticalScrollbarNative(instance); this.horizontal = new WalkontableHorizontalScrollbarNative(instance); this.corner = new WalkontableCornerScrollbarNative(instance); if (instance.getSetting('debug')) { this.debug = new WalkontableDebugOverlay(instance); } this.registerListeners(); } else { this.vertical = new WalkontableVerticalScrollbar(instance); this.horizontal = new WalkontableHorizontalScrollbar(instance); } } WalkontableScrollbars.prototype.registerListeners = function () { var that = this; var oldVerticalScrollPosition , oldHorizontalScrollPosition , oldBoxTop , oldBoxLeft , oldBoxWidth , oldBoxHeight; function refreshAll() { if (!that.instance.wtTable.holder.parentNode) { //Walkontable was detached from DOM, but this handler was not removed that.destroy(); return; } that.vertical.windowScrollPosition = that.vertical.getScrollPosition(); that.horizontal.windowScrollPosition = that.horizontal.getScrollPosition(); that.box = that.instance.wtTable.hider.getBoundingClientRect(); if((that.box.width !== oldBoxWidth || that.box.height !== oldBoxHeight) && that.instance.rowHeightCache) { //that.instance.rowHeightCache.length = 0; //at this point the cached row heights may be invalid, but it is better not to reset the cache, which could cause scrollbar jumping when there are multiline cells outside of the rendered part of the table oldBoxWidth = that.box.width; oldBoxHeight = that.box.height; that.instance.draw(); } if (that.vertical.windowScrollPosition !== oldVerticalScrollPosition || that.horizontal.windowScrollPosition !== oldHorizontalScrollPosition || that.box.top !== oldBoxTop || that.box.left !== oldBoxLeft) { that.vertical.onScroll(); that.horizontal.onScroll(); //it's done here to make sure that all onScroll's are executed before changing styles that.vertical.react(); that.horizontal.react(); //it's done here to make sure that all onScroll's are executed before changing styles oldVerticalScrollPosition = that.vertical.windowScrollPosition; oldHorizontalScrollPosition = that.horizontal.windowScrollPosition; oldBoxTop = that.box.top; oldBoxLeft = that.box.left; } } var $window = $(window); this.vertical.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll); if (this.vertical.scrollHandler !== this.horizontal.scrollHandler) { this.horizontal.$scrollHandler.on('scroll.' + this.instance.guid, refreshAll); } if (this.vertical.scrollHandler !== window && this.horizontal.scrollHandler !== window) { $window.on('scroll.' + this.instance.guid, refreshAll); } $window.on('load.' + this.instance.guid, refreshAll); $window.on('resize.' + this.instance.guid, refreshAll); $(document).on('ready.' + this.instance.guid, refreshAll); setInterval(refreshAll, 100); //Marcin - only idea I have to reposition scrollbars on CSS change of the container (container was moved using some styles after page was loaded) }; WalkontableScrollbars.prototype.destroy = function () { this.vertical && this.vertical.destroy(); this.horizontal && this.horizontal.destroy(); }; WalkontableScrollbars.prototype.refresh = function (selectionsOnly) { this.horizontal && this.horizontal.readSettings(); this.vertical && this.vertical.readSettings(); this.horizontal && this.horizontal.prepare(); this.vertical && this.vertical.prepare(); this.horizontal && this.horizontal.refresh(selectionsOnly); this.vertical && this.vertical.refresh(selectionsOnly); this.corner && this.corner.refresh(selectionsOnly); this.debug && this.debug.refresh(selectionsOnly); }; function WalkontableSelection(instance, settings) { this.instance = instance; this.settings = settings; this.selected = []; if (settings.border) { this.border = new WalkontableBorder(instance, settings); } } WalkontableSelection.prototype.add = function (coords) { this.selected.push(coords); }; WalkontableSelection.prototype.clear = function () { this.selected.length = 0; //http://jsperf.com/clear-arrayxxx }; /** * Returns the top left (TL) and bottom right (BR) selection coordinates * @returns {Object} */ WalkontableSelection.prototype.getCorners = function () { var minRow , minColumn , maxRow , maxColumn , i , ilen = this.selected.length; if (ilen > 0) { minRow = maxRow = this.selected[0][0]; minColumn = maxColumn = this.selected[0][1]; if (ilen > 1) { for (i = 1; i < ilen; i++) { if (this.selected[i][0] < minRow) { minRow = this.selected[i][0]; } else if (this.selected[i][0] > maxRow) { maxRow = this.selected[i][0]; } if (this.selected[i][1] < minColumn) { minColumn = this.selected[i][1]; } else if (this.selected[i][1] > maxColumn) { maxColumn = this.selected[i][1]; } } } } return [minRow, minColumn, maxRow, maxColumn]; }; WalkontableSelection.prototype.draw = function () { var corners, r, c, source_r, source_c; var visibleRows = this.instance.wtTable.rowStrategy.countVisible() , visibleColumns = this.instance.wtTable.columnStrategy.countVisible(); if (this.selected.length) { corners = this.getCorners(); for (r = 0; r < visibleRows; r++) { for (c = 0; c < visibleColumns; c++) { source_r = this.instance.wtTable.rowFilter.visibleToSource(r); source_c = this.instance.wtTable.columnFilter.visibleToSource(c); if (source_r >= corners[0] && source_r <= corners[2] && source_c >= corners[1] && source_c <= corners[3]) { //selected cell this.instance.wtTable.currentCellCache.add(r, c, this.settings.className); } else if (source_r >= corners[0] && source_r <= corners[2]) { //selection is in this row this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightRowClassName); } else if (source_c >= corners[1] && source_c <= corners[3]) { //selection is in this column this.instance.wtTable.currentCellCache.add(r, c, this.settings.highlightColumnClassName); } } } this.border && this.border.appear(corners); //warning! border.appear modifies corners! } else { this.border && this.border.disappear(); } }; function WalkontableSettings(instance, settings) { var that = this; this.instance = instance; //default settings. void 0 means it is required, null means it can be empty this.defaults = { table: void 0, debug: false, //shows WalkontableDebugOverlay //presentation mode scrollH: 'auto', //values: scroll (always show scrollbar), auto (show scrollbar if table does not fit in the container), none (never show scrollbar) scrollV: 'auto', //values: see above nativeScrollbars: false, //values: false (dragdealer), true (native) stretchH: 'hybrid', //values: hybrid, all, last, none currentRowClassName: null, currentColumnClassName: null, //data source data: void 0, offsetRow: 0, offsetColumn: 0, fixedColumnsLeft: 0, fixedRowsTop: 0, rowHeaders: function () { return [] }, //this must be array of functions: [function (row, TH) {}] columnHeaders: function () { return [] }, //this must be array of functions: [function (column, TH) {}] totalRows: void 0, totalColumns: void 0, width: null, height: null, cellRenderer: function (row, column, TD) { var cellData = that.getSetting('data', row, column); that.instance.wtDom.fastInnerText(TD, cellData === void 0 || cellData === null ? '' : cellData); }, columnWidth: 50, selections: null, hideBorderOnMouseDownOver: false, //callbacks onCellMouseDown: null, onCellMouseOver: null, // onCellMouseOut: null, onCellDblClick: null, onCellCornerMouseDown: null, onCellCornerDblClick: null, beforeDraw: null, onDraw: null, onScrollVertically: null, onScrollHorizontally: null, //constants scrollbarWidth: 10, scrollbarHeight: 10 }; //reference to settings this.settings = {}; for (var i in this.defaults) { if (this.defaults.hasOwnProperty(i)) { if (settings[i] !== void 0) { this.settings[i] = settings[i]; } else if (this.defaults[i] === void 0) { throw new Error('A required setting "' + i + '" was not provided'); } else { this.settings[i] = this.defaults[i]; } } } } /** * generic methods */ WalkontableSettings.prototype.update = function (settings, value) { if (value === void 0) { //settings is object for (var i in settings) { if (settings.hasOwnProperty(i)) { this.settings[i] = settings[i]; } } } else { //if value is defined then settings is the key this.settings[settings] = value; } return this.instance; }; WalkontableSettings.prototype.getSetting = function (key, param1, param2, param3) { if (this[key]) { return this[key](param1, param2, param3); } else { return this._getSetting(key, param1, param2, param3); } }; WalkontableSettings.prototype._getSetting = function (key, param1, param2, param3) { if (typeof this.settings[key] === 'function') { return this.settings[key](param1, param2, param3); } else if (param1 !== void 0 && Object.prototype.toString.call(this.settings[key]) === '[object Array]') { return this.settings[key][param1]; } else { return this.settings[key]; } }; WalkontableSettings.prototype.has = function (key) { return !!this.settings[key] }; /** * specific methods */ WalkontableSettings.prototype.rowHeight = function (row, TD) { if (!this.instance.rowHeightCache) { this.instance.rowHeightCache = []; //hack. This cache is being invalidated in WOT core.js } if (this.instance.rowHeightCache[row] === void 0) { var size = 23; //guess if (TD) { size = this.instance.wtDom.outerHeight(TD); //measure this.instance.rowHeightCache[row] = size; //cache only something we measured } return size; } else { return this.instance.rowHeightCache[row]; } }; function WalkontableTable(instance, table) { //reference to instance this.instance = instance; this.TABLE = table; this.wtDom = this.instance.wtDom; this.wtDom.removeTextNodes(this.TABLE); //wtSpreader var parent = this.TABLE.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var spreader = document.createElement('DIV'); spreader.className = 'wtSpreader'; if (parent) { parent.insertBefore(spreader, this.TABLE); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } spreader.appendChild(this.TABLE); } this.spreader = this.TABLE.parentNode; //wtHider parent = this.spreader.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var hider = document.createElement('DIV'); hider.className = 'wtHider'; if (parent) { parent.insertBefore(hider, this.spreader); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } hider.appendChild(this.spreader); } this.hider = this.spreader.parentNode; this.hiderStyle = this.hider.style; this.hiderStyle.position = 'relative'; //wtHolder parent = this.hider.parentNode; if (!parent || parent.nodeType !== 1 || !this.wtDom.hasClass(parent, 'wtHolder')) { var holder = document.createElement('DIV'); holder.style.position = 'relative'; holder.className = 'wtHolder'; if (parent) { parent.insertBefore(holder, this.hider); //if TABLE is detached (e.g. in Jasmine test), it has no parentNode so we cannot attach holder to it } holder.appendChild(this.hider); } this.holder = this.hider.parentNode; //bootstrap from settings this.TBODY = this.TABLE.getElementsByTagName('TBODY')[0]; if (!this.TBODY) { this.TBODY = document.createElement('TBODY'); this.TABLE.appendChild(this.TBODY); } this.THEAD = this.TABLE.getElementsByTagName('THEAD')[0]; if (!this.THEAD) { this.THEAD = document.createElement('THEAD'); this.TABLE.insertBefore(this.THEAD, this.TBODY); } this.COLGROUP = this.TABLE.getElementsByTagName('COLGROUP')[0]; if (!this.COLGROUP) { this.COLGROUP = document.createElement('COLGROUP'); this.TABLE.insertBefore(this.COLGROUP, this.THEAD); } if (this.instance.getSetting('columnHeaders').length) { if (!this.THEAD.childNodes.length) { var TR = document.createElement('TR'); this.THEAD.appendChild(TR); } } this.colgroupChildrenLength = this.COLGROUP.childNodes.length; this.theadChildrenLength = this.THEAD.firstChild ? this.THEAD.firstChild.childNodes.length : 0; this.tbodyChildrenLength = this.TBODY.childNodes.length; this.oldCellCache = new WalkontableClassNameCache(); this.currentCellCache = new WalkontableClassNameCache(); this.rowFilter = new WalkontableRowFilter(); this.columnFilter = new WalkontableColumnFilter(); this.verticalRenderReverse = false; } WalkontableTable.prototype.refreshHiderDimensions = function () { var height = this.instance.wtViewport.getWorkspaceHeight(); var width = this.instance.wtViewport.getWorkspaceWidth(); var spreaderStyle = this.spreader.style; if ((height !== Infinity || width !== Infinity) && !this.instance.getSetting('nativeScrollbars')) { if (height === Infinity) { height = this.instance.wtViewport.getWorkspaceActualHeight(); } if (width === Infinity) { width = this.instance.wtViewport.getWorkspaceActualWidth(); } this.hiderStyle.overflow = 'hidden'; spreaderStyle.position = 'absolute'; spreaderStyle.top = '0'; spreaderStyle.left = '0'; if (!this.instance.getSetting('nativeScrollbars')) { spreaderStyle.height = '4000px'; spreaderStyle.width = '4000px'; } if (height < 0) { //this happens with WalkontableOverlay and causes "Invalid argument" error in IE8 height = 0; } this.hiderStyle.height = height + 'px'; this.hiderStyle.width = width + 'px'; } else { spreaderStyle.position = 'relative'; spreaderStyle.width = 'auto'; spreaderStyle.height = 'auto'; } }; WalkontableTable.prototype.refreshStretching = function () { if (this.instance.cloneSource) { return; } var instance = this.instance , stretchH = instance.getSetting('stretchH') , totalRows = instance.getSetting('totalRows') , totalColumns = instance.getSetting('totalColumns') , offsetColumn = instance.getSetting('offsetColumn'); var containerWidthFn = function (cacheWidth) { var viewportWidth = that.instance.wtViewport.getViewportWidth(cacheWidth); if (viewportWidth < cacheWidth && that.instance.getSetting('nativeScrollbars')) { return Infinity; //disable stretching when viewport is bigger than sum of the cell widths } return viewportWidth; }; var that = this; var columnWidthFn = function (i) { var source_c = that.columnFilter.visibleToSource(i); if (source_c < totalColumns) { return instance.getSetting('columnWidth', source_c); } }; if (stretchH === 'hybrid') { if (offsetColumn > 0) { stretchH = 'last'; } else { stretchH = 'none'; } } var containerHeightFn = function (cacheHeight) { if (that.instance.getSetting('nativeScrollbars')) { if (that.instance.cloneOverlay instanceof WalkontableDebugOverlay) { return Infinity; } else { return 2 * that.instance.wtViewport.getViewportHeight(cacheHeight); } } return that.instance.wtViewport.getViewportHeight(cacheHeight); }; var rowHeightFn = function (i, TD) { if (that.instance.getSetting('nativeScrollbars')) { return 20; } var source_r = that.rowFilter.visibleToSource(i); if (source_r < totalRows) { if (that.verticalRenderReverse && i === 0) { return that.instance.getSetting('rowHeight', source_r, TD) - 1; } else { return that.instance.getSetting('rowHeight', source_r, TD); } } }; this.columnStrategy = new WalkontableColumnStrategy(instance, containerWidthFn, columnWidthFn, stretchH); this.rowStrategy = new WalkontableRowStrategy(instance, containerHeightFn, rowHeightFn); }; WalkontableTable.prototype.adjustAvailableNodes = function () { var displayTds , rowHeaders = this.instance.getSetting('rowHeaders') , displayThs = rowHeaders.length , columnHeaders = this.instance.getSetting('columnHeaders') , TR , TD , c; //adjust COLGROUP while (this.colgroupChildrenLength < displayThs) { this.COLGROUP.appendChild(document.createElement('COL')); this.colgroupChildrenLength++; } this.refreshStretching(); //actually it is wrong position because it assumes rowHeader would be always 50px wide (because we measure before it is filled with text). TODO: debug if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) { displayTds = this.instance.getSetting('fixedColumnsLeft'); } else { displayTds = this.columnStrategy.cellCount; } //adjust COLGROUP while (this.colgroupChildrenLength < displayTds + displayThs) { this.COLGROUP.appendChild(document.createElement('COL')); this.colgroupChildrenLength++; } while (this.colgroupChildrenLength > displayTds + displayThs) { this.COLGROUP.removeChild(this.COLGROUP.lastChild); this.colgroupChildrenLength--; } //adjust THEAD TR = this.THEAD.firstChild; if (columnHeaders.length) { if (!TR) { TR = document.createElement('TR'); this.THEAD.appendChild(TR); } this.theadChildrenLength = TR.childNodes.length; while (this.theadChildrenLength < displayTds + displayThs) { TR.appendChild(document.createElement('TH')); this.theadChildrenLength++; } while (this.theadChildrenLength > displayTds + displayThs) { TR.removeChild(TR.lastChild); this.theadChildrenLength--; } } else if (TR) { this.wtDom.empty(TR); } //draw COLGROUP for (c = 0; c < this.colgroupChildrenLength; c++) { if (c < displayThs) { this.wtDom.addClass(this.COLGROUP.childNodes[c], 'rowHeader'); } else { this.wtDom.removeClass(this.COLGROUP.childNodes[c], 'rowHeader'); } } //draw THEAD if (columnHeaders.length) { TR = this.THEAD.firstChild; if (displayThs) { TD = TR.firstChild; //actually it is TH but let's reuse single variable for (c = 0; c < displayThs; c++) { rowHeaders[c](-displayThs + c, TD); TD = TD.nextSibling; } } } for (c = 0; c < displayTds; c++) { if (columnHeaders.length) { columnHeaders[0](this.columnFilter.visibleToSource(c), TR.childNodes[displayThs + c]); } } }; WalkontableTable.prototype.adjustColumns = function (TR, desiredCount) { var count = TR.childNodes.length; while (count < desiredCount) { var TD = document.createElement('TD'); TR.appendChild(TD); count++; } while (count > desiredCount) { TR.removeChild(TR.lastChild); count--; } }; WalkontableTable.prototype.draw = function (selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { this.verticalRenderReverse = false; //this is only supported in dragdealer mode, not in native } this.rowFilter.readSettings(this.instance); this.columnFilter.readSettings(this.instance); if (!selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { if (this.instance.cloneSource) { this.tableOffset = this.instance.cloneSource.wtTable.tableOffset; } else { this.holderOffset = this.wtDom.offset(this.holder); this.tableOffset = this.wtDom.offset(this.TABLE); this.instance.wtScrollbars.vertical.readWindowSize(); this.instance.wtScrollbars.horizontal.readWindowSize(); this.instance.wtViewport.resetSettings(); } } else { this.tableOffset = this.wtDom.offset(this.TABLE); this.instance.wtViewport.resetSettings(); } this._doDraw(); } else { this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(true); } this.refreshPositions(selectionsOnly); if (!selectionsOnly) { if (this.instance.getSetting('nativeScrollbars')) { if (!this.instance.cloneSource) { this.instance.wtScrollbars.vertical.resetFixedPosition(); this.instance.wtScrollbars.horizontal.resetFixedPosition(); this.instance.wtScrollbars.corner.resetFixedPosition(); this.instance.wtScrollbars.debug && this.instance.wtScrollbars.debug.resetFixedPosition(); } } } this.instance.drawn = true; return this; }; WalkontableTable.prototype._doDraw = function () { var r = 0 , source_r , c , source_c , offsetRow = this.instance.getSetting('offsetRow') , totalRows = this.instance.getSetting('totalRows') , totalColumns = this.instance.getSetting('totalColumns') , displayTds , rowHeaders = this.instance.getSetting('rowHeaders') , displayThs = rowHeaders.length , TR , TD , TH , adjusted = false , workspaceWidth , mustBeInViewport , res; if (this.verticalRenderReverse) { mustBeInViewport = offsetRow; } var noPartial = false; if (this.verticalRenderReverse) { if (offsetRow === totalRows - this.rowFilter.fixedCount - 1) { noPartial = true; } else { this.instance.update('offsetRow', offsetRow + 1); //if we are scrolling reverse this.rowFilter.readSettings(this.instance); } } if (this.instance.cloneSource) { this.columnStrategy = this.instance.cloneSource.wtTable.columnStrategy; this.rowStrategy = this.instance.cloneSource.wtTable.rowStrategy; } //draw TBODY if (totalColumns > 0) { source_r = this.rowFilter.visibleToSource(r); var fixedRowsTop = this.instance.getSetting('fixedRowsTop'); var cloneLimit; if (this.instance.cloneSource) { //must be run after adjustAvailableNodes because otherwise this.rowStrategy is not yet defined if (this.instance.cloneOverlay instanceof WalkontableVerticalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative) { cloneLimit = fixedRowsTop; } else if (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative) { cloneLimit = this.rowStrategy.countVisible(); } //else if WalkontableDebugOverlay do nothing. No cloneLimit means render ALL rows } this.adjustAvailableNodes(); adjusted = true; if (this.instance.cloneSource && (this.instance.cloneOverlay instanceof WalkontableHorizontalScrollbarNative || this.instance.cloneOverlay instanceof WalkontableCornerScrollbarNative)) { displayTds = this.instance.getSetting('fixedColumnsLeft'); } else { displayTds = this.columnStrategy.cellCount; } if (!this.instance.cloneSource) { workspaceWidth = this.instance.wtViewport.getWorkspaceWidth(); this.columnStrategy.stretch(); } for (c = 0; c < displayTds; c++) { this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px'; } while (source_r < totalRows && source_r >= 0) { if (r > 1000) { throw new Error('Security brake: Too much TRs. Please define height for your table, which will enforce scrollbars.'); } if (cloneLimit !== void 0 && r === cloneLimit) { break; //we have as much rows as needed for this clone } if (r >= this.tbodyChildrenLength || (this.verticalRenderReverse && r >= this.rowFilter.fixedCount)) { TR = document.createElement('TR'); for (c = 0; c < displayThs; c++) { TR.appendChild(document.createElement('TH')); } if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) { this.TBODY.insertBefore(TR, this.TBODY.childNodes[this.rowFilter.fixedCount] || this.TBODY.firstChild); } else { this.TBODY.appendChild(TR); } this.tbodyChildrenLength++; } else if (r === 0) { TR = this.TBODY.firstChild; } else { TR = TR.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } //TH TH = TR.firstChild; for (c = 0; c < displayThs; c++) { //If the number of row headers increased we need to replace TD with TH if (TH.nodeName == 'TD') { TD = TH; TH = document.createElement('TH'); TR.insertBefore(TH, TD); TR.removeChild(TD); } rowHeaders[c](source_r, TH); //actually TH TH = TH.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } this.adjustColumns(TR, displayTds + displayThs); for (c = 0; c < displayTds; c++) { source_c = this.columnFilter.visibleToSource(c); if (c === 0) { TD = TR.childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(source_c)]; } else { TD = TD.nextSibling; //http://jsperf.com/nextsibling-vs-indexed-childnodes } //If the number of headers has been reduced, we need to replace excess TH with TD if (TD.nodeName == 'TH') { TH = TD; TD = document.createElement('TD'); TR.insertBefore(TD, TH); TR.removeChild(TH); } TD.className = ''; TD.removeAttribute('style'); this.instance.getSetting('cellRenderer', source_r, source_c, TD); } offsetRow = this.instance.getSetting('offsetRow'); //refresh the value //after last column is rendered, check if last cell is fully displayed if (this.verticalRenderReverse && noPartial) { if (-this.wtDom.outerHeight(TR.firstChild) < this.rowStrategy.remainingSize) { this.TBODY.removeChild(TR); this.instance.update('offsetRow', offsetRow + 1); this.tbodyChildrenLength--; this.rowFilter.readSettings(this.instance); break; } else if (!this.instance.cloneSource) { res = this.rowStrategy.add(r, TD, this.verticalRenderReverse); if (res === false) { this.rowStrategy.removeOutstanding(); } } } else if (!this.instance.cloneSource) { res = this.rowStrategy.add(r, TD, this.verticalRenderReverse); if (res === false) { if (!this.instance.getSetting('nativeScrollbars')) { this.rowStrategy.removeOutstanding(); } } if (this.rowStrategy.isLastIncomplete()) { if (this.verticalRenderReverse && !this.isRowInViewport(mustBeInViewport)) { //we failed because one of the cells was by far too large. Recover by rendering from top this.verticalRenderReverse = false; this.instance.update('offsetRow', mustBeInViewport); this.draw(); return; } break; } } if (this.instance.getSetting('nativeScrollbars')) { if (this.instance.cloneSource) { TR.style.height = this.instance.getSetting('rowHeight', source_r) + 'px'; //if I have 2 fixed columns with one-line content and the 3rd column has a multiline content, this is the way to make sure that the overlay will has same row height } else { this.instance.getSetting('rowHeight', source_r, TD); //this trick saves rowHeight in rowHeightCache. It is then read in WalkontableVerticalScrollbarNative.prototype.sumCellSizes and reset in Walkontable constructor } } if (this.verticalRenderReverse && r >= this.rowFilter.fixedCount) { if (offsetRow === 0) { break; } this.instance.update('offsetRow', offsetRow - 1); this.rowFilter.readSettings(this.instance); } else { r++; } source_r = this.rowFilter.visibleToSource(r); } } if (!adjusted) { this.adjustAvailableNodes(); } if (!(this.instance.cloneOverlay instanceof WalkontableDebugOverlay)) { r = this.rowStrategy.countVisible(); while (this.tbodyChildrenLength > r) { this.TBODY.removeChild(this.TBODY.lastChild); this.tbodyChildrenLength--; } } this.instance.wtScrollbars && this.instance.wtScrollbars.refresh(false); if (!this.instance.cloneSource) { if (workspaceWidth !== this.instance.wtViewport.getWorkspaceWidth()) { //workspace width changed though to shown/hidden vertical scrollbar. Let's reapply stretching this.columnStrategy.stretch(); for (c = 0; c < this.columnStrategy.cellCount; c++) { this.COLGROUP.childNodes[c + displayThs].style.width = this.columnStrategy.getSize(c) + 'px'; } } } this.verticalRenderReverse = false; }; WalkontableTable.prototype.refreshPositions = function (selectionsOnly) { this.refreshHiderDimensions(); this.refreshSelections(selectionsOnly); }; WalkontableTable.prototype.refreshSelections = function (selectionsOnly) { var vr , r , vc , c , s , slen , classNames = [] , visibleRows = this.rowStrategy.countVisible() , visibleColumns = this.columnStrategy.countVisible(); this.oldCellCache = this.currentCellCache; this.currentCellCache = new WalkontableClassNameCache(); if (this.instance.selections) { for (r in this.instance.selections) { if (this.instance.selections.hasOwnProperty(r)) { this.instance.selections[r].draw(); if (this.instance.selections[r].settings.className) { classNames.push(this.instance.selections[r].settings.className); } if (this.instance.selections[r].settings.highlightRowClassName) { classNames.push(this.instance.selections[r].settings.highlightRowClassName); } if (this.instance.selections[r].settings.highlightColumnClassName) { classNames.push(this.instance.selections[r].settings.highlightColumnClassName); } } } } slen = classNames.length; for (vr = 0; vr < visibleRows; vr++) { for (vc = 0; vc < visibleColumns; vc++) { r = this.rowFilter.visibleToSource(vr); c = this.columnFilter.visibleToSource(vc); for (s = 0; s < slen; s++) { if (this.currentCellCache.test(vr, vc, classNames[s])) { this.wtDom.addClass(this.getCell([r, c]), classNames[s]); } else if (selectionsOnly && this.oldCellCache.test(vr, vc, classNames[s])) { this.wtDom.removeClass(this.getCell([r, c]), classNames[s]); } } } } }; /** * getCell * @param {Array} coords * @return {Object} HTMLElement on success or {Number} one of the exit codes on error: * -1 row before viewport * -2 row after viewport * -3 column before viewport * -4 column after viewport * */ WalkontableTable.prototype.getCell = function (coords) { if (this.isRowBeforeViewport(coords[0])) { return -1; //row before viewport } else if (this.isRowAfterViewport(coords[0])) { return -2; //row after viewport } else { if (this.isColumnBeforeViewport(coords[1])) { return -3; //column before viewport } else if (this.isColumnAfterViewport(coords[1])) { return -4; //column after viewport } else { return this.TBODY.childNodes[this.rowFilter.sourceToVisible(coords[0])].childNodes[this.columnFilter.sourceColumnToVisibleRowHeadedColumn(coords[1])]; } } }; WalkontableTable.prototype.getCoords = function (TD) { return [ this.rowFilter.visibleToSource(this.wtDom.index(TD.parentNode)), this.columnFilter.visibleRowHeadedColumnToSourceColumn(TD.cellIndex) ]; }; //returns -1 if no row is visible WalkontableTable.prototype.getLastVisibleRow = function () { return this.rowFilter.visibleToSource(this.rowStrategy.cellCount - 1); }; //returns -1 if no column is visible WalkontableTable.prototype.getLastVisibleColumn = function () { return this.columnFilter.visibleToSource(this.columnStrategy.cellCount - 1); }; WalkontableTable.prototype.isRowBeforeViewport = function (r) { return (this.rowFilter.sourceToVisible(r) < this.rowFilter.fixedCount && r >= this.rowFilter.fixedCount); }; WalkontableTable.prototype.isRowAfterViewport = function (r) { return (r > this.getLastVisibleRow()); }; WalkontableTable.prototype.isColumnBeforeViewport = function (c) { return (this.columnFilter.sourceToVisible(c) < this.columnFilter.fixedCount && c >= this.columnFilter.fixedCount); }; WalkontableTable.prototype.isColumnAfterViewport = function (c) { return (c > this.getLastVisibleColumn()); }; WalkontableTable.prototype.isRowInViewport = function (r) { return (!this.isRowBeforeViewport(r) && !this.isRowAfterViewport(r)); }; WalkontableTable.prototype.isColumnInViewport = function (c) { return (!this.isColumnBeforeViewport(c) && !this.isColumnAfterViewport(c)); }; WalkontableTable.prototype.isLastRowFullyVisible = function () { return (this.getLastVisibleRow() === this.instance.getSetting('totalRows') - 1 && !this.rowStrategy.isLastIncomplete()); }; WalkontableTable.prototype.isLastColumnFullyVisible = function () { return (this.getLastVisibleColumn() === this.instance.getSetting('totalColumns') - 1 && !this.columnStrategy.isLastIncomplete()); }; function WalkontableViewport(instance) { this.instance = instance; this.resetSettings(); if (this.instance.getSetting('nativeScrollbars')) { var that = this; $(window).on('resize', function () { that.clientHeight = that.getWorkspaceHeight(); }); } } /*WalkontableViewport.prototype.isInSightVertical = function () { //is table outside viewport bottom edge if (tableTop > windowHeight + scrollTop) { return -1; } //is table outside viewport top edge else if (scrollTop > tableTop + tableFakeHeight) { return -2; } //table is in viewport but how much exactly? else { } };*/ //used by scrollbar WalkontableViewport.prototype.getWorkspaceHeight = function (proposedHeight) { if (this.instance.getSetting('nativeScrollbars')) { return this.instance.wtScrollbars.vertical.windowSize; } var height = this.instance.getSetting('height'); if (height === Infinity || height === void 0 || height === null || height < 1) { if (this.instance.wtScrollbars.vertical instanceof WalkontableOverlay) { height = this.instance.wtScrollbars.vertical.availableSize(); } else { height = Infinity; } } if (height !== Infinity) { if (proposedHeight >= height) { height -= this.instance.getSetting('scrollbarHeight'); } else if (this.instance.wtScrollbars.horizontal.visible) { height -= this.instance.getSetting('scrollbarHeight'); } } return height; }; WalkontableViewport.prototype.getWorkspaceWidth = function (proposedWidth) { var width = this.instance.getSetting('width'); if (width === Infinity || width === void 0 || width === null || width < 1) { if (this.instance.wtScrollbars.horizontal instanceof WalkontableOverlay) { width = this.instance.wtScrollbars.horizontal.availableSize(); } else { width = Infinity; } } if (width !== Infinity) { if (proposedWidth >= width) { width -= this.instance.getSetting('scrollbarWidth'); } else if (this.instance.wtScrollbars.vertical.visible) { width -= this.instance.getSetting('scrollbarWidth'); } } return width; }; WalkontableViewport.prototype.getWorkspaceActualHeight = function () { return this.instance.wtDom.outerHeight(this.instance.wtTable.TABLE); }; WalkontableViewport.prototype.getWorkspaceActualWidth = function () { return this.instance.wtDom.outerWidth(this.instance.wtTable.TABLE) || this.instance.wtDom.outerWidth(this.instance.wtTable.TBODY) || this.instance.wtDom.outerWidth(this.instance.wtTable.THEAD); //IE8 reports 0 as <table> offsetWidth; }; WalkontableViewport.prototype.getColumnHeaderHeight = function () { if (isNaN(this.columnHeaderHeight)) { var cellOffset = this.instance.wtDom.offset(this.instance.wtTable.TBODY) , tableOffset = this.instance.wtTable.tableOffset; this.columnHeaderHeight = cellOffset.top - tableOffset.top; } return this.columnHeaderHeight; }; WalkontableViewport.prototype.getViewportHeight = function (proposedHeight) { var containerHeight = this.getWorkspaceHeight(proposedHeight); if (containerHeight === Infinity) { return containerHeight; } var columnHeaderHeight = this.getColumnHeaderHeight(); if (columnHeaderHeight > 0) { return containerHeight - columnHeaderHeight; } else { return containerHeight; } }; WalkontableViewport.prototype.getRowHeaderWidth = function () { if (this.instance.cloneSource) { return this.instance.cloneSource.wtViewport.getRowHeaderWidth(); } if (isNaN(this.rowHeaderWidth)) { var rowHeaders = this.instance.getSetting('rowHeaders'); if (rowHeaders.length) { var TH = this.instance.wtTable.TABLE.querySelector('TH'); this.rowHeaderWidth = 0; for (var i = 0, ilen = rowHeaders.length; i < ilen; i++) { if (TH) { this.rowHeaderWidth += this.instance.wtDom.outerWidth(TH); TH = TH.nextSibling; } else { this.rowHeaderWidth += 50; //yes this is a cheat but it worked like that before, just taking assumption from CSS instead of measuring. TODO: proper fix } } } else { this.rowHeaderWidth = 0; } } return this.rowHeaderWidth; }; WalkontableViewport.prototype.getViewportWidth = function (proposedWidth) { var containerWidth = this.getWorkspaceWidth(proposedWidth); if (containerWidth === Infinity) { return containerWidth; } var rowHeaderWidth = this.getRowHeaderWidth(); if (rowHeaderWidth > 0) { return containerWidth - rowHeaderWidth; } else { return containerWidth; } }; WalkontableViewport.prototype.resetSettings = function () { this.rowHeaderWidth = NaN; this.columnHeaderHeight = NaN; }; function WalkontableWheel(instance) { if (instance.getSetting('nativeScrollbars')) { return; } //spreader === instance.wtTable.TABLE.parentNode $(instance.wtTable.spreader).on('mousewheel', function (event, delta, deltaX, deltaY) { if (!deltaX && !deltaY && delta) { //we are in IE8, see https://github.com/brandonaaron/jquery-mousewheel/issues/53 deltaY = delta; } if (!deltaX && !deltaY) { //this happens in IE8 test case return; } if (deltaY > 0 && instance.getSetting('offsetRow') === 0) { return; //attempt to scroll up when it's already showing first row } else if (deltaY < 0 && instance.wtTable.isLastRowFullyVisible()) { return; //attempt to scroll down when it's already showing last row } else if (deltaX < 0 && instance.getSetting('offsetColumn') === 0) { return; //attempt to scroll left when it's already showing first column } else if (deltaX > 0 && instance.wtTable.isLastColumnFullyVisible()) { return; //attempt to scroll right when it's already showing last column } //now we are sure we really want to scroll clearTimeout(instance.wheelTimeout); instance.wheelTimeout = setTimeout(function () { //timeout is needed because with fast-wheel scrolling mousewheel event comes dozen times per second if (deltaY) { //ceil is needed because jquery-mousewheel reports fractional mousewheel deltas on touchpad scroll //see http://stackoverflow.com/questions/5527601/normalizing-mousewheel-speed-across-browsers if (instance.wtScrollbars.vertical.visible) { // if we see scrollbar instance.scrollVertical(-Math.ceil(deltaY)).draw(); } } else if (deltaX) { if (instance.wtScrollbars.horizontal.visible) { // if we see scrollbar instance.scrollHorizontal(Math.ceil(deltaX)).draw(); } } }, 0); event.preventDefault(); }); } /** * Dragdealer JS v0.9.5 - patched by Walkontable at lines 66, 309-310, 339-340 * http://code.ovidiu.ch/dragdealer-js * * Copyright (c) 2010, Ovidiu Chereches * MIT License * http://legal.ovidiu.ch/licenses/MIT */ /* Cursor */ var Cursor = { x: 0, y: 0, init: function() { this.setEvent('mouse'); this.setEvent('touch'); }, setEvent: function(type) { var moveHandler = document['on' + type + 'move'] || function(){}; document['on' + type + 'move'] = function(e) { moveHandler(e); Cursor.refresh(e); } }, refresh: function(e) { if(!e) { e = window.event; } if(e.type == 'mousemove') { this.set(e); } else if(e.touches) { this.set(e.touches[0]); } }, set: function(e) { if(e.pageX || e.pageY) { this.x = e.pageX; this.y = e.pageY; } else if(document.body && (e.clientX || e.clientY)) //need to check whether body exists, because of IE8 issue (#1084) { this.x = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; this.y = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } } }; Cursor.init(); /* Position */ var Position = { get: function(obj) { var curtop = 0, curleft = 0; //Walkontable patch. Original (var curleft = curtop = 0;) created curtop in global scope if(obj.offsetParent) { do { curleft += obj.offsetLeft; curtop += obj.offsetTop; } while((obj = obj.offsetParent)); } return [curleft, curtop]; } }; /* Dragdealer */ var Dragdealer = function(wrapper, options) { if(typeof(wrapper) == 'string') { wrapper = document.getElementById(wrapper); } if(!wrapper) { return; } var handle = wrapper.getElementsByTagName('div')[0]; if(!handle || handle.className.search(/(^|\s)handle(\s|$)/) == -1) { return; } this.init(wrapper, handle, options || {}); this.setup(); }; Dragdealer.prototype = { init: function(wrapper, handle, options) { this.wrapper = wrapper; this.handle = handle; this.options = options; this.disabled = this.getOption('disabled', false); this.horizontal = this.getOption('horizontal', true); this.vertical = this.getOption('vertical', false); this.slide = this.getOption('slide', true); this.steps = this.getOption('steps', 0); this.snap = this.getOption('snap', false); this.loose = this.getOption('loose', false); this.speed = this.getOption('speed', 10) / 100; this.xPrecision = this.getOption('xPrecision', 0); this.yPrecision = this.getOption('yPrecision', 0); this.callback = options.callback || null; this.animationCallback = options.animationCallback || null; this.bounds = { left: options.left || 0, right: -(options.right || 0), top: options.top || 0, bottom: -(options.bottom || 0), x0: 0, x1: 0, xRange: 0, y0: 0, y1: 0, yRange: 0 }; this.value = { prev: [-1, -1], current: [options.x || 0, options.y || 0], target: [options.x || 0, options.y || 0] }; this.offset = { wrapper: [0, 0], mouse: [0, 0], prev: [-999999, -999999], current: [0, 0], target: [0, 0] }; this.change = [0, 0]; this.activity = false; this.dragging = false; this.tapping = false; }, getOption: function(name, defaultValue) { return this.options[name] !== undefined ? this.options[name] : defaultValue; }, setup: function() { this.setWrapperOffset(); this.setBoundsPadding(); this.setBounds(); this.setSteps(); this.addListeners(); }, setWrapperOffset: function() { this.offset.wrapper = Position.get(this.wrapper); }, setBoundsPadding: function() { if(!this.bounds.left && !this.bounds.right) { this.bounds.left = Position.get(this.handle)[0] - this.offset.wrapper[0]; this.bounds.right = -this.bounds.left; } if(!this.bounds.top && !this.bounds.bottom) { this.bounds.top = Position.get(this.handle)[1] - this.offset.wrapper[1]; this.bounds.bottom = -this.bounds.top; } }, setBounds: function() { this.bounds.x0 = this.bounds.left; this.bounds.x1 = this.wrapper.offsetWidth + this.bounds.right; this.bounds.xRange = (this.bounds.x1 - this.bounds.x0) - this.handle.offsetWidth; this.bounds.y0 = this.bounds.top; this.bounds.y1 = this.wrapper.offsetHeight + this.bounds.bottom; this.bounds.yRange = (this.bounds.y1 - this.bounds.y0) - this.handle.offsetHeight; this.bounds.xStep = 1 / (this.xPrecision || Math.max(this.wrapper.offsetWidth, this.handle.offsetWidth)); this.bounds.yStep = 1 / (this.yPrecision || Math.max(this.wrapper.offsetHeight, this.handle.offsetHeight)); }, setSteps: function() { if(this.steps > 1) { this.stepRatios = []; for(var i = 0; i <= this.steps - 1; i++) { this.stepRatios[i] = i / (this.steps - 1); } } }, addListeners: function() { var self = this; this.wrapper.onselectstart = function() { return false; } this.handle.onmousedown = this.handle.ontouchstart = function(e) { self.handleDownHandler(e); }; this.wrapper.onmousedown = this.wrapper.ontouchstart = function(e) { self.wrapperDownHandler(e); }; var mouseUpHandler = document.onmouseup || function(){}; document.onmouseup = function(e) { mouseUpHandler(e); self.documentUpHandler(e); }; var touchEndHandler = document.ontouchend || function(){}; document.ontouchend = function(e) { touchEndHandler(e); self.documentUpHandler(e); }; var resizeHandler = window.onresize || function(){}; window.onresize = function(e) { resizeHandler(e); self.documentResizeHandler(e); }; this.wrapper.onmousemove = function(e) { self.activity = true; } this.wrapper.onclick = function(e) { return !self.activity; } this.interval = setInterval(function(){ self.animate() }, 25); self.animate(false, true); }, handleDownHandler: function(e) { this.activity = false; Cursor.refresh(e); this.preventDefaults(e, true); this.startDrag(); }, wrapperDownHandler: function(e) { Cursor.refresh(e); this.preventDefaults(e, true); this.startTap(); }, documentUpHandler: function(e) { this.stopDrag(); this.stopTap(); }, documentResizeHandler: function(e) { this.setWrapperOffset(); this.setBounds(); this.update(); }, enable: function() { this.disabled = false; this.handle.className = this.handle.className.replace(/\s?disabled/g, ''); }, disable: function() { this.disabled = true; this.handle.className += ' disabled'; }, setStep: function(x, y, snap) { this.setValue( this.steps && x > 1 ? (x - 1) / (this.steps - 1) : 0, this.steps && y > 1 ? (y - 1) / (this.steps - 1) : 0, snap ); }, setValue: function(x, y, snap) { this.setTargetValue([x, y || 0]); if(snap) { this.groupCopy(this.value.current, this.value.target); } }, startTap: function(target) { if(this.disabled) { return; } this.tapping = true; this.setWrapperOffset(); this.setBounds(); if(target === undefined) { target = [ Cursor.x - this.offset.wrapper[0] - (this.handle.offsetWidth / 2), Cursor.y - this.offset.wrapper[1] - (this.handle.offsetHeight / 2) ]; } this.setTargetOffset(target); }, stopTap: function() { if(this.disabled || !this.tapping) { return; } this.tapping = false; this.setTargetValue(this.value.current); this.result(); }, startDrag: function() { if(this.disabled) { return; } this.setWrapperOffset(); this.setBounds(); this.offset.mouse = [ Cursor.x - Position.get(this.handle)[0], Cursor.y - Position.get(this.handle)[1] ]; this.dragging = true; }, stopDrag: function() { if(this.disabled || !this.dragging) { return; } this.dragging = false; var target = this.groupClone(this.value.current); if(this.slide) { var ratioChange = this.change; target[0] += ratioChange[0] * 4; target[1] += ratioChange[1] * 4; } this.setTargetValue(target); this.result(); }, feedback: function() { var value = this.value.current; if(this.snap && this.steps > 1) { value = this.getClosestSteps(value); } if(!this.groupCompare(value, this.value.prev)) { if(typeof(this.animationCallback) == 'function') { this.animationCallback(value[0], value[1]); } this.groupCopy(this.value.prev, value); } }, result: function() { if(typeof(this.callback) == 'function') { this.callback(this.value.target[0], this.value.target[1]); } }, animate: function(direct, first) { if(direct && !this.dragging) { return; } if(this.dragging) { var prevTarget = this.groupClone(this.value.target); var offset = [ Cursor.x - this.offset.wrapper[0] - this.offset.mouse[0], Cursor.y - this.offset.wrapper[1] - this.offset.mouse[1] ]; this.setTargetOffset(offset, this.loose); this.change = [ this.value.target[0] - prevTarget[0], this.value.target[1] - prevTarget[1] ]; } if(this.dragging || first) { this.groupCopy(this.value.current, this.value.target); } if(this.dragging || this.glide() || first) { this.update(); this.feedback(); } }, glide: function() { var diff = [ this.value.target[0] - this.value.current[0], this.value.target[1] - this.value.current[1] ]; if(!diff[0] && !diff[1]) { return false; } if(Math.abs(diff[0]) > this.bounds.xStep || Math.abs(diff[1]) > this.bounds.yStep) { this.value.current[0] += diff[0] * this.speed; this.value.current[1] += diff[1] * this.speed; } else { this.groupCopy(this.value.current, this.value.target); } return true; }, update: function() { if(!this.snap) { this.offset.current = this.getOffsetsByRatios(this.value.current); } else { this.offset.current = this.getOffsetsByRatios( this.getClosestSteps(this.value.current) ); } this.show(); }, show: function() { if(!this.groupCompare(this.offset.current, this.offset.prev)) { if(this.horizontal) { this.handle.style.left = String(this.offset.current[0]) + 'px'; } if(this.vertical) { this.handle.style.top = String(this.offset.current[1]) + 'px'; } this.groupCopy(this.offset.prev, this.offset.current); } }, setTargetValue: function(value, loose) { var target = loose ? this.getLooseValue(value) : this.getProperValue(value); this.groupCopy(this.value.target, target); this.offset.target = this.getOffsetsByRatios(target); }, setTargetOffset: function(offset, loose) { var value = this.getRatiosByOffsets(offset); var target = loose ? this.getLooseValue(value) : this.getProperValue(value); this.groupCopy(this.value.target, target); this.offset.target = this.getOffsetsByRatios(target); }, getLooseValue: function(value) { var proper = this.getProperValue(value); return [ proper[0] + ((value[0] - proper[0]) / 4), proper[1] + ((value[1] - proper[1]) / 4) ]; }, getProperValue: function(value) { var proper = this.groupClone(value); proper[0] = Math.max(proper[0], 0); proper[1] = Math.max(proper[1], 0); proper[0] = Math.min(proper[0], 1); proper[1] = Math.min(proper[1], 1); if((!this.dragging && !this.tapping) || this.snap) { if(this.steps > 1) { proper = this.getClosestSteps(proper); } } return proper; }, getRatiosByOffsets: function(group) { return [ this.getRatioByOffset(group[0], this.bounds.xRange, this.bounds.x0), this.getRatioByOffset(group[1], this.bounds.yRange, this.bounds.y0) ]; }, getRatioByOffset: function(offset, range, padding) { return range ? (offset - padding) / range : 0; }, getOffsetsByRatios: function(group) { return [ this.getOffsetByRatio(group[0], this.bounds.xRange, this.bounds.x0), this.getOffsetByRatio(group[1], this.bounds.yRange, this.bounds.y0) ]; }, getOffsetByRatio: function(ratio, range, padding) { return Math.round(ratio * range) + padding; }, getClosestSteps: function(group) { return [ this.getClosestStep(group[0]), this.getClosestStep(group[1]) ]; }, getClosestStep: function(value) { var k = 0; var min = 1; for(var i = 0; i <= this.steps - 1; i++) { if(Math.abs(this.stepRatios[i] - value) < min) { min = Math.abs(this.stepRatios[i] - value); k = i; } } return this.stepRatios[k]; }, groupCompare: function(a, b) { return a[0] == b[0] && a[1] == b[1]; }, groupCopy: function(a, b) { a[0] = b[0]; a[1] = b[1]; }, groupClone: function(a) { return [a[0], a[1]]; }, preventDefaults: function(e, selection) { if(!e) { e = window.event; } if(e.preventDefault) { e.preventDefault(); } e.returnValue = false; if(selection && document.selection) { document.selection.empty(); } }, cancelEvent: function(e) { if(!e) { e = window.event; } if(e.stopPropagation) { e.stopPropagation(); } e.cancelBubble = true; } }; /*! Copyright (c) 2013 Brandon Aaron (http://brandonaaron.net) * Licensed under the MIT License (LICENSE.txt). * * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers. * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix. * Thanks to: Seamus Leahy for adding deltaX and deltaY * * Version: 3.1.3 * * Requires: 1.2.2+ */ (function (factory) { if ( typeof define === 'function' && define.amd ) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS style for Browserify module.exports = factory; } else { // Browser globals factory(jQuery); } }(function ($) { var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll']; var toBind = 'onwheel' in document || document.documentMode >= 9 ? ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll']; var lowestDelta, lowestDeltaXY; if ( $.event.fixHooks ) { for ( var i = toFix.length; i; ) { $.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks; } } $.event.special.mousewheel = { setup: function() { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = handler; } }, teardown: function() { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); } } else { this.onmousewheel = null; } } }; $.fn.extend({ mousewheel: function(fn) { return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, unmousewheel: function(fn) { return this.unbind("mousewheel", fn); } }); function handler(event) { var orgEvent = event || window.event, args = [].slice.call(arguments, 1), delta = 0, deltaX = 0, deltaY = 0, absDelta = 0, absDeltaXY = 0, fn; event = $.event.fix(orgEvent); event.type = "mousewheel"; // Old school scrollwheel delta if ( orgEvent.wheelDelta ) { delta = orgEvent.wheelDelta; } if ( orgEvent.detail ) { delta = orgEvent.detail * -1; } // New school wheel delta (wheel event) if ( orgEvent.deltaY ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } if ( orgEvent.deltaX ) { deltaX = orgEvent.deltaX; delta = deltaX * -1; } // Webkit if ( orgEvent.wheelDeltaY !== undefined ) { deltaY = orgEvent.wheelDeltaY; } if ( orgEvent.wheelDeltaX !== undefined ) { deltaX = orgEvent.wheelDeltaX * -1; } // Look for lowest delta to normalize the delta values absDelta = Math.abs(delta); if ( !lowestDelta || absDelta < lowestDelta ) { lowestDelta = absDelta; } absDeltaXY = Math.max(Math.abs(deltaY), Math.abs(deltaX)); if ( !lowestDeltaXY || absDeltaXY < lowestDeltaXY ) { lowestDeltaXY = absDeltaXY; } // Get a whole value for the deltas fn = delta > 0 ? 'floor' : 'ceil'; delta = Math[fn](delta / lowestDelta); deltaX = Math[fn](deltaX / lowestDeltaXY); deltaY = Math[fn](deltaY / lowestDeltaXY); // Add event and delta to the front of the arguments args.unshift(event, delta, deltaX, deltaY); return ($.event.dispatch || $.event.handle).apply(this, args); } })); })(jQuery, window, Handsontable); // numeral.js // version : 1.4.7 // author : Adam Draper // license : MIT // http://adamwdraper.github.com/Numeral-js/ (function () { /************************************ Constants ************************************/ var numeral, VERSION = '1.4.7', // internal storage for language config files languages = {}, currentLanguage = 'en', zeroFormat = null, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports); /************************************ Constructors ************************************/ // Numeral prototype object function Numeral (number) { this._n = number; } /** * Implementation of toFixed() that treats floats more like decimals * * Fixes binary rounding issues (eg. (0.615).toFixed(2) === '0.61') that present * problems for accounting- and finance-related software. */ function toFixed (value, precision, optionals) { var power = Math.pow(10, precision), output; // Multiply up by precision, round accurately, then divide and use native toFixed(): output = (Math.round(value * power) / power).toFixed(precision); if (optionals) { var optionalsRegExp = new RegExp('0{1,' + optionals + '}$'); output = output.replace(optionalsRegExp, ''); } return output; } /************************************ Formatting ************************************/ // determine what type of formatting we need to do function formatNumeral (n, format) { var output; // figure out what kind of format we are dealing with if (format.indexOf('$') > -1) { // currency!!!!! output = formatCurrency(n, format); } else if (format.indexOf('%') > -1) { // percentage output = formatPercentage(n, format); } else if (format.indexOf(':') > -1) { // time output = formatTime(n, format); } else { // plain ol' numbers or bytes output = formatNumber(n, format); } // return string return output; } // revert to number function unformatNumeral (n, string) { if (string.indexOf(':') > -1) { n._n = unformatTime(string); } else { if (string === zeroFormat) { n._n = 0; } else { var stringOriginal = string; if (languages[currentLanguage].delimiters.decimal !== '.') { string = string.replace(/\./g,'').replace(languages[currentLanguage].delimiters.decimal, '.'); } // see if abbreviations are there so that we can multiply to the correct number var thousandRegExp = new RegExp(languages[currentLanguage].abbreviations.thousand + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), millionRegExp = new RegExp(languages[currentLanguage].abbreviations.million + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), billionRegExp = new RegExp(languages[currentLanguage].abbreviations.billion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'), trillionRegExp = new RegExp(languages[currentLanguage].abbreviations.trillion + '(?:\\)|(\\' + languages[currentLanguage].currency.symbol + ')?(?:\\))?)?$'); // see if bytes are there so that we can multiply to the correct number var prefixes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], bytesMultiplier = false; for (var power = 0; power <= prefixes.length; power++) { bytesMultiplier = (string.indexOf(prefixes[power]) > -1) ? Math.pow(1024, power + 1) : false; if (bytesMultiplier) { break; } } // do some math to create our number n._n = ((bytesMultiplier) ? bytesMultiplier : 1) * ((stringOriginal.match(thousandRegExp)) ? Math.pow(10, 3) : 1) * ((stringOriginal.match(millionRegExp)) ? Math.pow(10, 6) : 1) * ((stringOriginal.match(billionRegExp)) ? Math.pow(10, 9) : 1) * ((stringOriginal.match(trillionRegExp)) ? Math.pow(10, 12) : 1) * ((string.indexOf('%') > -1) ? 0.01 : 1) * Number(((string.indexOf('(') > -1) ? '-' : '') + string.replace(/[^0-9\.-]+/g, '')); // round if we are talking about bytes n._n = (bytesMultiplier) ? Math.ceil(n._n) : n._n; } } return n._n; } function formatCurrency (n, format) { var prependSymbol = (format.indexOf('$') <= 1) ? true : false; // remove $ for the moment var space = ''; // check for space before or after currency if (format.indexOf(' $') > -1) { space = ' '; format = format.replace(' $', ''); } else if (format.indexOf('$ ') > -1) { space = ' '; format = format.replace('$ ', ''); } else { format = format.replace('$', ''); } // format the number var output = formatNumeral(n, format); // position the symbol if (prependSymbol) { if (output.indexOf('(') > -1 || output.indexOf('-') > -1) { output = output.split(''); output.splice(1, 0, languages[currentLanguage].currency.symbol + space); output = output.join(''); } else { output = languages[currentLanguage].currency.symbol + space + output; } } else { if (output.indexOf(')') > -1) { output = output.split(''); output.splice(-1, 0, space + languages[currentLanguage].currency.symbol); output = output.join(''); } else { output = output + space + languages[currentLanguage].currency.symbol; } } return output; } function formatPercentage (n, format) { var space = ''; // check for space before % if (format.indexOf(' %') > -1) { space = ' '; format = format.replace(' %', ''); } else { format = format.replace('%', ''); } n._n = n._n * 100; var output = formatNumeral(n, format); if (output.indexOf(')') > -1 ) { output = output.split(''); output.splice(-1, 0, space + '%'); output = output.join(''); } else { output = output + space + '%'; } return output; } function formatTime (n, format) { var hours = Math.floor(n._n/60/60), minutes = Math.floor((n._n - (hours * 60 * 60))/60), seconds = Math.round(n._n - (hours * 60 * 60) - (minutes * 60)); return hours + ':' + ((minutes < 10) ? '0' + minutes : minutes) + ':' + ((seconds < 10) ? '0' + seconds : seconds); } function unformatTime (string) { var timeArray = string.split(':'), seconds = 0; // turn hours and minutes into seconds and add them all up if (timeArray.length === 3) { // hours seconds = seconds + (Number(timeArray[0]) * 60 * 60); // minutes seconds = seconds + (Number(timeArray[1]) * 60); // seconds seconds = seconds + Number(timeArray[2]); } else if (timeArray.lenght === 2) { // minutes seconds = seconds + (Number(timeArray[0]) * 60); // seconds seconds = seconds + Number(timeArray[1]); } return Number(seconds); } function formatNumber (n, format) { var negP = false, optDec = false, abbr = '', bytes = '', ord = '', abs = Math.abs(n._n); // check if number is zero and a custom zero format has been set if (n._n === 0 && zeroFormat !== null) { return zeroFormat; } else { // see if we should use parentheses for negative number if (format.indexOf('(') > -1) { negP = true; format = format.slice(1, -1); } // see if abbreviation is wanted if (format.indexOf('a') > -1) { // check for space before abbreviation if (format.indexOf(' a') > -1) { abbr = ' '; format = format.replace(' a', ''); } else { format = format.replace('a', ''); } if (abs >= Math.pow(10, 12)) { // trillion abbr = abbr + languages[currentLanguage].abbreviations.trillion; n._n = n._n / Math.pow(10, 12); } else if (abs < Math.pow(10, 12) && abs >= Math.pow(10, 9)) { // billion abbr = abbr + languages[currentLanguage].abbreviations.billion; n._n = n._n / Math.pow(10, 9); } else if (abs < Math.pow(10, 9) && abs >= Math.pow(10, 6)) { // million abbr = abbr + languages[currentLanguage].abbreviations.million; n._n = n._n / Math.pow(10, 6); } else if (abs < Math.pow(10, 6) && abs >= Math.pow(10, 3)) { // thousand abbr = abbr + languages[currentLanguage].abbreviations.thousand; n._n = n._n / Math.pow(10, 3); } } // see if we are formatting bytes if (format.indexOf('b') > -1) { // check for space before if (format.indexOf(' b') > -1) { bytes = ' '; format = format.replace(' b', ''); } else { format = format.replace('b', ''); } var prefixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], min, max; for (var power = 0; power <= prefixes.length; power++) { min = Math.pow(1024, power); max = Math.pow(1024, power+1); if (n._n >= min && n._n < max) { bytes = bytes + prefixes[power]; if (min > 0) { n._n = n._n / min; } break; } } } // see if ordinal is wanted if (format.indexOf('o') > -1) { // check for space before if (format.indexOf(' o') > -1) { ord = ' '; format = format.replace(' o', ''); } else { format = format.replace('o', ''); } ord = ord + languages[currentLanguage].ordinal(n._n); } if (format.indexOf('[.]') > -1) { optDec = true; format = format.replace('[.]', '.'); } var w = n._n.toString().split('.')[0], precision = format.split('.')[1], thousands = format.indexOf(','), d = '', neg = false; if (precision) { if (precision.indexOf('[') > -1) { precision = precision.replace(']', ''); precision = precision.split('['); d = toFixed(n._n, (precision[0].length + precision[1].length), precision[1].length); } else { d = toFixed(n._n, precision.length); } w = d.split('.')[0]; if (d.split('.')[1].length) { d = languages[currentLanguage].delimiters.decimal + d.split('.')[1]; } else { d = ''; } if (optDec && Number(d) === 0) { d = ''; } } else { w = toFixed(n._n, null); } // format number if (w.indexOf('-') > -1) { w = w.slice(1); neg = true; } if (thousands > -1) { w = w.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1' + languages[currentLanguage].delimiters.thousands); } if (format.indexOf('.') === 0) { w = ''; } return ((negP && neg) ? '(' : '') + ((!negP && neg) ? '-' : '') + w + d + ((ord) ? ord : '') + ((abbr) ? abbr : '') + ((bytes) ? bytes : '') + ((negP && neg) ? ')' : ''); } } /************************************ Top Level Functions ************************************/ numeral = function (input) { if (numeral.isNumeral(input)) { input = input.value(); } else if (!Number(input)) { input = 0; } return new Numeral(Number(input)); }; // version number numeral.version = VERSION; // compare numeral object numeral.isNumeral = function (obj) { return obj instanceof Numeral; }; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. numeral.language = function (key, values) { if (!key) { return currentLanguage; } if (key && !values) { currentLanguage = key; } if (values || !languages[key]) { loadLanguage(key, values); } return numeral; }; numeral.language('en', { delimiters: { thousands: ',', decimal: '.' }, abbreviations: { thousand: 'k', million: 'm', billion: 'b', trillion: 't' }, ordinal: function (number) { var b = number % 10; return (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; }, currency: { symbol: '$' } }); numeral.zeroFormat = function (format) { if (typeof(format) === 'string') { zeroFormat = format; } else { zeroFormat = null; } }; /************************************ Helpers ************************************/ function loadLanguage(key, values) { languages[key] = values; } /************************************ Numeral Prototype ************************************/ numeral.fn = Numeral.prototype = { clone : function () { return numeral(this); }, format : function (inputString) { return formatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, unformat : function (inputString) { return unformatNumeral(this, inputString ? inputString : numeral.defaultFormat); }, value : function () { return this._n; }, valueOf : function () { return this._n; }, set : function (value) { this._n = Number(value); return this; }, add : function (value) { this._n = this._n + Number(value); return this; }, subtract : function (value) { this._n = this._n - Number(value); return this; }, multiply : function (value) { this._n = this._n * Number(value); return this; }, divide : function (value) { this._n = this._n / Number(value); return this; }, difference : function (value) { var difference = this._n - Number(value); if (difference < 0) { difference = -difference; } return difference; } }; /************************************ Exposing Numeral ************************************/ // CommonJS module is defined if (hasModule) { module.exports = numeral; } /*global ender:false */ if (typeof ender === 'undefined') { // here, `this` means `window` in the browser, or `global` on the server // add `numeral` as a global object via a string identifier, // for Closure Compiler 'advanced' mode this['numeral'] = numeral; } /*global define:false */ if (typeof define === 'function' && define.amd) { define([], function () { return numeral; }); } }).call(this);
app/components/Icons/MaleCheckedIcon.js
Tetraib/player.rauks.org
import React from 'react' import SvgIcon from 'material-ui/SvgIcon' export const MaleCheckedIcon = (props) => ( <SvgIcon {...props}> <path d='M17.654,2l-0.828,1.449h2.069l-3.828,3.829C11.633,4.711,6.8,5.234,3.994,8.475 c-2.806,3.241-2.631,8.099,0.4,11.13s7.89,3.206,11.131,0.4c3.24-2.807,3.764-7.639,1.197-11.073l3.828-3.829v2.07L22,6.346V2 H17.654z M10.204,7.898c3.257,0,5.897,2.641,5.897,5.898c0,3.257-2.641,5.897-5.897,5.897c-3.257,0-5.898-2.641-5.898-5.897 C4.306,10.539,6.947,7.898,10.204,7.898L10.204,7.898z'/> <circle cx='10.2' cy='13.75' r='3'/> </SvgIcon> ) export default MaleCheckedIcon
src/components/Layout/SystemSwitcher.js
steem/qwp-antd
import React from 'react' import PropTypes from 'prop-types' import { Menu, Dropdown, Icon } from 'antd' import { Link } from 'dva/router' const SystemSwitcher = ({ itemClassName, subSystems }) => { const sysMenus = (<Menu> <Menu.Item>System Navigation Switcher Menu</Menu.Item> <Menu.Divider /> {subSystems.map(item => ( <Menu.Item> <Link to={item.path}>{item.icon && <Icon type={item.icon} />} {item.name}</Link> </Menu.Item> ))} </Menu> ) return ( <Dropdown overlay={sysMenus} trigger={['click']}> <div className={itemClassName}> <a className="ant-dropdown-link"> <Icon type="down-circle-o" /> </a> </div> </Dropdown> ) } SystemSwitcher.propTypes = { subSystems: PropTypes.array.isRequired, itemClassName: PropTypes.string.isRequired, } export default SystemSwitcher
app/components/Logo/__tests__/index.stories.js
BjornMelgaard/ran
import React from 'react' import { storiesOf } from '@storybook/react' import Logo from '../' storiesOf('Logo', module).add('default', () => <Logo />)
ajax/libs/forerunnerdb/1.3.670/fdb-all.js
ahocevar/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), CollectionGroup = _dereq_('../lib/CollectionGroup'), View = _dereq_('../lib/View'), Highchart = _dereq_('../lib/Highchart'), Persist = _dereq_('../lib/Persist'), Document = _dereq_('../lib/Document'), Overview = _dereq_('../lib/Overview'), Grid = _dereq_('../lib/Grid'), NodeApiClient = _dereq_('../lib/NodeApiClient'), BinaryLog = _dereq_('../lib/BinaryLog'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/BinaryLog":4,"../lib/CollectionGroup":8,"../lib/Document":11,"../lib/Grid":13,"../lib/Highchart":14,"../lib/NodeApiClient":30,"../lib/Overview":33,"../lib/Persist":35,"../lib/View":42,"./core":2}],2:[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":9,"../lib/Shim.IE8":41}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":34,"./Shared":40}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, ReactorIO, Collection, CollectionInit, Db, DbInit, BinaryLog; Shared = _dereq_('./Shared'); BinaryLog = function () { this.init.apply(this, arguments); }; BinaryLog.prototype.init = function (parent) { var self = this; self._logCounter = 0; self._parent = parent; self.size(1000); }; Shared.addModule('BinaryLog', BinaryLog); Shared.mixin(BinaryLog.prototype, 'Mixin.Common'); Shared.mixin(BinaryLog.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryLog.prototype, 'Mixin.Events'); Collection = Shared.modules.Collection; Db = Shared.modules.Db; ReactorIO = Shared.modules.ReactorIO; CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; Shared.synthesize(BinaryLog.prototype, 'name'); Shared.synthesize(BinaryLog.prototype, 'size'); BinaryLog.prototype.attachIO = function () { var self = this; if (!self._io) { self._log = new Collection(self._parent.name() + '-BinaryLog', {capped: true, size: self.size()}); // Override the log collection's id generator so it is linear self._log.objectId = function (id) { if (!id) { id = ++self._logCounter; } return id; }; self._io = new ReactorIO(self._parent, self, function (chainPacket) { self._log.insert({ type: chainPacket.type, data: chainPacket.data }); // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); } }; BinaryLog.prototype.detachIO = function () { var self = this; if (self._io) { self._log.drop(); self._io.drop(); delete self._log; delete self._io; } }; Collection.prototype.init = function () { CollectionInit.apply(this, arguments); this._binaryLog = new BinaryLog(this); }; Shared.finishModule('BinaryLog'); module.exports = BinaryLog; },{"./Shared":40}],5:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } 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, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } 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.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', 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.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ 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.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', 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) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //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._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // 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._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, 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._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ 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; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } 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 / path 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), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, 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, pathResolver); } 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; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // 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 indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // 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]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":34,"./Shared":40}],6:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; 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; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = 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 }; module.exports = checksum; },{}],7:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; 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 }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data 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 = true; // 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'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * 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'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * 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; delete this._listeners; 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: 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 = this.serialiser.convert(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'); if (this.chainWillSend()) { this.chainSend('setData', { dataSet: this.decouple(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 hash string jString = this.hash(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!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off 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.emit('immediateChange', {type: 'truncate'}); 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, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // 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, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); 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. * @param {Function=} callback The callback method to call when the update is * complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; Collection.prototype._handleUpdate = function (query, update, options, callback) { 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) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback(); } this.emit('immediateChange', {type: 'update', data: updated}); 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 {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * 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, tempKey, replaceObj, pk, 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; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } 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 { returnArr = []; 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); returnArr.push(dataItem); }; // 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); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * 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 > 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); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('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 (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // 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 }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted}); 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, capped = this.capped(), cappedSize = this.cappedSize(); 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); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; 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 'Trigger cancelled operation'; } } 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, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, 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, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // 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), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * 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.call(this, query, options, callback); }; 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 || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // 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); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } 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) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); 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)) { } } }*/ if (!options.$aggregate) { // 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'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * 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 = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } 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 = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } 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) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = 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); } };*/ /** * 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 }; };*/ /** * 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); }; /** * 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: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, 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 (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, 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) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), 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(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @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 {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * 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; case '2d': index = new Index2d(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 pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== 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[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // 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[pk])) { // 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.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } 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.dataSet); } 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 * @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 self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { 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!'); } return undefined; } 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); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); 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; },{"./Index2d":15,"./IndexBinaryTree":16,"./IndexHashMap":17,"./KeyValueStore":18,"./Metrics":19,"./Overload":32,"./Path":34,"./ReactorIO":38,"./Shared":40}],8:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":7,"./Shared":40}],9:[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 (val) { 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; } } if (callback) { 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; } } } } if (callback) { 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; /** * 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":10,"./Metrics.js":19,"./Overload":32,"./Shared":40}],10:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, 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; } } if (callback) { 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'); Checksum = _dereq_('./Checksum.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.Checksum = Checksum; /** * 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._listeners; 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._listeners; 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._listeners; 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._listeners; 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; },{"./Checksum.js":6,"./Collection.js":7,"./Metrics.js":19,"./Overload":32,"./Shared":40}],11:[function(_dereq_,module,exports){ "use strict"; // TODO: Remove the _update* methods because we are already mixing them // TODO: in now via Mixin.Updating and update autobind to extend the _update* // TODO: methods like we already do with collection var Shared, Collection, Db; Shared = _dereq_('./Shared'); /** * Creates a new Document instance. Documents allow you to create individual * objects that can have standard ForerunnerDB CRUD operations run against * them, as well as data-binding if the AutoBind module is included in your * project. * @name Document * @class Document * @constructor */ var FdbDocument = function () { this.init.apply(this, arguments); }; FdbDocument.prototype.init = function (name) { this._name = name; this._data = {}; }; Shared.addModule('Document', FdbDocument); Shared.mixin(FdbDocument.prototype, 'Mixin.Common'); Shared.mixin(FdbDocument.prototype, 'Mixin.Events'); Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor'); Shared.mixin(FdbDocument.prototype, 'Mixin.Constants'); Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers'); Shared.mixin(FdbDocument.prototype, 'Mixin.Matching'); Shared.mixin(FdbDocument.prototype, 'Mixin.Updating'); Shared.mixin(FdbDocument.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @func state * @memberof Document * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'state'); /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Document * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'db'); /** * Gets / sets the document name. * @func name * @memberof Document * @param {String=} val The name to assign * @returns {*} */ Shared.synthesize(FdbDocument.prototype, 'name'); /** * Sets the data for the document. * @func setData * @memberof Document * @param data * @param options * @returns {Document} */ FdbDocument.prototype.setData = function (data, options) { var i, $unset; if (data) { options = options || { $decouple: true }; if (options && options.$decouple === true) { data = this.decouple(data); } if (this._linked) { $unset = {}; // Remove keys that don't exist in the new data from the current object for (i in this._data) { if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) { // Check if existing data has key if (data[i] === undefined) { // Add property name to those to unset $unset[i] = 1; } } } data.$unset = $unset; // Now update the object with new data this.updateObject(this._data, data, {}); } else { // Straight data assignment this._data = data; } this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)}); } return this; }; /** * Gets the document's data returned as a single object. * @func find * @memberof Document * @param {Object} query The query object - currently unused, just * provide a blank object e.g. {} * @param {Object=} options An options object. * @returns {Object} The document's data object. */ FdbDocument.prototype.find = function (query, options) { var result; if (options && options.$decouple === false) { result = this._data; } else { result = this.decouple(this._data); } return result; }; /** * Modifies the document. This will update the document with the data held in 'update'. * @func update * @memberof 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. */ FdbDocument.prototype.update = function (query, update, options) { var result = this.updateObject(this._data, update, query, options); if (result) { this.deferEmit('change', {type: 'update', data: this.decouple(this._data)}); } }; /** * Internal method for document updating. * @func updateObject * @memberof Document * @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 */ FdbDocument.prototype.updateObject = Collection.prototype.updateObject; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @func _isPositionalKey * @memberof Document * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ FdbDocument.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Updates a property on an object depending on if the collection is * currently running data-binding or not. * @func _updateProperty * @memberof Document * @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 */ FdbDocument.prototype._updateProperty = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, val); if (this.debug()) { console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"'); } } else { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } } }; /** * Increments a value for a property on a document by the passed number. * @func _updateIncrement * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ FdbDocument.prototype._updateIncrement = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] + val); } else { doc[prop] += val; } }; /** * Changes the index of an item in the passed array. * @func _updateSpliceMove * @memberof Document * @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 */ FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) { if (this._linked) { window.jQuery.observable(arr).move(indexFrom, indexTo); if (this.debug()) { console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } } else { 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. * @func _updateSplicePush * @memberof Document * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updateSplicePush = function (arr, index, doc) { if (arr.length > index) { if (this._linked) { window.jQuery.observable(arr).insert(index, doc); } else { arr.splice(index, 0, doc); } } else { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } } }; /** * Inserts an item at the end of an array. * @func _updatePush * @memberof Document * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ FdbDocument.prototype._updatePush = function (arr, doc) { if (this._linked) { window.jQuery.observable(arr).insert(doc); } else { arr.push(doc); } }; /** * Removes an item from the passed array. * @func _updatePull * @memberof Document * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ FdbDocument.prototype._updatePull = function (arr, index) { if (this._linked) { window.jQuery.observable(arr).remove(index); } else { arr.splice(index, 1); } }; /** * Multiplies a value for a property on a document by the passed number. * @func _updateMultiply * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ FdbDocument.prototype._updateMultiply = function (doc, prop, val) { if (this._linked) { window.jQuery.observable(doc).setProperty(prop, doc[prop] * val); } else { doc[prop] *= val; } }; /** * Renames a property on a document to the passed property. * @func _updateRename * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ FdbDocument.prototype._updateRename = function (doc, prop, val) { var existingVal = doc[prop]; if (this._linked) { window.jQuery.observable(doc).setProperty(val, existingVal); window.jQuery.observable(doc).removeProperty(prop); } else { doc[val] = existingVal; delete doc[prop]; } }; /** * Deletes a property on a document. * @func _updateUnset * @memberof Document * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ FdbDocument.prototype._updateUnset = function (doc, prop) { if (this._linked) { window.jQuery.observable(doc).removeProperty(prop); } else { delete doc[prop]; } }; /** * Drops the document. * @func drop * @memberof Document * @returns {boolean} True if successful, false if not. */ FdbDocument.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._db && this._name) { if (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); if (callback) { callback(false, true); } delete this._listeners; return true; } } } else { return true; } return false; }; /** * Creates a new document instance or returns an existing * instance if one already exists with the passed name. * @func document * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.document = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof FdbDocument) { if (name.state() !== 'droppped') { return name; } else { name = name.name(); } } if (this._document && this._document[name]) { return this._document[name]; } this._document = this._document || {}; this._document[name] = new FdbDocument(name).db(this); self.emit('create', self._document[name], 'document', name); return this._document[name]; } else { // Return an object of document data return this._document; } }; /** * Returns an array of documents the DB currently has. * @func documents * @memberof Db * @returns {Array} An array of objects containing details of each document * the database is currently managing. */ Db.prototype.documents = function () { var arr = [], item, i; for (i in this._document) { if (this._document.hasOwnProperty(i)) { item = this._document[i]; arr.push({ name: i, linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Document'); module.exports = FdbDocument; },{"./Collection":7,"./Shared":40}],12:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - [email protected] "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],13:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, View, CollectionInit, DbInit, ReactorIO; //Shared = ForerunnerDB.shared; Shared = _dereq_('./Shared'); /** * Creates a new grid instance. * @name Grid * @class Grid * @param {String} selector jQuery selector. * @param {String} template The template selector. * @param {Object=} options The options object to apply to the grid. * @constructor */ var Grid = function (selector, template, options) { this.init.apply(this, arguments); }; Grid.prototype.init = function (selector, template, options) { var self = this; this._selector = selector; this._template = template; this._options = options || {}; this._debug = {}; this._id = this.objectId(); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; }; Shared.addModule('Grid', Grid); Shared.mixin(Grid.prototype, 'Mixin.Common'); Shared.mixin(Grid.prototype, 'Mixin.ChainReactor'); Shared.mixin(Grid.prototype, 'Mixin.Constants'); Shared.mixin(Grid.prototype, 'Mixin.Triggers'); Shared.mixin(Grid.prototype, 'Mixin.Events'); Shared.mixin(Grid.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); View = _dereq_('./View'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @func state * @memberof Grid * @param {String=} val The name of the state to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'state'); /** * Gets / sets the current name. * @func name * @memberof Grid * @param {String=} val The name to set. * @returns {Grid} */ Shared.synthesize(Grid.prototype, 'name'); /** * Executes an insert against the grid's underlying data-source. * @func insert * @memberof Grid */ Grid.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the grid's underlying data-source. * @func update * @memberof Grid */ Grid.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the grid's underlying data-source. * @func updateById * @memberof Grid */ Grid.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the grid's underlying data-source. * @func remove * @memberof Grid */ Grid.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Sets the collection from which the grid will assemble its data. * @func from * @memberof Grid * @param {Collection} collection The collection to use to assemble grid data. * @returns {Grid} */ Grid.prototype.from = function (collection) { //var self = this; if (collection !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); } if (typeof(collection) === 'string') { collection = this._db.collection(collection); } this._from = collection; this._from.on('drop', this._collectionDroppedWrap); this.refresh(); } return this; }; /** * Gets / sets the db instance this class instance belongs to. * @func db * @memberof Grid * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Grid.prototype, 'db', function (db) { if (db) { // Apply the same debug settings this.debug(db.debug()); } return this.$super.apply(this, arguments); }); Grid.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from grid delete this._from; } }; /** * Drops a grid and all it's stored data from the database. * @func drop * @memberof Grid * @returns {boolean} True on success, false on failure. */ Grid.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { // Remove data-binding this._from.unlink(this._selector, this.template()); // Kill listeners and references this._from.off('drop', this._collectionDroppedWrap); this._from._removeGrid(this); if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping grid ' + this._selector); } this._state = 'dropped'; if (this._db && this._selector) { delete this._db._grid[this._selector]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._selector; delete this._template; delete this._from; delete this._db; delete this._listeners; return true; } } else { return true; } return false; }; /** * Gets / sets the grid's HTML template to use when rendering. * @func template * @memberof Grid * @param {Selector} template The template's jQuery selector. * @returns {*} */ Grid.prototype.template = function (template) { if (template !== undefined) { this._template = template; return this; } return this._template; }; Grid.prototype._sortGridClick = function (e) { var elem = window.jQuery(e.currentTarget), sortColText = elem.attr('data-grid-sort') || '', sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1, sortCols = sortColText.split(','), sortObj = {}, i; // Remove all grid sort tags from the grid window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir'); // Flip the sort direction elem.attr('data-grid-dir', sortColDir); for (i = 0; i < sortCols.length; i++) { sortObj[sortCols] = sortColDir; } Shared.mixin(sortObj, this._options.$orderBy); this._from.orderBy(sortObj); this.emit('sort', sortObj); }; /** * Refreshes the grid data such as ordering etc. * @func refresh * @memberof Grid */ Grid.prototype.refresh = function () { if (this._from) { if (this._from.link) { var self = this, elem = window.jQuery(this._selector), sortClickListener = function () { self._sortGridClick.apply(self, arguments); }; // Clear the container elem.html(''); if (self._from.orderBy) { // Remove listeners elem.off('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Remove listeners elem.off('click', '[data-grid-filter]', sortClickListener ); } // Set wrap name if none is provided self._options.$wrap = self._options.$wrap || 'gridRow'; // Auto-bind the data to the grid template self._from.link(self._selector, self.template(), self._options); // Check if the data source (collection or view) has an // orderBy method (usually only views) and if so activate // the sorting system if (self._from.orderBy) { // Listen for sort requests elem.on('click', '[data-grid-sort]', sortClickListener); } if (self._from.query) { // Listen for filter requests var queryObj = {}; elem.find('[data-grid-filter]').each(function (index, filterElem) { filterElem = window.jQuery(filterElem); var filterField = filterElem.attr('data-grid-filter'), filterVarType = filterElem.attr('data-grid-vartype'), filterSort = {}, title = filterElem.html(), dropDownButton, dropDownMenu, template, filterQuery, filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField); filterSort[filterField] = 1; filterQuery = { $distinct: filterSort }; filterView .query(filterQuery) .orderBy(filterSort) .from(self._from._from); template = [ '<div class="dropdown" id="' + self._id + '_' + filterField + '">', '<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">', title + ' <span class="caret"></span>', '</button>', '</div>' ]; dropDownButton = window.jQuery(template.join('')); dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>'); dropDownButton.append(dropDownMenu); filterElem.html(dropDownButton); // Data-link the underlying data to the grid filter drop-down filterView.link(dropDownMenu, { 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{:' + filterField + '}">', '<a role="menuitem" tabindex="-1">', '<input type="checkbox">&nbsp;{^{:' + filterField + '}}', '</a>', '</li>', '{{/for}}' ].join('') }, { $wrap: 'options' }); elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) { var elem = window.jQuery(this), query = filterView.query(), search = elem.val(); if (search) { query[filterField] = new RegExp(search, 'gi'); } else { delete query[filterField]; } filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) { // Clear search text box window.jQuery(this).parents('li').find('.gridFilterSearch').val(''); // Clear view query var query = filterView.query(); delete query[filterField]; filterView.query(query); }); elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) { e.stopPropagation(); var fieldValue, elem = $(this), checkbox = elem.find('input[type="checkbox"]'), checked, addMode = true, fieldInArr, liElem, i; // If the checkbox is not the one clicked on if (!window.jQuery(e.target).is('input')) { // Set checkbox to opposite of current value checkbox.prop('checked', !checkbox.prop('checked')); checked = checkbox.is(':checked'); } else { checkbox.prop('checked', checkbox.prop('checked')); checked = checkbox.is(':checked'); } liElem = window.jQuery(this); fieldValue = liElem.attr('data-val'); // Check if the selection is the "all" option if (fieldValue === '$all') { // Remove the field from the query delete queryObj[filterField]; // Clear all other checkboxes liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false); } else { // Clear the "all" checkbox liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false); // Check if the type needs casting switch (filterVarType) { case 'integer': fieldValue = parseInt(fieldValue, 10); break; case 'float': fieldValue = parseFloat(fieldValue); break; default: } // Check if the item exists already queryObj[filterField] = queryObj[filterField] || { $in: [] }; fieldInArr = queryObj[filterField].$in; for (i = 0; i < fieldInArr.length; i++) { if (fieldInArr[i] === fieldValue) { // Item already exists if (checked === false) { // Remove the item fieldInArr.splice(i, 1); } addMode = false; break; } } if (addMode && checked) { fieldInArr.push(fieldValue); } if (!fieldInArr.length) { // Remove the field from the query delete queryObj[filterField]; } } // Set the view query self._from.queryData(queryObj); if (self._from.pageFirst) { self._from.pageFirst(); } }); }); } self.emit('refresh'); } else { throw('Grid requires the AutoBind module in order to operate!'); } } return this; }; /** * Returns the number of documents currently in the grid. * @func count * @memberof Grid * @returns {Number} */ Grid.prototype.count = function () { return this._from.count(); }; /** * Creates a grid and assigns the collection as its data source. * @func grid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.grid = View.prototype.grid = function (selector, template, options) { if (this._db && this._db._grid ) { if (selector !== undefined) { if (template !== undefined) { if (!this._db._grid[selector]) { var grid = new Grid(selector, template, options) .db(this._db) .from(this); this._grid = this._grid || []; this._grid.push(grid); this._db._grid[selector] = grid; return grid; } else { throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector); } } return this._db._grid[selector]; } return this._db._grid; } }; /** * Removes a grid safely from the DOM. Must be called when grid is * no longer required / is being removed from DOM otherwise references * will stick around and cause memory leaks. * @func unGrid * @memberof Collection * @param {String} selector jQuery selector of grid output target. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) { var i, grid; if (this._db && this._db._grid ) { if (selector && template) { if (this._db._grid[selector]) { grid = this._db._grid[selector]; delete this._db._grid[selector]; return grid.drop(); } else { throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name); } } else { // No parameters passed, remove all grids from this module for (i in this._db._grid) { if (this._db._grid.hasOwnProperty(i)) { grid = this._db._grid[i]; delete this._db._grid[i]; grid.drop(); if (this.debug()) { console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"'); } } } this._db._grid = {}; } } }; /** * Adds a grid to the internal grid lookup. * @func _addGrid * @memberof Collection * @param {Grid} grid The grid to add. * @returns {Collection} * @private */ Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) { if (grid !== undefined) { this._grid = this._grid || []; this._grid.push(grid); } return this; }; /** * Removes a grid from the internal grid lookup. * @func _removeGrid * @memberof Collection * @param {Grid} grid The grid to remove. * @returns {Collection} * @private */ Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) { if (grid !== undefined && this._grid) { var index = this._grid.indexOf(grid); if (index > -1) { this._grid.splice(index, 1); } } return this; }; // Extend DB with grids init Db.prototype.init = function () { this._grid = {}; DbInit.apply(this, arguments); }; /** * Determine if a grid with the passed name already exists. * @func gridExists * @memberof Db * @param {String} selector The jQuery selector to bind the grid to. * @returns {boolean} */ Db.prototype.gridExists = function (selector) { return Boolean(this._grid[selector]); }; /** * Creates a grid based on the passed arguments. * @func grid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.grid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Removes a grid based on the passed arguments. * @func unGrid * @memberof Db * @param {String} selector The jQuery selector of the grid to retrieve. * @param {String} template The table template to use when rendering the grid. * @param {Object=} options The options object to apply to the grid. * @returns {*} */ Db.prototype.unGrid = function (selector, template, options) { if (!this._grid[selector]) { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating grid ' + selector); } } this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this); return this._grid[selector]; }; /** * Returns an array of grids the DB currently has. * @func grids * @memberof Db * @returns {Array} An array of objects containing details of each grid * the database is currently managing. */ Db.prototype.grids = function () { var arr = [], item, i; for (i in this._grid) { if (this._grid.hasOwnProperty(i)) { item = this._grid[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Grid'); module.exports = Grid; },{"./Collection":7,"./CollectionGroup":8,"./ReactorIO":38,"./Shared":40,"./View":42}],14:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Collection, CollectionInit, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * The constructor. * * @constructor */ var Highchart = function (collection, options) { this.init.apply(this, arguments); }; Highchart.prototype.init = function (collection, options) { this._options = options; this._selector = window.jQuery(this._options.selector); if (!this._selector[0]) { throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector); } this._listeners = {}; this._collection = collection; // Setup the chart this._options.series = []; // Disable attribution on highcharts options.chartOptions = options.chartOptions || {}; options.chartOptions.credits = false; // Set the data for the chart var data, seriesObj, chartData; switch (this._options.type) { case 'pie': // Create chart from data this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); // Generate graph data from collection data data = this._collection.find(); seriesObj = { allowPointSelect: true, cursor: 'pointer', dataLabels: { enabled: true, format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)', style: { color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black' } } }; chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField); window.jQuery.extend(seriesObj, this._options.seriesOptions); window.jQuery.extend(seriesObj, { name: this._options.seriesName, data: chartData }); this._chart.addSeries(seriesObj, true, true); break; case 'line': case 'area': case 'column': case 'bar': // Generate graph data from collection data chartData = this.seriesDataFromCollectionData( this._options.seriesField, this._options.keyField, this._options.valField, this._options.orderBy, this._options ); this._options.chartOptions.xAxis = chartData.xAxis; this._options.chartOptions.series = chartData.series; this._selector.highcharts(this._options.chartOptions); this._chart = this._selector.highcharts(); break; default: throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type); } // Hook the collection events to auto-update the chart this._hookEvents(); }; Shared.addModule('Highchart', Highchart); Collection = Shared.modules.Collection; CollectionInit = Collection.prototype.init; Shared.mixin(Highchart.prototype, 'Mixin.Common'); Shared.mixin(Highchart.prototype, 'Mixin.Events'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Highchart.prototype, 'state'); /** * Generate pie-chart series data from the given collection data array. * @param data * @param keyField * @param valField * @returns {Array} */ Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) { var graphData = [], i; for (i = 0; i < data.length; i++) { graphData.push([data[i][keyField], data[i][valField]]); } return graphData; }; /** * Generate line-chart series data from the given collection data array. * @param seriesField * @param keyField * @param valField * @param orderBy */ Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy, options) { var data = this._collection.distinct(seriesField), seriesData = [], xAxis = options && options.chartOptions && options.chartOptions.xAxis ? options.chartOptions.xAxis : { categories: [] }, seriesName, query, dataSearch, seriesValues, sData, i, k; // What we WANT to output: /*series: [{ name: 'Responses', data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6] }]*/ // Loop keys for (i = 0; i < data.length; i++) { seriesName = data[i]; query = {}; query[seriesField] = seriesName; seriesValues = []; dataSearch = this._collection.find(query, { orderBy: orderBy }); // Loop the keySearch data and grab the value for each item for (k = 0; k < dataSearch.length; k++) { if (xAxis.categories) { xAxis.categories.push(dataSearch[k][keyField]); seriesValues.push(dataSearch[k][valField]); } else { seriesValues.push([dataSearch[k][keyField], dataSearch[k][valField]]); } } sData = { name: seriesName, data: seriesValues }; if (options.seriesOptions) { for (k in options.seriesOptions) { if (options.seriesOptions.hasOwnProperty(k)) { sData[k] = options.seriesOptions[k]; } } } seriesData.push(sData); } return { xAxis: xAxis, series: seriesData }; }; /** * Hook the events the chart needs to know about from the internal collection. * @private */ Highchart.prototype._hookEvents = function () { var self = this; self._collection.on('change', function () { self._changeListener.apply(self, arguments); }); // If the collection is dropped, clean up after ourselves self._collection.on('drop', function () { self.drop.apply(self); }); }; /** * Handles changes to the collection data that the chart is reading from and then * updates the data in the chart display. * @private */ Highchart.prototype._changeListener = function () { var self = this; // Update the series data on the chart if (typeof self._collection !== 'undefined' && self._chart) { var data = self._collection.find(), i; switch (self._options.type) { case 'pie': self._chart.series[0].setData( self.pieDataFromCollectionData( data, self._options.keyField, self._options.valField ), true, true ); break; case 'bar': case 'line': case 'area': case 'column': var seriesData = self.seriesDataFromCollectionData( self._options.seriesField, self._options.keyField, self._options.valField, self._options.orderBy, self._options ); if (seriesData.xAxis.categories) { self._chart.xAxis[0].setCategories( seriesData.xAxis.categories ); } for (i = 0; i < seriesData.series.length; i++) { if (self._chart.series[i]) { // Series exists, set it's data self._chart.series[i].setData( seriesData.series[i].data, true, true ); } else { // Series data does not yet exist, add a new series self._chart.addSeries( seriesData.series[i], true, true ); } } break; default: break; } } }; /** * Destroys the chart and all internal references. * @returns {Boolean} */ Highchart.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; if (this._chart) { this._chart.destroy(); } if (this._collection) { this._collection.off('change', this._changeListener); this._collection.off('drop', this.drop); if (this._collection._highcharts) { delete this._collection._highcharts[this._options.selector]; } } delete this._chart; delete this._options; delete this._collection; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; return true; } else { return true; } }; // Extend collection with highchart init Collection.prototype.init = function () { this._highcharts = {}; CollectionInit.apply(this, arguments); }; /** * Creates a pie chart from the collection. * @type {Overload} */ Collection.prototype.pieChart = new Overload({ /** * Chart via options object. * @func pieChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'pie'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'pie'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func pieChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {String} seriesName The name of the series to display on the chart. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) { options = options || {}; options.selector = selector; options.keyField = keyField; options.valField = valField; options.seriesName = seriesName; // Call the main chart method this.pieChart(options); } }); /** * Creates a line chart from the collection. * @type {Overload} */ Collection.prototype.lineChart = new Overload({ /** * Chart via selector. * @func lineChart * @memberof Highchart * @param {String} selector The chart selector. * @returns {*} */ 'string': function (selector) { return this._highcharts[selector]; }, /** * Chart via options object. * @func lineChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'line'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'line'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func lineChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.lineChart(options); } }); /** * Creates an area chart from the collection. * @type {Overload} */ Collection.prototype.areaChart = new Overload({ /** * Chart via options object. * @func areaChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'area'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'area'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func areaChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.areaChart(options); } }); /** * Creates a column chart from the collection. * @type {Overload} */ Collection.prototype.columnChart = new Overload({ /** * Chart via options object. * @func columnChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'column'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'column'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func columnChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.columnChart(options); } }); /** * Creates a bar chart from the collection. * @type {Overload} */ Collection.prototype.barChart = new Overload({ /** * Chart via options object. * @func barChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func barChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.barChart(options); } }); /** * Creates a stacked bar chart from the collection. * @type {Overload} */ Collection.prototype.stackedBarChart = new Overload({ /** * Chart via options object. * @func stackedBarChart * @memberof Highchart * @param {Object} options The options object. * @returns {*} */ 'object': function (options) { options.type = 'bar'; options.chartOptions = options.chartOptions || {}; options.chartOptions.chart = options.chartOptions.chart || {}; options.chartOptions.chart.type = 'bar'; options.plotOptions = options.plotOptions || {}; options.plotOptions.series = options.plotOptions.series || {}; options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal'; if (!this._highcharts[options.selector]) { // Store new chart in charts array this._highcharts[options.selector] = new Highchart(this, options); } return this._highcharts[options.selector]; }, /** * Chart via defined params and an options object. * @func stackedBarChart * @memberof Highchart * @param {String|jQuery} selector The element to render the chart to. * @param {String} seriesField The name of the series to plot. * @param {String} keyField The field to use as the data key. * @param {String} valField The field to use as the data value. * @param {Object} options The options object. */ '*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) { options = options || {}; options.seriesField = seriesField; options.selector = selector; options.keyField = keyField; options.valField = valField; // Call the main chart method this.stackedBarChart(options); } }); /** * Removes a chart from the page by it's selector. * @memberof Collection * @param {String} selector The chart selector. */ Collection.prototype.dropChart = function (selector) { if (this._highcharts && this._highcharts[selector]) { this._highcharts[selector].drop(); } }; Shared.finishModule('Highchart'); module.exports = Highchart; },{"./Overload":32,"./Shared":40}],15:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.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.clear(); this._size = 0; 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 }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.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]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.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; }; Index2d.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; }; Index2d.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('Index2d'); module.exports = Index2d; },{"./BinaryTree":5,"./GeoHash":12,"./Path":34,"./Shared":40}],16:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree 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 BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; 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.clear(); this._size = 0; 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; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; 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, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; 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":5,"./Path":34,"./Shared":40}],17:[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 = {}; this._size = 0; 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":34,"./Shared":40}],18:[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 {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * 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":40}],19:[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":31,"./Shared":40}],20:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],21:[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 = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ 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); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ 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); } } }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ 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() + '"'); } } if (arrItem.chainReceive) { 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!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],22:[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, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * 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 && data !== "") { 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 JSON.parse(data, serialiser.reviver()); }, /** * 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; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * 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 'ForerunnerDB ' + 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'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":32,"./Serialiser":39}],23:[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; },{}],24:[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":32}],25:[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; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = 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 if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ 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} queryOptions The options the query was passed with. * @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 '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === 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 (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } 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 (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } 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; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.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)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.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 (resultKeyName === '$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 [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[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 { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions 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 pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[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] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],26:[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; },{}],27:[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; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * 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 {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} 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":32}],29:[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 + '" to val "' + val + '"'); } }, /** * 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 set. * @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; },{}],30:[function(_dereq_,module,exports){ "use strict"; // Tell JSHint about EventSource /*global EventSource */ // Import external names locally var Shared = _dereq_('./Shared'), Core, CoreInit, Collection, NodeApiClient, Overload; NodeApiClient = function () { this.init.apply(this, arguments); }; /** * The init method that can be overridden or extended. * @param {Core} core The ForerunnerDB core instance. */ NodeApiClient.prototype.init = function (core) { var self = this; self._core = core; self.rootPath('/fdb'); }; Shared.addModule('NodeApiClient', NodeApiClient); Shared.mixin(NodeApiClient.prototype, 'Mixin.Common'); Shared.mixin(NodeApiClient.prototype, 'Mixin.Events'); Shared.mixin(NodeApiClient.prototype, 'Mixin.ChainReactor'); Core = Shared.modules.Core; CoreInit = Core.prototype.init; Collection = Shared.modules.Collection; Overload = Shared.overload; Shared.synthesize(NodeApiClient.prototype, 'rootPath'); /** * Set the url of the server to use for API. * @name server * @param {String} host The server host name including protocol. E.g. * "https://0.0.0.0". * @param {String} port The server port number e.g. "8080". */ NodeApiClient.prototype.server = function (host, port) { if (host !== undefined) { if (host.substr(host.length - 1, 1) === '/') { // Strip trailing / host = host.substr(0, host.length - 1); } if (port !== undefined) { this._server = host + ":" + port; } else { this._server = host; } this._host = host; this._port = port; return this; } if (port !== undefined) { return { host: this._host, port: this._port, url: this._server }; } else { return this._server; } }; NodeApiClient.prototype.http = function (method, url, data, options, callback) { var self = this, finalUrl, sessionData, bodyData, xmlHttp = new XMLHttpRequest(); method = method.toUpperCase(); xmlHttp.onreadystatechange = function () { if (xmlHttp.readyState === 4) { if (xmlHttp.status === 200) { // Tell the callback about success callback(false, self.jParse(xmlHttp.responseText)); } else { // Tell the callback about the error callback(xmlHttp.status, xmlHttp.responseText); // Emit the error code self.emit('httpError', xmlHttp.status, xmlHttp.responseText); } } }; switch (method) { case 'GET': case 'DELETE': case 'HEAD': // Check for global auth if (this._sessionData) { data = data !== undefined ? data : {}; // Add the session data to the key specified data[this._sessionData.key] = this._sessionData.obj; } finalUrl = url + (data !== undefined ? '?' + self.jStringify(data) : ''); bodyData = null; break; case 'POST': case 'PUT': case 'PATCH': // Check for global auth if (this._sessionData) { sessionData = {}; // Add the session data to the key specified sessionData[this._sessionData.key] = this._sessionData.obj; } finalUrl = url + (sessionData !== undefined ? '?' + self.jStringify(sessionData) : ''); bodyData = (data !== undefined ? self.jStringify(data) : null); break; default: return false; } xmlHttp.open(method, finalUrl, true); xmlHttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xmlHttp.send(bodyData); return this; }; // Define HTTP helper methods NodeApiClient.prototype.head = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('HEAD', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.get = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('GET', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.put = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('PUT', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.post = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('POST', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.patch = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('PATCH', this.server() + this._rootPath + path, data, options, callback); } }); NodeApiClient.prototype.postPatch = function (path, id, data, options, callback) { var self = this; // Determine if the item exists or not this.head(path + '/' + id, undefined, {}, function (err, headData) { if (err) { if (err === 404) { // Item does not exist, run post return self.http('POST', self.server() + self._rootPath + path, data, options, callback); } else { callback(err, data); } } else { // Item already exists, run patch return self.http('PATCH', self.server() + self._rootPath + path + '/' + id, data, options, callback); } }); }; NodeApiClient.prototype.delete = new Overload({ 'string, function': function (path, callback) { return this.$main.call(this, path, undefined, {}, callback); }, 'string, *, function': function (path, data, callback) { return this.$main.call(this, path, data, {}, callback); }, 'string, *, object, function': function (path, data, options, callback) { return this.$main.call(this, path, data, options, callback); }, '$main': function (path, data, options, callback) { return this.http('DELETE', this.server() + this._rootPath + path, data, options, callback); } }); /** * Gets/ sets a global object that will be sent up with client * requests to the API or REST server. * @param {String} key The key to send the session object up inside. * @param {*} obj The object / value to send up with all requests. If * a request has its own data to send up, this session data will be * mixed in to the request data under the specified key. */ NodeApiClient.prototype.session = function (key, obj) { if (key !== undefined && obj !== undefined) { this._sessionData = { key: key, obj: obj }; return this; } return this._sessionData; }; /** * Initiates a client connection to the API server. * @param collectionInstance * @param path * @param query * @param options * @param callback */ NodeApiClient.prototype.sync = function (collectionInstance, path, query, options, callback) { var self = this, source, finalPath, queryParams, queryString = '', connecting = true; if (this.debug()) { console.log(this.logIdentifier() + ' Connecting to API server ' + this.server() + this._rootPath + path); } finalPath = this.server() + this._rootPath + path + '/_sync'; // Check for global auth if (this._sessionData) { queryParams = queryParams || {}; if (this._sessionData.key) { // Add the session data to the key specified queryParams[this._sessionData.key] = this._sessionData.obj; } else { // Add the session data to the root query object Shared.mixin(queryParams, this._sessionData.obj); } } if (query) { queryParams = queryParams || {}; queryParams.$query = query; } if (options) { queryParams = queryParams || {}; if (options.$initialData === undefined) { options.$initialData = true; } queryParams.$options = options; } if (queryParams) { queryString = this.jStringify(queryParams); finalPath += '?' + queryString; } source = new EventSource(finalPath); collectionInstance.__apiConnection = source; source.addEventListener('open', function (e) { if (!options || (options && options.$initialData)) { // The connection is open, grab the initial data self.get(path, queryParams, function (err, data) { if (!err) { collectionInstance.upsert(data); } }); } }, false); source.addEventListener('error', function (e) { if (source.readyState === 2) { // The connection is dead, remove the connection collectionInstance.unSync(); } if (connecting) { connecting = false; callback(e); } }, false); source.addEventListener('insert', function(e) { var data = self.jParse(e.data); collectionInstance.insert(data.dataSet); }, false); source.addEventListener('update', function(e) { var data = self.jParse(e.data); collectionInstance.update(data.query, data.update); }, false); source.addEventListener('remove', function(e) { var data = self.jParse(e.data); collectionInstance.remove(data.query); }, false); if (callback) { source.addEventListener('connected', function (e) { if (connecting) { connecting = false; callback(false); } }, false); } }; Collection.prototype.sync = new Overload({ /** * Sync with this collection on the server-side. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'function': function (callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), null, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, function': function (collectionName, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, null, null, callback); }, /** * Sync with this collection on the server-side. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'object, function': function (query, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), query, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, function': function (objectType, objectName, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, null, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, object, function': function (collectionName, query, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, query, null, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Object} query A query object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, object, function': function (objectType, objectName, query, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, query, null, callback); }, /** * Sync with this collection on the server-side. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'object, object, function': function (query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + this.name(), query, options, callback); }, /** * Sync with this collection on the server-side. * @param {String} collectionName The collection to sync from. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, object, object, function': function (collectionName, query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/collection/' + collectionName, query, options, callback); }, /** * Sync with this collection on the server-side. * @param {String} objectType The type of object to sync to e.g. * "collection" or "view". * @param {String} objectName The name of the object to sync from. * @param {Object} query A query object. * @param {Object} options An options object. * @param {Function} callback The callback method to call once * the connection to the server has been established. */ 'string, string, object, object, function': function (objectType, objectName, query, options, callback) { this.$main.call(this, '/' + this._db.name() + '/' + objectType + '/' + objectName, query, options, callback); }, '$main': function (path, query, options, callback) { var self = this; if (this._db && this._db._core) { // Kill any existing sync connection this.unSync(); // Create new sync connection this._db._core.api.sync(this, path, query, options, callback); // Hook on drop to call unsync this.on('drop', function () { self.unSync(); }); } else { throw(this.logIdentifier() + ' Cannot sync for an anonymous collection! (Collection must be attached to a database)'); } } }); /** * Disconnects an existing connection to a sync server. * @returns {boolean} True if a connection existed, false * if no connection existed. */ Collection.prototype.unSync = function () { if (this.__apiConnection) { if (this.__apiConnection.readyState !== 2) { this.__apiConnection.close(); } delete this.__apiConnection; return true; } return false; }; Collection.prototype.http = new Overload({ 'string, function': function (method, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + this.name(), undefined, undefined, {}, callback); }, '$main': function (method, path, queryObj, queryOptions, options, callback) { if (this._db && this._db._core) { return this._db._core.api.http('GET', this._db._core.api.server() + this._rootPath + path, {"$query": queryObj, "$options": queryOptions}, options, callback); } else { throw(this.logIdentifier() + ' Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)'); } } }); Collection.prototype.autoHttp = new Overload({ 'string, function': function (method, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + this.name(), undefined, undefined, {}, callback); }, 'string, string, function': function (method, collectionName, callback) { this.$main.call(this, method, '/' + this._db.name() + '/collection/' + collectionName, undefined, undefined, {}, callback); }, 'string, string, string, function': function (method, objType, objName, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, undefined, undefined, {}, callback); }, 'string, string, string, object, function': function (method, objType, objName, queryObj, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, queryObj, undefined, {}, callback); }, 'string, string, string, object, object, function': function (method, objType, objName, queryObj, queryOptions, callback) { this.$main.call(this, method, '/' + this._db.name() + '/' + objType + '/' + objName, queryObj, queryOptions, {}, callback); }, '$main': function (method, path, queryObj, queryOptions, options, callback) { var self = this; if (this._db && this._db._core) { return this._db._core.api.http('GET', this._db._core.api.server() + this._db._core.api._rootPath + path, {"$query": queryObj, "$options": queryOptions}, options, function (err, data) { var i; if (!err && data) { // Check the type of method we used and operate on the collection accordingly switch (method) { // Find insert case 'GET': self.insert(data); break; // Insert case 'POST': if (data.inserted && data.inserted.length) { self.insert(data.inserted); } break; // Update overwrite case 'PUT': case 'PATCH': if (data instanceof Array) { // Update each document for (i = 0; i < data.length; i++) { self.updateById(data[i]._id, {$overwrite: data[i]}); } } else { // Update single document self.updateById(data._id, {$overwrite: data}); } break; // Remove case 'DELETE': self.remove(data); break; default: // Nothing to do with this method break; } } // Send the data back to the callback callback(err, data); }); } else { throw(this.logIdentifier() + ' Cannot do HTTP for an anonymous collection! (Collection must be attached to a database)'); } } }); // Override the Core init to instantiate the plugin Core.prototype.init = function () { CoreInit.apply(this, arguments); this.api = new NodeApiClient(this); }; Shared.finishModule('NodeApiClient'); module.exports = NodeApiClient; },{"./Shared":40}],31:[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":34,"./Shared":40}],32:[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'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" 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; },{}],33:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, DbDocument; Shared = _dereq_('./Shared'); var Overview = function () { this.init.apply(this, arguments); }; Overview.prototype.init = function (name) { var self = this; this._name = name; this._data = new DbDocument('__FDB__dc_data_' + this._name); this._collData = new Collection(); this._sources = []; this._sourceDroppedWrap = function () { self._sourceDropped.apply(self, arguments); }; }; Shared.addModule('Overview', Overview); Shared.mixin(Overview.prototype, 'Mixin.Common'); Shared.mixin(Overview.prototype, 'Mixin.ChainReactor'); Shared.mixin(Overview.prototype, 'Mixin.Constants'); Shared.mixin(Overview.prototype, 'Mixin.Triggers'); Shared.mixin(Overview.prototype, 'Mixin.Events'); Shared.mixin(Overview.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); DbDocument = _dereq_('./Document'); Db = Shared.modules.Db; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Overview.prototype, 'state'); Shared.synthesize(Overview.prototype, 'db'); Shared.synthesize(Overview.prototype, 'name'); Shared.synthesize(Overview.prototype, 'query', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'queryOptions', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Shared.synthesize(Overview.prototype, 'reduce', function (val) { var ret = this.$super(val); if (val !== undefined) { this._refresh(); } return ret; }); Overview.prototype.from = function (source) { if (source !== undefined) { if (typeof(source) === 'string') { source = this._db.collection(source); } this._setFrom(source); return this; } return this._sources; }; Overview.prototype.find = function () { return this._collData.find.apply(this._collData, arguments); }; /** * Executes and returns the response from the current reduce method * assigned to the overview. * @returns {*} */ Overview.prototype.exec = function () { var reduceFunc = this.reduce(); return reduceFunc ? reduceFunc.apply(this) : undefined; }; Overview.prototype.count = function () { return this._collData.count.apply(this._collData, arguments); }; Overview.prototype._setFrom = function (source) { // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } this._addSource(source); return this; }; Overview.prototype._addSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } if (this._sources.indexOf(source) === -1) { this._sources.push(source); source.chain(this); source.on('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._removeSource = function (source) { if (source && source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } var sourceIndex = this._sources.indexOf(source); if (sourceIndex > -1) { this._sources.splice(source, 1); source.unChain(this); source.off('drop', this._sourceDroppedWrap); this._refresh(); } return this; }; Overview.prototype._sourceDropped = function (source) { if (source) { // Source was dropped, remove from overview this._removeSource(source); } }; Overview.prototype._refresh = function () { if (!this.isDropped()) { if (this._sources && this._sources[0]) { this._collData.primaryKey(this._sources[0].primaryKey()); var tempArr = [], i; for (i = 0; i < this._sources.length; i++) { tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions)); } this._collData.setData(tempArr); } // Now execute the reduce method if (this._reduce) { var reducedData = this._reduce.apply(this); // Update the document with the newly returned data this._data.setData(reducedData); } } }; Overview.prototype._chainHandler = function (chainPacket) { switch (chainPacket.type) { case 'setData': case 'insert': case 'update': case 'remove': this._refresh(); break; default: break; } }; /** * Gets the module's internal data collection. * @returns {Collection} */ Overview.prototype.data = function () { return this._data; }; Overview.prototype.drop = function (callback) { if (!this.isDropped()) { this._state = 'dropped'; delete this._data; delete this._collData; // Remove all source references while (this._sources.length) { this._removeSource(this._sources[0]); } delete this._sources; if (this._db && this._name) { delete this._db._overview[this._name]; } delete this._name; this.emit('drop', this); if (callback) { callback(false, true); } delete this._listeners; } return true; }; Db.prototype.overview = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof Overview) { return name; } if (this._overview && this._overview[name]) { return this._overview[name]; } this._overview = this._overview || {}; this._overview[name] = new Overview(name).db(this); self.emit('create', self._overview[name], 'overview', name); return this._overview[name]; } else { // Return an object of collection data return this._overview || {}; } }; /** * Returns an array of overviews the DB currently has. * @returns {Array} An array of objects containing details of each overview * the database is currently managing. */ Db.prototype.overviews = function () { var arr = [], item, i; for (i in this._overview) { if (this._overview.hasOwnProperty(i)) { item = this._overview[i]; arr.push({ name: i, count: item.count(), linked: item.isLinked !== undefined ? item.isLinked() : false }); } } return arr; }; Shared.finishModule('Overview'); module.exports = Overview; },{"./Collection":7,"./Document":11,"./Shared":40}],34:[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. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @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') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * 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; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * 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(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; 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], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * 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":40}],35:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the auto flag which determines if the persistence module * will automatically load data for collections the first time they are * accessed and save data whenever it changes. This is disabled by * default. * @param {Boolean} val Set to true to enable, false to disable * @returns {*} */ Shared.synthesize(Persist.prototype, 'auto', function (val) { var self = this; if (val !== undefined) { if (val) { // Hook db events this._db.on('create', function () { self._autoLoad.apply(self, arguments); }); this._db.on('change', function () { self._autoSave.apply(self, arguments); }); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save enabled'); } } else { // Un-hook db events this._db.off('create', this._autoLoad); this._db.off('change', this._autoSave); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save disbled'); } } } return this.$super.call(this, val); }); Persist.prototype._autoLoad = function (obj, objType, name) { var self = this; if (typeof obj.load === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name); } obj.load(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic load failed:', err); } self.emit('load', err, data); }); } else { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping'); } } }; Persist.prototype._autoSave = function (obj, objType, name) { var self = this; if (typeof obj.save === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name); } obj.save(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic save failed:', err); } self.emit('save', err, data); }); } }; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.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 localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) { if (callback) { callback(err, data, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); //self.setData(data); } // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":7,"./CollectionGroup":8,"./PersistCompress":36,"./PersistCrypto":37,"./Shared":40,"async":43,"localforage":79}],36:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":40,"pako":80}],37:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":40,"crypto-js":52}],38:[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) { 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); delete this._listeners; } 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":40}],39:[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 () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],40:[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.670', 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]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @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. */ '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); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ '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":20,"./Mixin.ChainReactor":21,"./Mixin.Common":22,"./Mixin.Constants":23,"./Mixin.Events":24,"./Mixin.Matching":25,"./Mixin.Sorting":26,"./Mixin.Tags":27,"./Mixin.Triggers":28,"./Mixin.Updating":29,"./Overload":32}],41:[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 = {}; },{}],42:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'), Path, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.Matching'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; Path = Shared.modules.Path; sharedPathSolver = new Path(); View.prototype.init = function (name, query, options) { var self = this; this.sharedPathSolver = sharedPathSolver; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._data = new Collection(this.name() + '_internal'); }; /** * This reactor IO node is given data changes from source data and * then acts as a firewall process between the source and view data. * Data needs to meet the requirements this IO node imposes before * the data is passed down the reactor chain (to the view). This * allows us to intercept data changes from the data source and act * on them such as applying transforms, checking the data matches * the view's query, applying joins to the data etc before sending it * down the reactor chain via the this.chainSend() calls. * * Update packets are especially complex to handle because an update * on the underlying source data could translate into an insert, * update or remove call on the view. Take a scenario where the view's * query limits the data see from the source. If the source data is * updated and the data now falls inside the view's query limitations * the data is technically now an insert on the view, not an update. * The same is true in reverse where the update becomes a remove. If * the updated data already exists in the view and will still exist * after the update operation then the update can remain an update. * @param {Object} chainPacket The chain reactor packet representing the * data operation that has just been processed on the source data. * @param {View} self The reference to the view we are operating for. * @private */ View.prototype._handleChainIO = function (chainPacket, self) { var type = chainPacket.type, hasActiveJoin, hasActiveQuery, hasTransformIn, sharedData; // NOTE: "self" in this context is the view instance. // NOTE: "this" in this context is the ReactorIO node sitting in // between the source (sender) and the destination (listener) and // in this case the source is the view's "from" data source and the // destination is the view's _data collection. This means // that "this.chainSend()" is asking the ReactorIO node to send the // packet on to the destination listener. // EARLY EXIT: Check that the packet is not a CRUD operation if (type !== 'setData' && type !== 'insert' && type !== 'update' && type !== 'remove') { // This packet is NOT a CRUD operation packet so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We only need to check packets under three conditions // 1) We have a limiting query on the view "active query", // 2) We have a query options with a $join clause on the view "active join" // 3) We have a transformIn operation registered on the view. // If none of these conditions exist we can just allow the chain // packet to proceed as normal hasActiveJoin = Boolean(self._querySettings.options && self._querySettings.options.$join); hasActiveQuery = Boolean(self._querySettings.query); hasTransformIn = self._data._transformIn !== undefined; // EARLY EXIT: Check for any complex operation flags and if none // exist, send the packet on and exit early if (!hasActiveJoin && !hasActiveQuery && !hasTransformIn) { // We don't have any complex operation flags so exit early! // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } // We have either an active query, active join or a transformIn // function registered on the view // We create a shared data object here so that the disparate method // calls can share data with each other via this object whilst // still remaining separate methods to keep code relatively clean. sharedData = { dataArr: [], removeArr: [] }; // Check the packet type to get the data arrays to work on if (chainPacket.type === 'insert') { // Check if the insert data is an array if (chainPacket.data.dataSet instanceof Array) { // Use the insert data array sharedData.dataArr = chainPacket.data.dataSet; } else { // Generate an array from the single insert object sharedData.dataArr = [chainPacket.data.dataSet]; } } else if (chainPacket.type === 'update') { // Use the dataSet array sharedData.dataArr = chainPacket.data.dataSet; } else if (chainPacket.type === 'remove') { if (chainPacket.data.dataSet instanceof Array) { // Use the remove data array sharedData.removeArr = chainPacket.data.dataSet; } else { // Generate an array from the single remove object sharedData.removeArr = [chainPacket.data.dataSet]; } } // Safety check if (!(sharedData.dataArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: dataArr being processed by chain reactor in View class is inconsistent!'); sharedData.dataArr = []; } if (!(sharedData.removeArr instanceof Array)) { // This shouldn't happen, let's log it console.warn('WARNING: removeArr being processed by chain reactor in View class is inconsistent!'); sharedData.removeArr = []; } // We need to operate in this order: // 1) Check if there is an active join - active joins are operated // against the SOURCE data. The joined data can potentially be // utilised by any active query or transformIn so we do this step first. // 2) Check if there is an active query - this is a query that is run // against the SOURCE data after any active joins have been resolved // on the source data. This allows an active query to operate on data // that would only exist after an active join has been executed. // If the source data does not fall inside the limiting factors of the // active query then we add it to a removal array. If it does fall // inside the limiting factors when we add it to an upsert array. This // is because data that falls inside the query could end up being // either new data or updated data after a transformIn operation. // 3) Check if there is a transformIn function. If a transformIn function // exist we run it against the data after doing any active join and // active query. if (hasActiveJoin) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } self._handleChainIO_ActiveJoin(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveJoin'); } } if (hasActiveQuery) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } self._handleChainIO_ActiveQuery(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_ActiveQuery'); } } if (hasTransformIn) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } self._handleChainIO_TransformIn(chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_TransformIn'); } } // Check if we still have data to operate on and exit // if there is none left if (!sharedData.dataArr.length && !sharedData.removeArr.length) { // There is no more data to operate on, exit without // sending any data down the chain reactor (return true // will tell reactor to exit without continuing)! return true; } // Grab the public data collection's primary key sharedData.pk = self._data.primaryKey(); // We still have data left, let's work out how to handle it // first let's loop through the removals as these are easy if (sharedData.removeArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } self._handleChainIO_RemovePackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_RemovePackets'); } } if (sharedData.dataArr.length) { if (this.debug()) { console.time(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } self._handleChainIO_UpsertPackets(this, chainPacket, sharedData); if (this.debug()) { console.timeEnd(this.logIdentifier() + ' :: _handleChainIO_UpsertPackets'); } } // Now return true to tell the chain reactor not to propagate // the data itself as we have done all that work here return true; }; View.prototype._handleChainIO_ActiveJoin = function (chainPacket, sharedData) { var dataArr = sharedData.dataArr, removeArr; // Since we have an active join, all we need to do is operate // the join clause on each item in the packet's data array. removeArr = this.applyJoin(dataArr, this._querySettings.options.$join, {}, {}); // Now that we've run our join keep in mind that joins can exclude data // if there is no matching joined data and the require: true clause in // the join options is enabled. This means we have to store a removal // array that tells us which items from the original data we sent to // join did not match the join data and were set with a require flag. // Now that we have our array of items to remove, let's run through the // original data and remove them from there. this.spliceArrayByIndexList(dataArr, removeArr); // Make sure we add any items we removed to the shared removeArr sharedData.removeArr = sharedData.removeArr.concat(removeArr); }; View.prototype._handleChainIO_ActiveQuery = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, i; // Now we need to run the data against the active query to // see if the data should be in the final data list or not, // so we use the _match method. // Loop backwards so we can safely splice from the array // while we are looping for (i = dataArr.length - 1; i >= 0; i--) { if (!self._match(dataArr[i], self._querySettings.query, self._querySettings.options, 'and', {})) { // The data didn't match the active query, add it // to the shared removeArr sharedData.removeArr.push(dataArr[i]); // Now remove it from the shared dataArr dataArr.splice(i, 1); } } }; View.prototype._handleChainIO_TransformIn = function (chainPacket, sharedData) { var self = this, dataArr = sharedData.dataArr, removeArr = sharedData.removeArr, dataIn = self._data._transformIn, i; // At this stage we take the remaining items still left in the data // array and run our transformIn method on each one, modifying it // from what it was to what it should be on the view. We also have // to run this on items we want to remove too because transforms can // affect primary keys and therefore stop us from identifying the // correct items to run removal operations on. // It is important that these are transformed BEFORE they are passed // to the CRUD methods because we use the CU data to check the position // of the item in the array and that can only happen if it is already // pre-transformed. The removal stuff also needs pre-transformed // because ids can be modified by a transform. for (i = 0; i < dataArr.length; i++) { // Assign the new value dataArr[i] = dataIn(dataArr[i]); } for (i = 0; i < removeArr.length; i++) { // Assign the new value removeArr[i] = dataIn(removeArr[i]); } }; View.prototype._handleChainIO_RemovePackets = function (ioObj, chainPacket, sharedData) { var $or = [], pk = sharedData.pk, removeArr = sharedData.removeArr, packet = { dataSet: removeArr, query: { $or: $or } }, orObj, i; for (i = 0; i < removeArr.length; i++) { orObj = {}; orObj[pk] = removeArr[i][pk]; $or.push(orObj); } ioObj.chainSend('remove', packet); }; View.prototype._handleChainIO_UpsertPackets = function (ioObj, chainPacket, sharedData) { var data = this._data, primaryIndex = data._primaryIndex, primaryCrc = data._primaryCrc, pk = sharedData.pk, dataArr = sharedData.dataArr, arrItem, insertArr = [], updateArr = [], query, i; // Let's work out what type of operation this data should // generate between an insert or an update. for (i = 0; i < dataArr.length; i++) { arrItem = dataArr[i]; // Check if the data already exists in the data if (primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (primaryCrc.get(arrItem[pk]) !== this.hash(arrItem[pk])) { // The document exists in the data collection but data differs, update required updateArr.push(arrItem); } } else { // The document is missing from this collection, insert required insertArr.push(arrItem); } } if (insertArr.length) { ioObj.chainSend('insert', { dataSet: insertArr }); } if (updateArr.length) { for (i = 0; i < updateArr.length; i++) { arrItem = updateArr[i]; query = {}; query[pk] = arrItem[pk]; ioObj.chainSend('update', { query: query, update: arrItem, dataSet: [arrItem] }); } } }; /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this._data.findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this._data.findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._data.findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this._data.findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._data; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); // Remove the current reference to the _from since we // are about to replace it with a new one delete this._from; } // Check if we have an existing reactor io that links the // previous _from source to the view's internal data if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } // Check if we were passed a source name rather than a // reference to a source object if (typeof(source) === 'string') { // We were passed a name, assume it is a collection and // get the reference to the collection of that name source = this._db.collection(source); } // Check if we were passed a reference to a view rather than // a collection. Views need to be handled slightly differently // since their data is stored in an internal data collection // rather than actually being a direct data source themselves. if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source._data; if (this.debug()) { console.log(this.logIdentifier() + ' Using internal data "' + source.instanceIdentifier() + '" for IO graph linking'); } } // Assign the new data source as the view's _from this._from = source; // Hook the new data source's drop event so we can unhook // it as a data source if it gets dropped. This is important // so that we don't run into problems using a dropped source // for active data. this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's _from source and determines how they should be interpreted by // this view. See the _handleChainIO() method which does all the chain packet // processing for the view. this._io = new ReactorIO(this._from, this, function (chainPacket) { return self._handleChainIO.call(this, chainPacket, self); }); // Set the view's internal data primary key to the same as the // current active _from data source this._data.primaryKey(source.primaryKey()); // Do the initial data lookup and populate the view's internal data // since at this point we don't actually have any data in the view // yet. var collData = source.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData, {}, callback); // If we have an active query and that query has an $orderBy clause, // update our active bucket which allows us to keep track of where // data should be placed in our internal data array. This is about // ordering of data and making sure that we maintain an ordered array // so that if we have data-binding we can place an item in the data- // bound view at the correct location. Active buckets use quick-sort // algorithms to quickly determine the position of an item inside an // existing array based on a sort protocol. if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data: ' + chainPacket.type); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._data.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._data.setData(collData); // Rebuild active bucket as well 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() + '"'); } // Make sure we are working with an array if (!(chainPacket.data.dataSet instanceof Array)) { chainPacket.data.dataSet = [chainPacket.data.dataSet]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data.dataSet; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._data._insertHandle(arr[index], insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._data._data.length; this._data._insertHandle(chainPacket.data.dataSet, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._data.name() + '"'); } primaryKey = this._data.primaryKey(); // Do the update updates = this._data._handleUpdate( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._data._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._data._updateSpliceMove(this._data._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._data.name() + '"'); } this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._data.ensureIndex.apply(this._data, arguments); }; /** /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._data.on.apply(this._data, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._data.off.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._data.emit.apply(this._data, arguments); }; /** * Emits an event. * @see Mixin.Events::deferEmit() */ View.prototype.deferEmit = function () { return this._data.deferEmit.apply(this._data, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { return this._data.distinct(key, query, options); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this._data.primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._data) { this._data.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._data; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this._querySettings.query; }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._data.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._data.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; /** * Clears the existing active bucket and builds a new one based * on the passed orderBy object (if one is passed). * @param {Object=} orderBy The orderBy object describing how to * order any data. */ View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._data._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._data.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { var self = this, refreshResults, joinArr, i, k; if (this._from) { // Clear the private data collection which will propagate to the public data // collection automatically via the chain reactor node between them this._data.remove(); // Grab all the data from the underlying data source refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); // Insert the underlying data into the private data collection this._data.insert(refreshResults); // Store the current cursor data this._data._data.$cursor = refreshResults.$cursor; this._data._data.$cursor = refreshResults.$cursor; } if (this._querySettings && this._querySettings.options && this._querySettings.options.$join && this._querySettings.options.$join.length) { // Define the change handler method self.__joinChange = self.__joinChange || function () { self._joinChange(); }; // Check for existing join collections if (this._joinCollections && this._joinCollections.length) { // Loop the join collections and remove change listeners // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).off('immediateChange', self.__joinChange); } } // Now start hooking any new / existing joins joinArr = this._querySettings.options.$join; this._joinCollections = []; // Loop the joined collections and hook change events for (i = 0; i < joinArr.length; i++) { for (k in joinArr[i]) { if (joinArr[i].hasOwnProperty(k)) { this._joinCollections.push(k); } } } if (this._joinCollections.length) { // Loop the collections and hook change events for (i = 0; i < this._joinCollections.length; i++) { this._db.collection(this._joinCollections[i]).on('immediateChange', self.__joinChange); } } } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Handles when a change has occurred on a collection that is joined * by query to this view. * @param objName * @param objType * @private */ View.prototype._joinChange = function (objName, objType) { this.emit('joinChange'); // TODO: This is a really dirty solution because it will require a complete // TODO: rebuild of the view data. We need to implement an IO handler to // TODO: selectively update the data of the view based on the joined // TODO: collection data operation. // FIXME: This isnt working, major performance killer, invest in some IO from chain reactor to make this a targeted call this.refresh(); }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { return this._data.count.apply(this._data, arguments); }; // Call underlying View.prototype.subset = function () { return this._data.subset.apply(this._data, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" * and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var currentSettings, newSettings; currentSettings = this._data.transform(); this._data.transform(obj); newSettings = this._data.transform(); // Check if transforms are enabled, a dataIn method is set and these // settings did not match the previous transform settings if (newSettings.enabled && newSettings.dataIn && (currentSettings.enabled !== newSettings.enabled || currentSettings.dataIn !== newSettings.dataIn)) { // The data in the view is now stale, refresh it this.refresh(); } return newSettings; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return this._data.filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.data = function () { return this._data; }; /** * @see Collection.indexOf * @returns {*} */ View.prototype.indexOf = function () { return this._data.indexOf.apply(this._data, arguments); }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this._data.db(db); // Apply the same debug settings this.debug(db.debug()); this._data.debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} name The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (name) { var self = this; // Handle being passed an instance if (name instanceof View) { return name; } if (this._view[name]) { return this._view[name]; } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + name); } this._view[name] = new View(name).db(this); self.emit('create', self._view[name], 'view', name); return this._view[name]; }; /** * Determine if a view with the passed name already exists. * @param {String} name The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (name) { return Boolean(this._view[name]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":7,"./CollectionGroup":8,"./Overload":32,"./ReactorIO":38,"./Shared":40}],43:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (!callback) { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has inexistant dependency'); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback(null); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { while(workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":78}],44:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],45:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":46}],46:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],47:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":46}],48:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":46}],49:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":46,"./hmac":51,"./sha1":70}],50:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":45,"./core":46}],51:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":46}],52:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // 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"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./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(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":46}],54:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":46}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":45,"./core":46}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby [email protected] */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":45,"./core":46}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":45,"./core":46}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":45,"./core":46}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":45,"./core":46}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":45,"./core":46}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":45,"./core":46}],62:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":45,"./core":46}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":45,"./core":46}],64:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":45,"./core":46}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":46,"./hmac":51,"./sha1":70}],66:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],67:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],68:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],69:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.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]); var _zr = WordArray.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]); var _sl = WordArray.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 ]); var _sr = WordArray.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 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":46}],70:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":46}],71:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":46,"./sha256":72}],72:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":46}],73:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":46,"./x64-core":77}],74:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":46,"./sha512":75,"./x64-core":77}],75:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":46,"./x64-core":77}],76:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 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 ]; // Permuted Choice 2 constants var PC2 = [ 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 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],77:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":46}],78:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(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; clearTimeout(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) { setTimeout(drainQueue, 0); } }; // 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; }; },{}],79:[function(_dereq_,module,exports){ (function (process,global){ /*! localForage -- Offline Storage, Improved Version 1.3.0 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function() { var define, requireModule, _dereq_, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = _dereq_ = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], 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(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.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 var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node 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() { local.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; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length 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. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; 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 isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.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 var promise = RSVP.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 @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }());(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["localforage"] = factory(); else root["localforage"] = 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'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { 'use strict'; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function (self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function () { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = (function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof options === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); promise.then(callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = (function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return new Promise(function (resolve, reject) { resolve(__webpack_require__(1)); }); case self.LOCALSTORAGE: return new Promise(function (resolve, reject) { resolve(__webpack_require__(2)); }); case self.WEBSQL: return new Promise(function (resolve, reject) { resolve(__webpack_require__(4)); }); } } else if (CustomDrivers[driverName]) { return Promise.resolve(CustomDrivers[driverName]); } return Promise.reject(new Error('Driver not found.')); })(); getDriverPromise.then(callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }); if (callback && typeof callback === 'function') { serializerPromise.then(function (result) { callback(result); }); } return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); promise.then(callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })['catch'](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { return Promise.resolve(); }) : Promise.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })['catch'](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; }); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; })(); var localForage = new LocalForage(); exports['default'] = localForage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({ status: xhr.status, response: xhr.response }); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function (resolve, reject) { var blob = _createBlob([''], { type: 'image/png' }); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function () { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function (e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function (res) { resolve(!!(res && res.type === 'image/png')); }, function () { resolve(false); }).then(function () { URL.revokeObjectURL(url); }); }; }; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(this); // Create an array of readiness of the related localForages. var readyPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== this) { // Don't wait for itself... readyPromises.push(forage.ready()['catch'](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise.all(readyPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k in forages) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _getConnection(dbInfo, upgradeNeeded) { return new Promise(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = indexedDB.open.apply(indexedDB, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); }; }); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function (blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = asyncStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = localStorageWrapper; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; (function () { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; exports['default'] = localforageSerializer; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function () { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = webSQLStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ } /******/ ]) }); ; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":78}],80:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":81,"./lib/inflate":82,"./lib/utils/common":83,"./lib/zlib/constants":86}],81:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ var Deflate = function(options) { this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } }; /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function(status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate alrorythm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":83,"./utils/strings":84,"./zlib/deflate.js":88,"./zlib/messages":93,"./zlib/zstream":95}],82:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var gzheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new gzheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); }; /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function(status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":83,"./utils/strings":84,"./zlib/constants":86,"./zlib/gzheader":89,"./zlib/inflate.js":91,"./zlib/messages":93,"./zlib/zstream":95}],83:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs+len), dest_offs); return; } // Fallback to ordinary array for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i=0, l=chunks.length; i<l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i=0, l=chunks.length; i<l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],84:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q=0; q<256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i=0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function(buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function(str) { var buf = new utils.Buf8(str.length); for (var i=0, len=buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":83}],85:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],86:[function(_dereq_,module,exports){ module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ 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, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ 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, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],87:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n =0; n < 256; n++) { c = n; for (var k =0; k < 8; k++) { c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],88:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only (s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH-1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length-1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH-1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var Config = function (good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; }; var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":83,"./adler32":85,"./crc32":87,"./messages":93,"./trees":94}],89:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],90:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],91:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function ZSWAP32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window,src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = ZSWAP32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = {bits: state.lenbits}; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = {bits: state.lenbits}; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = {bits: state.distbits}; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":83,"./adler32":85,"./crc32":87,"./inffast":90,"./inftrees":92}],92:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 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 ]; var lext = [ /* Length codes 257..285 extra */ 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 ]; var dbase = [ /* Distance codes 0..29 base */ 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 ]; var dext = [ /* Distance codes 0..29 extra */ 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 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i=0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":83}],93:[function(_dereq_,module,exports){ 'use strict'; module.exports = { '2': 'need dictionary', /* Z_NEED_DICT 2 */ '1': 'stream end', /* Z_STREAM_END 1 */ '0': '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],94:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ var extra_lbits = /* extra bits for each length code */ [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]; var extra_dbits = /* extra bits for each distance code */ [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]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES+2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; }; var static_l_desc; var static_d_desc; var static_bl_desc; var TreeDesc = function(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ }; function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short (s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max+1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n*2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n-base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m*2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; tree[m*2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n*2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n*2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n*2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n*2 + 1]/*.Len*/ = 5; static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n*2; var _m2 = m*2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n*2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node*2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6*2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10*2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138*2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3*(max_blindex+1) + 5+5+4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len+3+7) >>> 3; static_lenb = (s.static_len+3+7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc*2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":83}],95:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}]},{},[1]);
__tests__/index.ios.js
elderfo/elderfo-react-native-components
import 'react-native'; import React from 'react'; import Index from '../index.ios.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/components/weather-panel.js
sebastianrb/react-redux-weather-app
import React from 'react'; import EasyTransition from 'react-easy-transition'; import { Link } from "react-router-dom"; import { transitionSetting } from "../index.js"; import { connect } from "react-redux"; import conditions from "./conditions-object"; import WeatherDay from "./weather-day"; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import CityHeader from "./city-header"; let daysListResult; class WeatherPanel extends React.Component { constructor(props) { super(props); this.state = { conditions: conditions, daysPlaceholder: [ { dayTitle: "Now", classText: "now" }, { dayTitle: "Tomorrow", classText: "tomorrow" }, { dayTitle: "The Next Day", classText: "next-day" } ] }; } renderDayList() { if(this.props.weather.count === 0) { return daysListResult = this.state.daysPlaceholder.map((dayObject) => { return ( <WeatherDay dataPresent="noResult" classTest={dayObject.classText} dayTitle={dayObject.dayTitle} key={`${dayObject.dayTitle}`} lastTerm={this.props.lastTerm} /> ); }); } else if(Object.keys(this.props.weather).length === 0) { //default on page load return daysListResult = this.state.daysPlaceholder.map((dayObject) => { return ( <WeatherDay dataPresent={false} classTest={dayObject.classText} dayTitle={dayObject.dayTitle} key={`${dayObject.dayTitle}`} /> ); }); } else { //return days with data flowing through return daysListResult = this.props.weather.days.map((day) => { return ( <WeatherDay dataPresent={true} dayName={day.day} city={this.props.weather.location.city} caption={day.caption} imageURL={this.state.conditions[day.conditionCode].image} conditionDescription={this.state.conditions[day.conditionCode].description} currentTemp={(day.currentTemp ? day.currentTemp : "")} high={day.high} low={day.low} humidity={(day.humidity ? day.humidity : "")} key={`${day.day}-${this.props.weather.location.city}`} /> ); }); } } // renderCityHeader() { // if(Object.keys(this.props.weather).length > 0 && Object.keys(this.props.weather).length !== 1) { // return ( // <h3 className="city-name-header">Here's the forecast for <span>{this.props.weather.location.city}, {this.props.weather.location.region}, {this.props.weather.location.country}</span></h3> // ); // } else { // return ( // "" // ); // } // } render() { const transitionOptions = { transitionName: "fade", transitionEnterTimeout: 100, transitionLeaveTimeout: 0 }; return ( <EasyTransition path={location.pathname} initialStyle={{opacity: 0, transform: "scale(.9)"}} transition={transitionSetting} finalStyle={{opacity: 1, transform: "scale(1)"}} > <div className="weather-panel"> {/* {this.renderCityHeader()}*/} <CityHeader weather={this.props.weather} headerText="Here's the forecast for" panelName="Weather" /> <ul className="weather-panel__day-list"> <ReactCSSTransitionGroup {...transitionOptions}> {this.renderDayList()} </ReactCSSTransitionGroup> </ul> </div> </EasyTransition> ); } } //connect to redux function mapStateToProps(state) { return { weather: state.weather, lastTerm: state.lastTerm } } export default connect(mapStateToProps)(WeatherPanel);
node_modules/core-js/client/library.js
vision89/vanilla-javascript-tag-input
/** * core-js 1.2.6 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2015 Denis Pushkarev */ !function(__e, __g, undefined){ 'use strict'; /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(1); __webpack_require__(32); __webpack_require__(40); __webpack_require__(42); __webpack_require__(44); __webpack_require__(46); __webpack_require__(48); __webpack_require__(49); __webpack_require__(50); __webpack_require__(51); __webpack_require__(52); __webpack_require__(53); __webpack_require__(54); __webpack_require__(55); __webpack_require__(56); __webpack_require__(57); __webpack_require__(58); __webpack_require__(59); __webpack_require__(60); __webpack_require__(62); __webpack_require__(63); __webpack_require__(64); __webpack_require__(65); __webpack_require__(66); __webpack_require__(67); __webpack_require__(68); __webpack_require__(70); __webpack_require__(71); __webpack_require__(72); __webpack_require__(74); __webpack_require__(75); __webpack_require__(76); __webpack_require__(78); __webpack_require__(79); __webpack_require__(80); __webpack_require__(81); __webpack_require__(82); __webpack_require__(83); __webpack_require__(84); __webpack_require__(85); __webpack_require__(86); __webpack_require__(87); __webpack_require__(88); __webpack_require__(89); __webpack_require__(90); __webpack_require__(92); __webpack_require__(94); __webpack_require__(98); __webpack_require__(99); __webpack_require__(101); __webpack_require__(102); __webpack_require__(106); __webpack_require__(112); __webpack_require__(113); __webpack_require__(116); __webpack_require__(118); __webpack_require__(120); __webpack_require__(122); __webpack_require__(123); __webpack_require__(124); __webpack_require__(131); __webpack_require__(134); __webpack_require__(135); __webpack_require__(137); __webpack_require__(138); __webpack_require__(139); __webpack_require__(140); __webpack_require__(141); __webpack_require__(142); __webpack_require__(143); __webpack_require__(144); __webpack_require__(145); __webpack_require__(146); __webpack_require__(147); __webpack_require__(148); __webpack_require__(150); __webpack_require__(151); __webpack_require__(152); __webpack_require__(153); __webpack_require__(154); __webpack_require__(155); __webpack_require__(157); __webpack_require__(158); __webpack_require__(159); __webpack_require__(160); __webpack_require__(162); __webpack_require__(163); __webpack_require__(165); __webpack_require__(166); __webpack_require__(168); __webpack_require__(169); __webpack_require__(170); __webpack_require__(171); __webpack_require__(174); __webpack_require__(109); __webpack_require__(176); __webpack_require__(175); __webpack_require__(177); __webpack_require__(178); __webpack_require__(179); __webpack_require__(180); __webpack_require__(181); __webpack_require__(183); __webpack_require__(184); __webpack_require__(185); __webpack_require__(186); __webpack_require__(187); module.exports = __webpack_require__(188); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , $export = __webpack_require__(3) , DESCRIPTORS = __webpack_require__(8) , createDesc = __webpack_require__(10) , html = __webpack_require__(11) , cel = __webpack_require__(12) , has = __webpack_require__(14) , cof = __webpack_require__(15) , invoke = __webpack_require__(16) , fails = __webpack_require__(9) , anObject = __webpack_require__(17) , aFunction = __webpack_require__(7) , isObject = __webpack_require__(13) , toObject = __webpack_require__(18) , toIObject = __webpack_require__(20) , toInteger = __webpack_require__(22) , toIndex = __webpack_require__(23) , toLength = __webpack_require__(24) , IObject = __webpack_require__(21) , IE_PROTO = __webpack_require__(25)('__proto__') , createArrayMethod = __webpack_require__(26) , arrayIndexOf = __webpack_require__(31)(false) , ObjectProto = Object.prototype , ArrayProto = Array.prototype , arraySlice = ArrayProto.slice , arrayJoin = ArrayProto.join , defineProperty = $.setDesc , getOwnDescriptor = $.getDesc , defineProperties = $.setDescs , factories = {} , IE8_DOM_DEFINE; if(!DESCRIPTORS){ IE8_DOM_DEFINE = !fails(function(){ return defineProperty(cel('div'), 'a', {get: function(){ return 7; }}).a != 7; }); $.setDesc = function(O, P, Attributes){ if(IE8_DOM_DEFINE)try { return defineProperty(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)anObject(O)[P] = Attributes.value; return O; }; $.getDesc = function(O, P){ if(IE8_DOM_DEFINE)try { return getOwnDescriptor(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!ObjectProto.propertyIsEnumerable.call(O, P), O[P]); }; $.setDescs = defineProperties = function(O, Properties){ anObject(O); var keys = $.getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)$.setDesc(O, P = keys[i++], Properties[P]); return O; }; } $export($export.S + $export.F * !DESCRIPTORS, 'Object', { // 19.1.2.6 / 15.2.3.3 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $.getDesc, // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) defineProperty: $.setDesc, // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) defineProperties: defineProperties }); // IE 8- don't enum bug keys var keys1 = ('constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,' + 'toLocaleString,toString,valueOf').split(',') // Additional keys for getOwnPropertyNames , keys2 = keys1.concat('length', 'prototype') , keysLen1 = keys1.length; // Create object with `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = cel('iframe') , i = keysLen1 , gt = '>' , iframeDocument; iframe.style.display = 'none'; html.appendChild(iframe); iframe.src = 'javascript:'; // eslint-disable-line no-script-url // createDict = iframe.contentWindow.Object; // html.removeChild(iframe); iframeDocument = iframe.contentWindow.document; iframeDocument.open(); iframeDocument.write('<script>document.F=Object</script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict.prototype[keys1[i]]; return createDict(); }; var createGetKeys = function(names, length){ return function(object){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; }; var Empty = function(){}; $export($export.S, 'Object', { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) getPrototypeOf: $.getProto = $.getProto || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }, // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) getOwnPropertyNames: $.getNames = $.getNames || createGetKeys(keys2, keys2.length, true), // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) create: $.create = $.create || function(O, /*?*/Properties){ var result; if(O !== null){ Empty.prototype = anObject(O); result = new Empty(); Empty.prototype = null; // add "__proto__" for Object.getPrototypeOf shim result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : defineProperties(result, Properties); }, // 19.1.2.14 / 15.2.3.14 Object.keys(O) keys: $.getKeys = $.getKeys || createGetKeys(keys1, keysLen1, false) }); var construct = function(F, len, args){ if(!(len in factories)){ for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']'; factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); } return factories[len](F, args); }; // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) $export($export.P, 'Function', { bind: function bind(that /*, args... */){ var fn = aFunction(this) , partArgs = arraySlice.call(arguments, 1); var bound = function(/* args... */){ var args = partArgs.concat(arraySlice.call(arguments)); return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); }; if(isObject(fn.prototype))bound.prototype = fn.prototype; return bound; } }); // fallback for not array-like ES3 strings and DOM objects $export($export.P + $export.F * fails(function(){ if(html)arraySlice.call(html); }), 'Array', { slice: function(begin, end){ var len = toLength(this.length) , klass = cof(this); end = end === undefined ? len : end; if(klass == 'Array')return arraySlice.call(this, begin, end); var start = toIndex(begin, len) , upTo = toIndex(end, len) , size = toLength(upTo - start) , cloned = Array(size) , i = 0; for(; i < size; i++)cloned[i] = klass == 'String' ? this.charAt(start + i) : this[start + i]; return cloned; } }); $export($export.P + $export.F * (IObject != Object), 'Array', { join: function join(separator){ return arrayJoin.call(IObject(this), separator === undefined ? ',' : separator); } }); // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) $export($export.S, 'Array', {isArray: __webpack_require__(28)}); var createArrayReduce = function(isRight){ return function(callbackfn, memo){ aFunction(callbackfn); var O = IObject(this) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(arguments.length < 2)for(;;){ if(index in O){ memo = O[index]; index += i; break; } index += i; if(isRight ? index < 0 : length <= index){ throw TypeError('Reduce of empty array with no initial value'); } } for(;isRight ? index >= 0 : length > index; index += i)if(index in O){ memo = callbackfn(memo, O[index], index, this); } return memo; }; }; var methodize = function($fn){ return function(arg1/*, arg2 = undefined */){ return $fn(this, arg1, arguments[1]); }; }; $export($export.P, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: $.each = $.each || methodize(createArrayMethod(0)), // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: methodize(createArrayMethod(1)), // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: methodize(createArrayMethod(2)), // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: methodize(createArrayMethod(3)), // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: methodize(createArrayMethod(4)), // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: createArrayReduce(false), // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: createArrayReduce(true), // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: methodize(arrayIndexOf), // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function(el, fromIndex /* = @[*-1] */){ var O = toIObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, toInteger(fromIndex)); if(index < 0)index = toLength(length + index); for(;index >= 0; index--)if(index in O)if(O[index] === el)return index; return -1; } }); // 20.3.3.1 / 15.9.4.4 Date.now() $export($export.S, 'Date', {now: function(){ return +new Date; }}); var lz = function(num){ return num > 9 ? num : '0' + num; }; // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() // PhantomJS / old WebKit has a broken implementations $export($export.P + $export.F * (fails(function(){ return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z'; }) || !fails(function(){ new Date(NaN).toISOString(); })), 'Date', { toISOString: function toISOString(){ if(!isFinite(this))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; } }); /***/ }, /* 2 */ /***/ function(module, exports) { var $Object = Object; module.exports = { create: $Object.create, getProto: $Object.getPrototypeOf, isEnum: {}.propertyIsEnumerable, getDesc: $Object.getOwnPropertyDescriptor, setDesc: $Object.defineProperty, setDescs: $Object.defineProperties, getKeys: $Object.keys, getNames: $Object.getOwnPropertyNames, getSymbols: $Object.getOwnPropertySymbols, each: [].forEach }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , core = __webpack_require__(5) , ctx = __webpack_require__(6) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && key in target; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(param){ return this instanceof C ? new C(param) : C(param); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out; } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap module.exports = $export; /***/ }, /* 4 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 5 */ /***/ function(module, exports) { var core = module.exports = {version: '1.2.6'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(7); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 7 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(9)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 9 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 10 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(4).document && document.documentElement; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(13) , document = __webpack_require__(4).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 13 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 14 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 15 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 16 */ /***/ function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(13); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(19); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 19 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(21) , defined = __webpack_require__(19); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(15); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 22 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(22) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(22) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 25 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var ctx = __webpack_require__(6) , IObject = __webpack_require__(21) , toObject = __webpack_require__(18) , toLength = __webpack_require__(24) , asc = __webpack_require__(27); module.exports = function(TYPE){ 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 = toObject($this) , self = IObject(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = IS_MAP ? asc($this, length) : IS_FILTER ? asc($this, 0) : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var isObject = __webpack_require__(13) , isArray = __webpack_require__(28) , SPECIES = __webpack_require__(29)('species'); module.exports = function(original, length){ var C; if(isArray(original)){ C = original.constructor; // cross-realm fallback if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined; if(isObject(C)){ C = C[SPECIES]; if(C === null)C = undefined; } } return new (C === undefined ? Array : C)(length); }; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(15); module.exports = Array.isArray || function(arg){ return cof(arg) == 'Array'; }; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var store = __webpack_require__(30)('wks') , uid = __webpack_require__(25) , Symbol = __webpack_require__(4).Symbol; module.exports = function(name){ return store[name] || (store[name] = Symbol && Symbol[name] || (Symbol || uid)('Symbol.' + name)); }; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(20) , toLength = __webpack_require__(24) , toIndex = __webpack_require__(23); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // ECMAScript 6 symbols shim var $ = __webpack_require__(2) , global = __webpack_require__(4) , has = __webpack_require__(14) , DESCRIPTORS = __webpack_require__(8) , $export = __webpack_require__(3) , redefine = __webpack_require__(33) , $fails = __webpack_require__(9) , shared = __webpack_require__(30) , setToStringTag = __webpack_require__(35) , uid = __webpack_require__(25) , wks = __webpack_require__(29) , keyOf = __webpack_require__(36) , $names = __webpack_require__(37) , enumKeys = __webpack_require__(38) , isArray = __webpack_require__(28) , anObject = __webpack_require__(17) , toIObject = __webpack_require__(20) , createDesc = __webpack_require__(10) , getDesc = $.getDesc , setDesc = $.setDesc , _create = $.create , getNames = $names.get , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , setter = false , HIDDEN = wks('_hidden') , isEnum = $.isEnum , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , useNative = typeof $Symbol == 'function' , ObjectProto = Object.prototype; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(setDesc({}, 'a', { get: function(){ return setDesc(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = getDesc(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; setDesc(it, key, D); if(protoDesc && it !== ObjectProto)setDesc(ObjectProto, key, protoDesc); } : setDesc; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol.prototype); sym._k = tag; DESCRIPTORS && setter && setSymbolDesc(ObjectProto, tag, { configurable: true, set: function(value){ if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); } }); return sym; }; var isSymbol = function(it){ return typeof it == 'symbol'; }; var $defineProperty = function defineProperty(it, key, D){ if(D && has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))setDesc(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return setDesc(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key); return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ var D = getDesc(it = toIObject(it), key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = getNames(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(!has(AllSymbols, key = names[i++]) && key != HIDDEN)result.push(key); return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var names = getNames(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i)if(has(AllSymbols, key = names[i++]))result.push(AllSymbols[key]); return result; }; var $stringify = function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , $$ = arguments , replacer, $replacer; while($$.length > i)args.push($$[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); }; var buggyJSON = $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; }); // 19.4.1.1 Symbol([description]) if(!useNative){ $Symbol = function Symbol(){ if(isSymbol(this))throw TypeError('Symbol is not a constructor'); return wrap(uid(arguments.length > 0 ? arguments[0] : undefined)); }; redefine($Symbol.prototype, 'toString', function toString(){ return this._k; }); isSymbol = function(it){ return it instanceof $Symbol; }; $.create = $create; $.isEnum = $propertyIsEnumerable; $.getDesc = $getOwnPropertyDescriptor; $.setDesc = $defineProperty; $.setDescs = $defineProperties; $.getNames = $names.get = $getOwnPropertyNames; $.getSymbols = $getOwnPropertySymbols; if(DESCRIPTORS && !__webpack_require__(39)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } } var symbolStatics = { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ return keyOf(SymbolRegistry, key); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }; // 19.4.2.2 Symbol.hasInstance // 19.4.2.3 Symbol.isConcatSpreadable // 19.4.2.4 Symbol.iterator // 19.4.2.6 Symbol.match // 19.4.2.8 Symbol.replace // 19.4.2.9 Symbol.search // 19.4.2.10 Symbol.species // 19.4.2.11 Symbol.split // 19.4.2.12 Symbol.toPrimitive // 19.4.2.13 Symbol.toStringTag // 19.4.2.14 Symbol.unscopables $.each.call(( 'hasInstance,isConcatSpreadable,iterator,match,replace,search,' + 'species,split,toPrimitive,toStringTag,unscopables' ).split(','), function(it){ var sym = wks(it); symbolStatics[it] = useNative ? sym : wrap(sym); }); setter = true; $export($export.G + $export.W, {Symbol: $Symbol}); $export($export.S, 'Symbol', symbolStatics); $export($export.S + $export.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 }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!useNative || buggyJSON), 'JSON', {stringify: $stringify}); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(34); /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , createDesc = __webpack_require__(10); module.exports = __webpack_require__(8) ? function(object, key, value){ return $.setDesc(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { var def = __webpack_require__(2).setDesc , has = __webpack_require__(14) , TAG = __webpack_require__(29)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , toIObject = __webpack_require__(20); module.exports = function(object, el){ var O = toIObject(object) , keys = $.getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(20) , getNames = __webpack_require__(2).getNames , toString = {}.toString; var windowNames = typeof window == 'object' && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return getNames(it); } catch(e){ return windowNames.slice(); } }; module.exports.get = function getOwnPropertyNames(it){ if(windowNames && toString.call(it) == '[object Window]')return getWindowNames(it); return getNames(toIObject(it)); }; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var $ = __webpack_require__(2); module.exports = function(it){ var keys = $.getKeys(it) , getSymbols = $.getSymbols; if(getSymbols){ var symbols = getSymbols(it) , isEnum = $.isEnum , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))keys.push(key); } return keys; }; /***/ }, /* 39 */ /***/ function(module, exports) { module.exports = true; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(3); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(41)}); /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.1 Object.assign(target, source, ...) var $ = __webpack_require__(2) , toObject = __webpack_require__(18) , IObject = __webpack_require__(21); // should work with symbols and should have deterministic property order (V8 bug) module.exports = __webpack_require__(9)(function(){ var a = Object.assign , A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return a({}, A)[S] != 7 || Object.keys(a({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , $$ = arguments , $$len = $$.length , index = 1 , getKeys = $.getKeys , getSymbols = $.getSymbols , isEnum = $.isEnum; while($$len > index){ var S = IObject($$[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : Object.assign; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.10 Object.is(value1, value2) var $export = __webpack_require__(3); $export($export.S, 'Object', {is: __webpack_require__(43)}); /***/ }, /* 43 */ /***/ function(module, exports) { // 7.2.9 SameValue(x, y) module.exports = Object.is || function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(3); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(45).set}); /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var getDesc = __webpack_require__(2).getDesc , isObject = __webpack_require__(13) , anObject = __webpack_require__(17); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = __webpack_require__(6)(Function.call, getDesc(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.5 Object.freeze(O) var isObject = __webpack_require__(13); __webpack_require__(47)('freeze', function($freeze){ return function freeze(it){ return $freeze && isObject(it) ? $freeze(it) : it; }; }); /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(3) , core = __webpack_require__(5) , fails = __webpack_require__(9); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.17 Object.seal(O) var isObject = __webpack_require__(13); __webpack_require__(47)('seal', function($seal){ return function seal(it){ return $seal && isObject(it) ? $seal(it) : it; }; }); /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.15 Object.preventExtensions(O) var isObject = __webpack_require__(13); __webpack_require__(47)('preventExtensions', function($preventExtensions){ return function preventExtensions(it){ return $preventExtensions && isObject(it) ? $preventExtensions(it) : it; }; }); /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.12 Object.isFrozen(O) var isObject = __webpack_require__(13); __webpack_require__(47)('isFrozen', function($isFrozen){ return function isFrozen(it){ return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; }; }); /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.13 Object.isSealed(O) var isObject = __webpack_require__(13); __webpack_require__(47)('isSealed', function($isSealed){ return function isSealed(it){ return isObject(it) ? $isSealed ? $isSealed(it) : false : true; }; }); /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.11 Object.isExtensible(O) var isObject = __webpack_require__(13); __webpack_require__(47)('isExtensible', function($isExtensible){ return function isExtensible(it){ return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; }; }); /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = __webpack_require__(20); __webpack_require__(47)('getOwnPropertyDescriptor', function($getOwnPropertyDescriptor){ return function getOwnPropertyDescriptor(it, key){ return $getOwnPropertyDescriptor(toIObject(it), key); }; }); /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__(18); __webpack_require__(47)('getPrototypeOf', function($getPrototypeOf){ return function getPrototypeOf(it){ return $getPrototypeOf(toObject(it)); }; }); /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(18); __webpack_require__(47)('keys', function($keys){ return function keys(it){ return $keys(toObject(it)); }; }); /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.7 Object.getOwnPropertyNames(O) __webpack_require__(47)('getOwnPropertyNames', function(){ return __webpack_require__(37).get; }); /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , isObject = __webpack_require__(13) , HAS_INSTANCE = __webpack_require__(29)('hasInstance') , FunctionProto = Function.prototype; // 19.2.3.6 Function.prototype[@@hasInstance](V) if(!(HAS_INSTANCE in FunctionProto))$.setDesc(FunctionProto, HAS_INSTANCE, {value: function(O){ if(typeof this != 'function' || !isObject(O))return false; if(!isObject(this.prototype))return O instanceof this; // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: while(O = $.getProto(O))if(this.prototype === O)return true; return false; }}); /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.1 Number.EPSILON var $export = __webpack_require__(3); $export($export.S, 'Number', {EPSILON: Math.pow(2, -52)}); /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.2 Number.isFinite(number) var $export = __webpack_require__(3) , _isFinite = __webpack_require__(4).isFinite; $export($export.S, 'Number', { isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); } }); /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.3 Number.isInteger(number) var $export = __webpack_require__(3); $export($export.S, 'Number', {isInteger: __webpack_require__(61)}); /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.3 Number.isInteger(number) var isObject = __webpack_require__(13) , floor = Math.floor; module.exports = function isInteger(it){ return !isObject(it) && isFinite(it) && floor(it) === it; }; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.4 Number.isNaN(number) var $export = __webpack_require__(3); $export($export.S, 'Number', { isNaN: function isNaN(number){ return number != number; } }); /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.5 Number.isSafeInteger(number) var $export = __webpack_require__(3) , isInteger = __webpack_require__(61) , abs = Math.abs; $export($export.S, 'Number', { isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= 0x1fffffffffffff; } }); /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.6 Number.MAX_SAFE_INTEGER var $export = __webpack_require__(3); $export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff}); /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.10 Number.MIN_SAFE_INTEGER var $export = __webpack_require__(3); $export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff}); /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.12 Number.parseFloat(string) var $export = __webpack_require__(3); $export($export.S, 'Number', {parseFloat: parseFloat}); /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.13 Number.parseInt(string, radix) var $export = __webpack_require__(3); $export($export.S, 'Number', {parseInt: parseInt}); /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.3 Math.acosh(x) var $export = __webpack_require__(3) , log1p = __webpack_require__(69) , sqrt = Math.sqrt , $acosh = Math.acosh; // V8 bug https://code.google.com/p/v8/issues/detail?id=3509 $export($export.S + $export.F * !($acosh && Math.floor($acosh(Number.MAX_VALUE)) == 710), 'Math', { acosh: function acosh(x){ return (x = +x) < 1 ? NaN : x > 94906265.62425156 ? Math.log(x) + Math.LN2 : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); } }); /***/ }, /* 69 */ /***/ function(module, exports) { // 20.2.2.20 Math.log1p(x) module.exports = Math.log1p || function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.5 Math.asinh(x) var $export = __webpack_require__(3); function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); } $export($export.S, 'Math', {asinh: asinh}); /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.7 Math.atanh(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { atanh: function atanh(x){ return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; } }); /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.9 Math.cbrt(x) var $export = __webpack_require__(3) , sign = __webpack_require__(73); $export($export.S, 'Math', { cbrt: function cbrt(x){ return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); } }); /***/ }, /* 73 */ /***/ function(module, exports) { // 20.2.2.28 Math.sign(x) module.exports = Math.sign || function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.11 Math.clz32(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { clz32: function clz32(x){ return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; } }); /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.12 Math.cosh(x) var $export = __webpack_require__(3) , exp = Math.exp; $export($export.S, 'Math', { cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; } }); /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.14 Math.expm1(x) var $export = __webpack_require__(3); $export($export.S, 'Math', {expm1: __webpack_require__(77)}); /***/ }, /* 77 */ /***/ function(module, exports) { // 20.2.2.14 Math.expm1(x) module.exports = Math.expm1 || function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; }; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.16 Math.fround(x) var $export = __webpack_require__(3) , sign = __webpack_require__(73) , pow = Math.pow , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); var roundTiesToEven = function(n){ return n + 1 / EPSILON - 1 / EPSILON; }; $export($export.S, 'Math', { fround: function fround(x){ var $abs = Math.abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; } }); /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) var $export = __webpack_require__(3) , abs = Math.abs; $export($export.S, 'Math', { hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , i = 0 , $$ = arguments , $$len = $$.length , larg = 0 , arg, div; while(i < $$len){ arg = abs($$[i++]); if(larg < arg){ div = larg / arg; sum = sum * div * div + 1; larg = arg; } else if(arg > 0){ div = arg / larg; sum += div * div; } else sum += arg; } return larg === Infinity ? Infinity : larg * Math.sqrt(sum); } }); /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.18 Math.imul(x, y) var $export = __webpack_require__(3) , $imul = Math.imul; // some WebKit versions fails with big numbers, some has wrong arity $export($export.S + $export.F * __webpack_require__(9)(function(){ return $imul(0xffffffff, 5) != -5 || $imul.length != 2; }), 'Math', { imul: function imul(x, y){ var UINT16 = 0xffff , xn = +x , yn = +y , xl = UINT16 & xn , yl = UINT16 & yn; return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); } }); /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.21 Math.log10(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { log10: function log10(x){ return Math.log(x) / Math.LN10; } }); /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.20 Math.log1p(x) var $export = __webpack_require__(3); $export($export.S, 'Math', {log1p: __webpack_require__(69)}); /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.22 Math.log2(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { log2: function log2(x){ return Math.log(x) / Math.LN2; } }); /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.28 Math.sign(x) var $export = __webpack_require__(3); $export($export.S, 'Math', {sign: __webpack_require__(73)}); /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.30 Math.sinh(x) var $export = __webpack_require__(3) , expm1 = __webpack_require__(77) , exp = Math.exp; // V8 near Chromium 38 has a problem with very small numbers $export($export.S + $export.F * __webpack_require__(9)(function(){ return !Math.sinh(-2e-17) != -2e-17; }), 'Math', { sinh: function sinh(x){ return Math.abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); } }); /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.33 Math.tanh(x) var $export = __webpack_require__(3) , expm1 = __webpack_require__(77) , exp = Math.exp; $export($export.S, 'Math', { tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); } }); /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.34 Math.trunc(x) var $export = __webpack_require__(3); $export($export.S, 'Math', { trunc: function trunc(it){ return (it > 0 ? Math.floor : Math.ceil)(it); } }); /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , toIndex = __webpack_require__(23) , fromCharCode = String.fromCharCode , $fromCodePoint = String.fromCodePoint; // length should be 1, old FF problem $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , $$ = arguments , $$len = $$.length , i = 0 , code; while($$len > i){ code = +$$[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , toIObject = __webpack_require__(20) , toLength = __webpack_require__(24); $export($export.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = toIObject(callSite.raw) , len = toLength(tpl.length) , $$ = arguments , $$len = $$.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < $$len)res.push(String($$[i])); } return res.join(''); } }); /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 21.1.3.25 String.prototype.trim() __webpack_require__(91)('trim', function($trim){ return function trim(){ return $trim(this, 3); }; }); /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , defined = __webpack_require__(19) , fails = __webpack_require__(9) , spaces = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF' , space = '[' + spaces + ']' , non = '\u200b\u0085' , ltrim = RegExp('^' + space + space + '*') , rtrim = RegExp(space + space + '*$'); var exporter = function(KEY, exec){ var exp = {}; exp[KEY] = exec(trim); $export($export.P + $export.F * fails(function(){ return !!spaces[KEY]() || non[KEY]() != non; }), 'String', exp); }; // 1 -> String#trimLeft // 2 -> String#trimRight // 3 -> String#trim var trim = exporter.trim = function(string, TYPE){ string = String(defined(string)); if(TYPE & 1)string = string.replace(ltrim, ''); if(TYPE & 2)string = string.replace(rtrim, ''); return string; }; module.exports = exporter; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3) , $at = __webpack_require__(93)(false); $export($export.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: function codePointAt(pos){ return $at(this, pos); } }); /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(22) , defined = __webpack_require__(19); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) 'use strict'; var $export = __webpack_require__(3) , toLength = __webpack_require__(24) , context = __webpack_require__(95) , ENDS_WITH = 'endsWith' , $endsWith = ''[ENDS_WITH]; $export($export.P + $export.F * __webpack_require__(97)(ENDS_WITH), 'String', { endsWith: function endsWith(searchString /*, endPosition = @length */){ var that = context(this, searchString, ENDS_WITH) , $$ = arguments , endPosition = $$.length > 1 ? $$[1] : undefined , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len) , search = String(searchString); return $endsWith ? $endsWith.call(that, search, end) : that.slice(end - search.length, end) === search; } }); /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { // helper for String#{startsWith, endsWith, includes} var isRegExp = __webpack_require__(96) , defined = __webpack_require__(19); module.exports = function(that, searchString, NAME){ if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!"); return String(defined(that)); }; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { // 7.2.8 IsRegExp(argument) var isObject = __webpack_require__(13) , cof = __webpack_require__(15) , MATCH = __webpack_require__(29)('match'); module.exports = function(it){ var isRegExp; return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); }; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { var MATCH = __webpack_require__(29)('match'); module.exports = function(KEY){ var re = /./; try { '/./'[KEY](re); } catch(e){ try { re[MATCH] = false; return !'/./'[KEY](re); } catch(f){ /* empty */ } } return true; }; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.7 String.prototype.includes(searchString, position = 0) 'use strict'; var $export = __webpack_require__(3) , context = __webpack_require__(95) , INCLUDES = 'includes'; $export($export.P + $export.F * __webpack_require__(97)(INCLUDES), 'String', { includes: function includes(searchString /*, position = 0 */){ return !!~context(this, searchString, INCLUDES) .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); } }); /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3); $export($export.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: __webpack_require__(100) }); /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var toInteger = __webpack_require__(22) , defined = __webpack_require__(19); module.exports = function repeat(count){ var str = String(defined(this)) , res = '' , n = toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) 'use strict'; var $export = __webpack_require__(3) , toLength = __webpack_require__(24) , context = __webpack_require__(95) , STARTS_WITH = 'startsWith' , $startsWith = ''[STARTS_WITH]; $export($export.P + $export.F * __webpack_require__(97)(STARTS_WITH), 'String', { startsWith: function startsWith(searchString /*, position = 0 */){ var that = context(this, searchString, STARTS_WITH) , $$ = arguments , index = toLength(Math.min($$.length > 1 ? $$[1] : undefined, that.length)) , search = String(searchString); return $startsWith ? $startsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $at = __webpack_require__(93)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(103)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(39) , $export = __webpack_require__(3) , redefine = __webpack_require__(33) , hide = __webpack_require__(34) , has = __webpack_require__(14) , Iterators = __webpack_require__(104) , $iterCreate = __webpack_require__(105) , setToStringTag = __webpack_require__(35) , getProto = __webpack_require__(2).getProto , ITERATOR = __webpack_require__(29)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , methods, key; // Fix native if($native){ var IteratorPrototype = getProto($default.call(new Base)); // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // FF fix if(!LIBRARY && has(proto, FF_ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: !DEF_VALUES ? $default : getMethod('entries') }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }, /* 104 */ /***/ function(module, exports) { module.exports = {}; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , descriptor = __webpack_require__(10) , setToStringTag = __webpack_require__(35) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(34)(IteratorPrototype, __webpack_require__(29)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = $.create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ctx = __webpack_require__(6) , $export = __webpack_require__(3) , toObject = __webpack_require__(18) , call = __webpack_require__(107) , isArrayIter = __webpack_require__(108) , toLength = __webpack_require__(24) , getIterFn = __webpack_require__(109); $export($export.S + $export.F * !__webpack_require__(111)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , $$ = arguments , $$len = $$.length , mapfn = $$len > 1 ? $$[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, $$len > 2 ? $$[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ result[index] = mapping ? call(iterator, mapfn, [step.value, index], true) : step.value; } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ result[index] = mapping ? mapfn(O[index], index) : O[index]; } } result.length = index; return result; } }); /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(17); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(104) , ITERATOR = __webpack_require__(29)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(110) , ITERATOR = __webpack_require__(29)('iterator') , Iterators = __webpack_require__(104); module.exports = __webpack_require__(5).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(15) , TAG = __webpack_require__(29)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = (O = Object(it))[TAG]) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(29)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ safe = true; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3); // WebKit Array.of isn't generic $export($export.S + $export.F * __webpack_require__(9)(function(){ function F(){} return !(Array.of.call(F) instanceof F); }), 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , $$ = arguments , $$len = $$.length , result = new (typeof this == 'function' ? this : Array)($$len); while($$len > index)result[index] = $$[index++]; result.length = $$len; return result; } }); /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var addToUnscopables = __webpack_require__(114) , step = __webpack_require__(115) , Iterators = __webpack_require__(104) , toIObject = __webpack_require__(20); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(103)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }, /* 114 */ /***/ function(module, exports) { module.exports = function(){ /* empty */ }; /***/ }, /* 115 */ /***/ function(module, exports) { module.exports = function(done, value){ return {value: value, done: !!done}; }; /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(117)('Array'); /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var core = __webpack_require__(5) , $ = __webpack_require__(2) , DESCRIPTORS = __webpack_require__(8) , SPECIES = __webpack_require__(29)('species'); module.exports = function(KEY){ var C = core[KEY]; if(DESCRIPTORS && C && !C[SPECIES])$.setDesc(C, SPECIES, { configurable: true, get: function(){ return this; } }); }; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) var $export = __webpack_require__(3); $export($export.P, 'Array', {copyWithin: __webpack_require__(119)}); __webpack_require__(114)('copyWithin'); /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) 'use strict'; var toObject = __webpack_require__(18) , toIndex = __webpack_require__(23) , toLength = __webpack_require__(24); module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){ var O = toObject(this) , len = toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , $$ = arguments , end = $$.length > 2 ? $$[2] : undefined , count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from += count - 1; to += count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) var $export = __webpack_require__(3); $export($export.P, 'Array', {fill: __webpack_require__(121)}); __webpack_require__(114)('fill'); /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) 'use strict'; var toObject = __webpack_require__(18) , toIndex = __webpack_require__(23) , toLength = __webpack_require__(24); module.exports = [].fill || function fill(value /*, start = 0, end = @length */){ var O = toObject(this) , length = toLength(O.length) , $$ = arguments , $$len = $$.length , index = toIndex($$len > 1 ? $$[1] : undefined, length) , end = $$len > 2 ? $$[2] : undefined , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; }; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var $export = __webpack_require__(3) , $find = __webpack_require__(26)(5) , KEY = 'find' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { find: function find(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(114)(KEY); /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var $export = __webpack_require__(3) , $find = __webpack_require__(26)(6) , KEY = 'findIndex' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { findIndex: function findIndex(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(114)(KEY); /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , LIBRARY = __webpack_require__(39) , global = __webpack_require__(4) , ctx = __webpack_require__(6) , classof = __webpack_require__(110) , $export = __webpack_require__(3) , isObject = __webpack_require__(13) , anObject = __webpack_require__(17) , aFunction = __webpack_require__(7) , strictNew = __webpack_require__(125) , forOf = __webpack_require__(126) , setProto = __webpack_require__(45).set , same = __webpack_require__(43) , SPECIES = __webpack_require__(29)('species') , speciesConstructor = __webpack_require__(127) , asap = __webpack_require__(128) , PROMISE = 'Promise' , process = global.process , isNode = classof(process) == 'process' , P = global[PROMISE] , Wrapper; var testResolve = function(sub){ var test = new P(function(){}); if(sub)test.constructor = Object; return P.resolve(test) === test; }; var USE_NATIVE = function(){ var works = false; function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } try { works = P && P.resolve && testResolve(); setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); // actual Firefox has broken subclass support, test that if(!(P2.resolve(5).then(function(){}) instanceof P2)){ works = false; } // actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162 if(works && __webpack_require__(8)){ var thenableThenGotten = false; P.resolve($.setDesc({}, 'then', { get: function(){ thenableThenGotten = true; } })); works = thenableThenGotten; } } catch(e){ works = false; } return works; }(); // helpers var sameConstructor = function(a, b){ // library wrapper special case if(LIBRARY && a === P && b === Wrapper)return true; return same(a, b); }; var getConstructor = function(C){ var S = anObject(C)[SPECIES]; return S != undefined ? S : C; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var PromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve), this.reject = aFunction(reject) }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(record, isReject){ if(record.n)return; record.n = true; var chain = record.c; asap(function(){ var value = record.v , ok = record.s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , result, then; try { if(handler){ if(!ok)record.h = true; result = handler === true ? value : handler(value); if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach chain.length = 0; record.n = false; if(isReject)setTimeout(function(){ var promise = record.p , handler, console; if(isUnhandled(promise)){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } } record.a = undefined; }, 1); }); }; var isUnhandled = function(promise){ var record = promise._d , chain = record.a || record.c , i = 0 , reaction; if(record.h)return false; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var $reject = function(value){ var record = this; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; record.a = record.c.slice(); notify(record, true); }; var $resolve = function(value){ var record = this , then; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(record.p === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ asap(function(){ var wrapper = {r: record, d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { record.v = value; record.s = 1; notify(record, false); } } catch(e){ $reject.call({r: record, d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ aFunction(executor); var record = this._d = { p: strictNew(this, P, PROMISE), // <- promise c: [], // <- awaiting reactions a: undefined, // <- checked in isUnhandled reactions s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false, // <- handled rejection n: false // <- notify }; try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; __webpack_require__(130)(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = new PromiseCapability(speciesConstructor(this, P)) , promise = reaction.promise , record = this._d; reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; record.c.push(reaction); if(record.a)record.a.push(reaction); if(record.s)notify(record, false); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: P}); __webpack_require__(35)(P, PROMISE); __webpack_require__(117)(PROMISE); Wrapper = __webpack_require__(5)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = new PromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (!USE_NATIVE || testResolve(true)), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof P && sameConstructor(x.constructor, this))return x; var capability = new PromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(111)(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , capability = new PromiseCapability(C) , resolve = capability.resolve , reject = capability.reject , values = []; var abrupt = perform(function(){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ var alreadyCalled = false; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; results[index] = value; --remaining || resolve(results); }, reject); }); else resolve(results); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this) , capability = new PromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } }); /***/ }, /* 125 */ /***/ function(module, exports) { module.exports = function(it, Constructor, name){ if(!(it instanceof Constructor))throw TypeError(name + ": use the 'new' operator!"); return it; }; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(6) , call = __webpack_require__(107) , isArrayIter = __webpack_require__(108) , anObject = __webpack_require__(17) , toLength = __webpack_require__(24) , getIterFn = __webpack_require__(109); module.exports = function(iterable, entries, fn, that){ var iterFn = getIterFn(iterable) , f = ctx(fn, that, entries ? 2 : 1) , index = 0 , length, step, iterator; if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ call(iterator, f, step.value, entries); } }; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(17) , aFunction = __webpack_require__(7) , SPECIES = __webpack_require__(29)('species'); module.exports = function(O, D){ var C = anObject(O).constructor, S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , macrotask = __webpack_require__(129).set , Observer = global.MutationObserver || global.WebKitMutationObserver , process = global.process , Promise = global.Promise , isNode = __webpack_require__(15)(process) == 'process' , head, last, notify; var flush = function(){ var parent, domain, fn; if(isNode && (parent = process.domain)){ process.domain = null; parent.exit(); } while(head){ domain = head.domain; fn = head.fn; if(domain)domain.enter(); fn(); // <- currently we use it only for Promise - try / catch not required if(domain)domain.exit(); head = head.next; } last = undefined; if(parent)parent.enter(); }; // Node.js if(isNode){ notify = function(){ process.nextTick(flush); }; // browsers with MutationObserver } else if(Observer){ var toggle = 1 , node = document.createTextNode(''); new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new notify = function(){ node.data = toggle = -toggle; }; // environments with maybe non-completely correct, but existent Promise } else if(Promise && Promise.resolve){ notify = function(){ Promise.resolve().then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function(){ // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } module.exports = function asap(fn){ var task = {fn: fn, next: undefined, domain: isNode && process.domain}; if(last)last.next = task; if(!head){ head = task; notify(); } last = task; }; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(6) , invoke = __webpack_require__(16) , html = __webpack_require__(11) , cel = __webpack_require__(12) , global = __webpack_require__(4) , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; var run = function(){ var id = +this; if(queue.hasOwnProperty(id)){ var fn = queue[id]; delete queue[id]; fn(); } }; var listner = function(event){ run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!setTask || !clearTask){ setTask = function setImmediate(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id){ delete queue[id]; }; // Node.js 0.8- if(__webpack_require__(15)(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if(MessageChannel){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listner; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ defer = function(id){ global.postMessage(id + '', '*'); }; global.addEventListener('message', listner, false); // IE8- } else if(ONREADYSTATECHANGE in cel('script')){ defer = function(id){ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { var redefine = __webpack_require__(33); module.exports = function(target, src){ for(var key in src)redefine(target, key, src[key]); return target; }; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(132); // 23.1 Map Objects __webpack_require__(133)('Map', function(get){ return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , hide = __webpack_require__(34) , redefineAll = __webpack_require__(130) , ctx = __webpack_require__(6) , strictNew = __webpack_require__(125) , defined = __webpack_require__(19) , forOf = __webpack_require__(126) , $iterDefine = __webpack_require__(103) , step = __webpack_require__(115) , ID = __webpack_require__(25)('id') , $has = __webpack_require__(14) , isObject = __webpack_require__(13) , setSpecies = __webpack_require__(117) , DESCRIPTORS = __webpack_require__(8) , isExtensible = Object.isExtensible || isObject , SIZE = DESCRIPTORS ? '_s' : 'size' , id = 0; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!$has(it, ID)){ // can't set id to frozen object if(!isExtensible(it))return 'F'; // 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]; }; var getEntry = function(that, key){ // fast case var index = fastKey(key), entry; if(index !== 'F')return that._i[index]; // frozen object case for(entry = that._f; entry; entry = entry.n){ if(entry.k == key)return entry; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ strictNew(that, C, NAME); that._i = $.create(null); // index that._f = undefined; // first entry that._l = undefined; // last entry that[SIZE] = 0; // size if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that._f = that._l = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that._i[entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that._f == entry)that._f = next; if(that._l == entry)that._l = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) , entry; while(entry = entry ? entry.n : this._f){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if(DESCRIPTORS)$.setDesc(C.prototype, 'size', { get: function(){ return defined(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that._l = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that._l, // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that._f)that._f = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index !== 'F')that._i[index] = entry; } return that; }, getEntry: getEntry, setStrong: function(C, NAME, IS_MAP){ // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 $iterDefine(C, NAME, function(iterated, kind){ this._t = iterated; // target this._k = kind; // kind this._l = undefined; // previous }, function(){ var that = this , kind = that._k , entry = that._l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ // or finish the iteration that._t = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(NAME); } }; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , global = __webpack_require__(4) , $export = __webpack_require__(3) , fails = __webpack_require__(9) , hide = __webpack_require__(34) , redefineAll = __webpack_require__(130) , forOf = __webpack_require__(126) , strictNew = __webpack_require__(125) , isObject = __webpack_require__(13) , setToStringTag = __webpack_require__(35) , DESCRIPTORS = __webpack_require__(8); module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ var Base = global[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; if(!DESCRIPTORS || typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ new C().entries().next(); }))){ // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); redefineAll(C.prototype, methods); } else { C = wrapper(function(target, iterable){ strictNew(target, C, NAME); target._c = new Base; if(iterable != undefined)forOf(iterable, IS_MAP, target[ADDER], target); }); $.each.call('add,clear,delete,forEach,get,has,set,keys,values,entries'.split(','),function(KEY){ var IS_ADDER = KEY == 'add' || KEY == 'set'; if(KEY in proto && !(IS_WEAK && KEY == 'clear'))hide(C.prototype, KEY, function(a, b){ if(!IS_ADDER && IS_WEAK && !isObject(a))return KEY == 'get' ? undefined : false; var result = this._c[KEY](a === 0 ? 0 : a, b); return IS_ADDER ? this : result; }); }); if('size' in proto)$.setDesc(C.prototype, 'size', { get: function(){ return this._c.size; } }); } setToStringTag(C, NAME); O[NAME] = C; $export($export.G + $export.W + $export.F, O); if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); return C; }; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(132); // 23.2 Set Objects __webpack_require__(133)('Set', function(get){ return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , redefine = __webpack_require__(33) , weak = __webpack_require__(136) , isObject = __webpack_require__(13) , has = __webpack_require__(14) , frozenStore = weak.frozenStore , WEAK = weak.WEAK , isExtensible = Object.isExtensible || isObject , tmp = {}; // 23.3 WeakMap Objects var $WeakMap = __webpack_require__(133)('WeakMap', function(get){ return function WeakMap(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ if(!isExtensible(key))return frozenStore(this).get(key); if(has(key, WEAK))return key[WEAK][this._i]; } }, // 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(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ $.each.call(['delete', 'has', 'get', 'set'], function(key){ var proto = $WeakMap.prototype , method = proto[key]; redefine(proto, key, function(a, b){ // store frozen objects on leaky map if(isObject(a) && !isExtensible(a)){ var result = frozenStore(this)[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }); }); } /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var hide = __webpack_require__(34) , redefineAll = __webpack_require__(130) , anObject = __webpack_require__(17) , isObject = __webpack_require__(13) , strictNew = __webpack_require__(125) , forOf = __webpack_require__(126) , createArrayMethod = __webpack_require__(26) , $has = __webpack_require__(14) , WEAK = __webpack_require__(25)('weak') , isExtensible = Object.isExtensible || isObject , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , id = 0; // fallback for frozen keys var frozenStore = function(that){ return that._l || (that._l = new FrozenStore); }; var FrozenStore = function(){ this.a = []; }; var findFrozen = function(store, key){ return arrayFind(store.a, function(it){ return it[0] === key; }); }; FrozenStore.prototype = { 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.a.push([key, value]); }, 'delete': function(key){ var index = arrayFindIndex(this.a, function(it){ return it[0] === key; }); if(~index)this.a.splice(index, 1); return !!~index; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ strictNew(that, C, NAME); that._i = id++; // collection id that._l = undefined; // leak store for frozen objects if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; if(!isExtensible(key))return frozenStore(this)['delete'](key); return $has(key, WEAK) && $has(key[WEAK], this._i) && delete key[WEAK][this._i]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; if(!isExtensible(key))return frozenStore(this).has(key); return $has(key, WEAK) && $has(key[WEAK], this._i); } }); return C; }, def: function(that, key, value){ if(!isExtensible(anObject(key))){ frozenStore(that).set(key, value); } else { $has(key, WEAK) || hide(key, WEAK, {}); key[WEAK][that._i] = value; } return that; }, frozenStore: frozenStore, WEAK: WEAK }; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var weak = __webpack_require__(136); // 23.4 WeakSet Objects __webpack_require__(133)('WeakSet', function(get){ return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) var $export = __webpack_require__(3) , _apply = Function.apply; $export($export.S, 'Reflect', { apply: function apply(target, thisArgument, argumentsList){ return _apply.call(target, thisArgument, argumentsList); } }); /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) var $ = __webpack_require__(2) , $export = __webpack_require__(3) , aFunction = __webpack_require__(7) , anObject = __webpack_require__(17) , isObject = __webpack_require__(13) , bind = Function.bind || __webpack_require__(5).Function.prototype.bind; // MS Edge supports only 2 arguments // FF Nightly sets third argument as `new.target`, but does not create `this` from it $export($export.S + $export.F * __webpack_require__(9)(function(){ function F(){} return !(Reflect.construct(function(){}, [], F) instanceof F); }), 'Reflect', { construct: function construct(Target, args /*, newTarget*/){ aFunction(Target); var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); if(Target == newTarget){ // w/o altered newTarget, optimization for 0-4 arguments if(args != undefined)switch(anObject(args).length){ case 0: return new Target; case 1: return new Target(args[0]); case 2: return new Target(args[0], args[1]); case 3: return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); } // w/o altered newTarget, lot of arguments case var $args = [null]; $args.push.apply($args, args); return new (bind.apply(Target, $args)); } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype , instance = $.create(isObject(proto) ? proto : Object.prototype) , result = Function.apply.call(Target, instance, args); return isObject(result) ? result : instance; } }); /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) var $ = __webpack_require__(2) , $export = __webpack_require__(3) , anObject = __webpack_require__(17); // MS Edge has broken Reflect.defineProperty - throwing instead of returning false $export($export.S + $export.F * __webpack_require__(9)(function(){ Reflect.defineProperty($.setDesc({}, 1, {value: 1}), 1, {value: 2}); }), 'Reflect', { defineProperty: function defineProperty(target, propertyKey, attributes){ anObject(target); try { $.setDesc(target, propertyKey, attributes); return true; } catch(e){ return false; } } }); /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { // 26.1.4 Reflect.deleteProperty(target, propertyKey) var $export = __webpack_require__(3) , getDesc = __webpack_require__(2).getDesc , anObject = __webpack_require__(17); $export($export.S, 'Reflect', { deleteProperty: function deleteProperty(target, propertyKey){ var desc = getDesc(anObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; } }); /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 26.1.5 Reflect.enumerate(target) var $export = __webpack_require__(3) , anObject = __webpack_require__(17); var Enumerate = function(iterated){ this._t = anObject(iterated); // target this._i = 0; // next index var keys = this._k = [] // keys , key; for(key in iterated)keys.push(key); }; __webpack_require__(105)(Enumerate, 'Object', function(){ var that = this , keys = that._k , key; do { if(that._i >= keys.length)return {value: undefined, done: true}; } while(!((key = keys[that._i++]) in that._t)); return {value: key, done: false}; }); $export($export.S, 'Reflect', { enumerate: function enumerate(target){ return new Enumerate(target); } }); /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { // 26.1.6 Reflect.get(target, propertyKey [, receiver]) var $ = __webpack_require__(2) , has = __webpack_require__(14) , $export = __webpack_require__(3) , isObject = __webpack_require__(13) , anObject = __webpack_require__(17); function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc, proto; if(anObject(target) === receiver)return target[propertyKey]; if(desc = $.getDesc(target, propertyKey))return has(desc, 'value') ? desc.value : desc.get !== undefined ? desc.get.call(receiver) : undefined; if(isObject(proto = $.getProto(target)))return get(proto, propertyKey, receiver); } $export($export.S, 'Reflect', {get: get}); /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) var $ = __webpack_require__(2) , $export = __webpack_require__(3) , anObject = __webpack_require__(17); $export($export.S, 'Reflect', { getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return $.getDesc(anObject(target), propertyKey); } }); /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { // 26.1.8 Reflect.getPrototypeOf(target) var $export = __webpack_require__(3) , getProto = __webpack_require__(2).getProto , anObject = __webpack_require__(17); $export($export.S, 'Reflect', { getPrototypeOf: function getPrototypeOf(target){ return getProto(anObject(target)); } }); /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { // 26.1.9 Reflect.has(target, propertyKey) var $export = __webpack_require__(3); $export($export.S, 'Reflect', { has: function has(target, propertyKey){ return propertyKey in target; } }); /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { // 26.1.10 Reflect.isExtensible(target) var $export = __webpack_require__(3) , anObject = __webpack_require__(17) , $isExtensible = Object.isExtensible; $export($export.S, 'Reflect', { isExtensible: function isExtensible(target){ anObject(target); return $isExtensible ? $isExtensible(target) : true; } }); /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { // 26.1.11 Reflect.ownKeys(target) var $export = __webpack_require__(3); $export($export.S, 'Reflect', {ownKeys: __webpack_require__(149)}); /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { // all object keys, includes non-enumerable and symbols var $ = __webpack_require__(2) , anObject = __webpack_require__(17) , Reflect = __webpack_require__(4).Reflect; module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){ var keys = $.getNames(anObject(it)) , getSymbols = $.getSymbols; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { // 26.1.12 Reflect.preventExtensions(target) var $export = __webpack_require__(3) , anObject = __webpack_require__(17) , $preventExtensions = Object.preventExtensions; $export($export.S, 'Reflect', { preventExtensions: function preventExtensions(target){ anObject(target); try { if($preventExtensions)$preventExtensions(target); return true; } catch(e){ return false; } } }); /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) var $ = __webpack_require__(2) , has = __webpack_require__(14) , $export = __webpack_require__(3) , createDesc = __webpack_require__(10) , anObject = __webpack_require__(17) , isObject = __webpack_require__(13); function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = $.getDesc(anObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = $.getProto(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = createDesc(0); } if(has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = $.getDesc(receiver, propertyKey) || createDesc(0); existingDescriptor.value = V; $.setDesc(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } $export($export.S, 'Reflect', {set: set}); /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { // 26.1.14 Reflect.setPrototypeOf(target, proto) var $export = __webpack_require__(3) , setProto = __webpack_require__(45); if(setProto)$export($export.S, 'Reflect', { setPrototypeOf: function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } } }); /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3) , $includes = __webpack_require__(31)(true); $export($export.P, 'Array', { // https://github.com/domenic/Array.prototype.includes includes: function includes(el /*, fromIndex = 0 */){ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(114)('includes'); /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/mathiasbynens/String.prototype.at var $export = __webpack_require__(3) , $at = __webpack_require__(93)(true); $export($export.P, 'String', { at: function at(pos){ return $at(this, pos); } }); /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3) , $pad = __webpack_require__(156); $export($export.P, 'String', { padLeft: function padLeft(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); } }); /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/ljharb/proposal-string-pad-left-right var toLength = __webpack_require__(24) , repeat = __webpack_require__(100) , defined = __webpack_require__(19); module.exports = function(that, maxLength, fillString, left){ var S = String(defined(that)) , stringLength = S.length , fillStr = fillString === undefined ? ' ' : String(fillString) , intMaxLength = toLength(maxLength); if(intMaxLength <= stringLength)return S; if(fillStr == '')fillStr = ' '; var fillLen = intMaxLength - stringLength , stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen); return left ? stringFiller + S : S + stringFiller; }; /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3) , $pad = __webpack_require__(156); $export($export.P, 'String', { padRight: function padRight(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); } }); /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim __webpack_require__(91)('trimLeft', function($trim){ return function trimLeft(){ return $trim(this, 1); }; }); /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim __webpack_require__(91)('trimRight', function($trim){ return function trimRight(){ return $trim(this, 2); }; }); /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/benjamingr/RexExp.escape var $export = __webpack_require__(3) , $re = __webpack_require__(161)(/[\\^$*+?.()|[\]{}]/g, '\\$&'); $export($export.S, 'RegExp', {escape: function escape(it){ return $re(it); }}); /***/ }, /* 161 */ /***/ function(module, exports) { module.exports = function(regExp, replace){ var replacer = replace === Object(replace) ? function(part){ return replace[part]; } : replace; return function(it){ return String(it).replace(regExp, replacer); }; }; /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/WebReflection/9353781 var $ = __webpack_require__(2) , $export = __webpack_require__(3) , ownKeys = __webpack_require__(149) , toIObject = __webpack_require__(20) , createDesc = __webpack_require__(10); $export($export.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = toIObject(object) , setDesc = $.setDesc , getDesc = $.getDesc , keys = ownKeys(O) , result = {} , i = 0 , key, D; while(keys.length > i){ D = getDesc(O, key = keys[i++]); if(key in result)setDesc(result, key, createDesc(0, D)); else result[key] = D; } return result; } }); /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { // http://goo.gl/XkBrjD var $export = __webpack_require__(3) , $values = __webpack_require__(164)(false); $export($export.S, 'Object', { values: function values(it){ return $values(it); } }); /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , toIObject = __webpack_require__(20) , isEnum = $.isEnum; module.exports = function(isEntries){ return function(it){ var O = toIObject(it) , keys = $.getKeys(O) , length = keys.length , i = 0 , result = [] , key; while(length > i)if(isEnum.call(O, key = keys[i++])){ result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { // http://goo.gl/XkBrjD var $export = __webpack_require__(3) , $entries = __webpack_require__(164)(true); $export($export.S, 'Object', { entries: function entries(it){ return $entries(it); } }); /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(3); $export($export.P, 'Map', {toJSON: __webpack_require__(167)('Map')}); /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var forOf = __webpack_require__(126) , classof = __webpack_require__(110); module.exports = function(NAME){ return function toJSON(){ if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); var arr = []; forOf(this, false, arr.push, arr); return arr; }; }; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(3); $export($export.P, 'Set', {toJSON: __webpack_require__(167)('Set')}); /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , $task = __webpack_require__(129); $export($export.G + $export.B, { setImmediate: $task.set, clearImmediate: $task.clear }); /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(113); var Iterators = __webpack_require__(104); Iterators.NodeList = Iterators.HTMLCollection = Iterators.Array; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { // ie9- setTimeout & setInterval additional parameters fix var global = __webpack_require__(4) , $export = __webpack_require__(3) , invoke = __webpack_require__(16) , partial = __webpack_require__(172) , navigator = global.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check var wrap = function(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), typeof fn == 'function' ? fn : Function(fn) ), time); } : set; }; $export($export.G + $export.B + $export.F * MSIE, { setTimeout: wrap(global.setTimeout), setInterval: wrap(global.setInterval) }); /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var path = __webpack_require__(173) , invoke = __webpack_require__(16) , aFunction = __webpack_require__(7); module.exports = function(/* ...pargs */){ var fn = aFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , $$ = arguments , $$len = $$.length , j = 0, k = 0, args; if(!holder && !$$len)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = $$[k++]; while($$len > k)args.push($$[k++]); return invoke(fn, args, that); }; }; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(5); /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $ = __webpack_require__(2) , ctx = __webpack_require__(6) , $export = __webpack_require__(3) , createDesc = __webpack_require__(10) , assign = __webpack_require__(41) , keyOf = __webpack_require__(36) , aFunction = __webpack_require__(7) , forOf = __webpack_require__(126) , isIterable = __webpack_require__(175) , $iterCreate = __webpack_require__(105) , step = __webpack_require__(115) , isObject = __webpack_require__(13) , toIObject = __webpack_require__(20) , DESCRIPTORS = __webpack_require__(8) , has = __webpack_require__(14) , getKeys = $.getKeys; // 0 -> Dict.forEach // 1 -> Dict.map // 2 -> Dict.filter // 3 -> Dict.some // 4 -> Dict.every // 5 -> Dict.find // 6 -> Dict.findKey // 7 -> Dict.mapPairs var createDictMethod = function(TYPE){ var IS_MAP = TYPE == 1 , IS_EVERY = TYPE == 4; return function(object, callbackfn, that /* = undefined */){ var f = ctx(callbackfn, that, 3) , O = toIObject(object) , result = IS_MAP || TYPE == 7 || TYPE == 2 ? new (typeof this == 'function' ? this : Dict) : undefined , key, val, res; for(key in O)if(has(O, key)){ val = O[key]; res = f(val, key, object); if(TYPE){ if(IS_MAP)result[key] = res; // map else if(res)switch(TYPE){ case 2: result[key] = val; break; // filter case 3: return true; // some case 5: return val; // find case 6: return key; // findKey case 7: result[res[0]] = res[1]; // mapPairs } else if(IS_EVERY)return false; // every } } return TYPE == 3 || IS_EVERY ? IS_EVERY : result; }; }; var findKey = createDictMethod(6); var createDictIter = function(kind){ return function(it){ return new DictIterator(it, kind); }; }; var DictIterator = function(iterated, kind){ this._t = toIObject(iterated); // target this._a = getKeys(iterated); // keys this._i = 0; // next index this._k = kind; // kind }; $iterCreate(DictIterator, 'Dict', function(){ var that = this , O = that._t , keys = that._a , kind = that._k , key; do { if(that._i >= keys.length){ that._t = undefined; return step(1); } } while(!has(O, key = keys[that._i++])); if(kind == 'keys' )return step(0, key); if(kind == 'values')return step(0, O[key]); return step(0, [key, O[key]]); }); function Dict(iterable){ var dict = $.create(null); if(iterable != undefined){ if(isIterable(iterable)){ forOf(iterable, true, function(key, value){ dict[key] = value; }); } else assign(dict, iterable); } return dict; } Dict.prototype = null; function reduce(object, mapfn, init){ aFunction(mapfn); var O = toIObject(object) , keys = getKeys(O) , length = keys.length , i = 0 , memo, key; if(arguments.length < 3){ if(!length)throw TypeError('Reduce of empty object with no initial value'); memo = O[keys[i++]]; } else memo = Object(init); while(length > i)if(has(O, key = keys[i++])){ memo = mapfn(memo, O[key], key, object); } return memo; } function includes(object, el){ return (el == el ? keyOf(object, el) : findKey(object, function(it){ return it != it; })) !== undefined; } function get(object, key){ if(has(object, key))return object[key]; } function set(object, key, value){ if(DESCRIPTORS && key in Object)$.setDesc(object, key, createDesc(0, value)); else object[key] = value; return object; } function isDict(it){ return isObject(it) && $.getProto(it) === Dict.prototype; } $export($export.G + $export.F, {Dict: Dict}); $export($export.S, 'Dict', { keys: createDictIter('keys'), values: createDictIter('values'), entries: createDictIter('entries'), forEach: createDictMethod(0), map: createDictMethod(1), filter: createDictMethod(2), some: createDictMethod(3), every: createDictMethod(4), find: createDictMethod(5), findKey: findKey, mapPairs: createDictMethod(7), reduce: reduce, keyOf: keyOf, includes: includes, has: has, get: get, set: set, isDict: isDict }); /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(110) , ITERATOR = __webpack_require__(29)('iterator') , Iterators = __webpack_require__(104); module.exports = __webpack_require__(5).isIterable = function(it){ var O = Object(it); return O[ITERATOR] !== undefined || '@@iterator' in O || Iterators.hasOwnProperty(classof(O)); }; /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(17) , get = __webpack_require__(109); module.exports = __webpack_require__(5).getIterator = function(it){ var iterFn = get(it); if(typeof iterFn != 'function')throw TypeError(it + ' is not iterable!'); return anObject(iterFn.call(it)); }; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(4) , core = __webpack_require__(5) , $export = __webpack_require__(3) , partial = __webpack_require__(172); // https://esdiscuss.org/topic/promise-returning-delay-function $export($export.G + $export.F, { delay: function delay(time){ return new (core.Promise || global.Promise)(function(resolve){ setTimeout(partial.call(resolve, true), time); }); } }); /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { var path = __webpack_require__(173) , $export = __webpack_require__(3); // Placeholder __webpack_require__(5)._ = path._ = path._ || {}; $export($export.P + $export.F, 'Function', {part: __webpack_require__(172)}); /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3); $export($export.S + $export.F, 'Object', {isObject: __webpack_require__(13)}); /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3); $export($export.S + $export.F, 'Object', {classof: __webpack_require__(110)}); /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , define = __webpack_require__(182); $export($export.S + $export.F, 'Object', {define: define}); /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , ownKeys = __webpack_require__(149) , toIObject = __webpack_require__(20); module.exports = function define(target, mixin){ var keys = ownKeys(toIObject(mixin)) , length = keys.length , i = 0, key; while(length > i)$.setDesc(target, key = keys[i++], $.getDesc(mixin, key)); return target; }; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(3) , define = __webpack_require__(182) , create = __webpack_require__(2).create; $export($export.S + $export.F, 'Object', { make: function(proto, mixin){ return define(create(proto), mixin); } }); /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(103)(Number, 'Number', function(iterated){ this._l = +iterated; this._i = 0; }, function(){ var i = this._i++ , done = !(i < this._l); return {done: done, value: done ? undefined : i}; }); /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3); var $re = __webpack_require__(161)(/[&<>"']/g, { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;' }); $export($export.P + $export.F, 'String', {escapeHTML: function escapeHTML(){ return $re(this); }}); /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(3); var $re = __webpack_require__(161)(/&(?:amp|lt|gt|quot|apos);/g, { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&apos;': "'" }); $export($export.P + $export.F, 'String', {unescapeHTML: function unescapeHTML(){ return $re(this); }}); /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { var $ = __webpack_require__(2) , global = __webpack_require__(4) , $export = __webpack_require__(3) , log = {} , enabled = true; // Methods from https://github.com/DeveloperToolsWG/console-object/blob/master/api.md $.each.call(( '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' ).split(','), function(key){ log[key] = function(){ var $console = global.console; if(enabled && $console && $console[key]){ return Function.apply.call($console[key], $console, arguments); } }; }); $export($export.G + $export.F, {log: __webpack_require__(41)(log.log, log, { enable: function(){ enabled = true; }, disable: function(){ enabled = false; } })}); /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { // JavaScript 1.6 / Strawman array statics shim var $ = __webpack_require__(2) , $export = __webpack_require__(3) , $ctx = __webpack_require__(6) , $Array = __webpack_require__(5).Array || Array , statics = {}; var setStatics = function(keys, length){ $.each.call(keys.split(','), function(key){ if(length == undefined && key in $Array)statics[key] = $Array[key]; else if(key in [])statics[key] = $ctx(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'); $export($export.S, 'Array', statics); /***/ } /******/ ]); // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = __e; // RequireJS export else if(typeof define == 'function' && define.amd)define(function(){return __e}); // Export to global object else __g.core = __e; }(1, 1);
ajax/libs/amplitudejs/3.2.3-0/amplitude.js
seogi1004/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define("Amplitude", [], factory); else if(typeof exports === 'object') exports["Amplitude"] = factory(); else root["Amplitude"] = 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] = { /******/ 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 = 8); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* |------------------------------------------------------------------------------- | Module Variables |------------------------------------------------------------------------------- | These variables make Amplitude run. The config is the most important | containing active settings and parameters. */ /*-------------------------------------------------------------------------- The config JSON is the global settings for ALL of Amplitude functions. This is global and contains all of the user preferences. The default settings are set, and the user overwrites them when they initialize Amplitude. --------------------------------------------------------------------------*/ var config = { version: '3.2.3', /* The audio element we will be using to handle all of the audio. This is the javascript version of the HTML5 audio element. */ active_song: new Audio(), /* JSON object that contains the active metadata for the song. */ active_metadata: {}, /* String to hold the active album name. Used to check and see if the album changed and run the album changed callback. */ active_album: '', /* Contains the index of the actively playing song. */ active_index: 0, /* Contains the key to the active playlist index. */ active_playlist: '', /* Set to true to autoplay the song */ autoplay: false, /* Sets the initial playback speed of the song. The values for this can be 1.0, 1.5, 2.0 */ playback_speed: 1.0, /* The user can pass a JSON object with a key => value store of callbacks to be run at certain events. */ callbacks: {}, /* Object containing all of the songs the user has passed to Amplitude to use. */ songs: [], /* Object containing all of the playlists the user created. */ playlists: {}, /* Object that will contain shuffled playlists. */ shuffled_playlists: {}, /* Object that contains whether the current playlist is in shuffle mode or not. */ shuffled_statuses: {}, /* Object that contains the active index in a shuffled playlist. */ shuffled_active_indexes: {}, /* When repeat is on, when the song ends the song will replay itself. */ repeat: false, /* When shuffled, this gets populated with the songs the user provided in a random order. */ shuffle_list: {}, /* When shuffled is turned on this gets set to true so when traversing through songs Amplitude knows whether or not to use the songs object or the shuffle_list. */ shuffle_on: false, /* When shuffled, this index is used to let Amplitude know where it's at when traversing. */ shuffle_active_index: 0, /* The user can set default album art to be displayed if the song they set doesn't contain album art. */ default_album_art: '', /* When set to true, Amplitude will print to the console any errors that it runs into providing helpful feedback to the user. */ debug: false, /* The user can set the initial volume to a number between 0 and 1 overridding a default of .5. */ volume: .5, /* This is set on mute so that when a user un-mutes Amplitude knows what to restore the volume to. */ pre_mute_volume: .5, /* This is an integer between 1 and 100 for how much the volume should increase when the user presses a volume up button. */ volume_increment: 5, /* This is an integer between 1 and 100 for how much the volume should decrease when the user presses a volume down button. */ volume_decrement: 5, /* When using SoundCloud, the user will have to provide their API Client ID */ soundcloud_client: '', /* The user can set this to true and Amplitude will use the album art for the song returned from the Soundcloud API */ soundcloud_use_art: false, /* Used on config to count how many songs are from soundcloud and compare it to how many are ready for when to move to the rest of the configuration. */ soundcloud_song_count: 0, /* Used on config to count how many songs are ready so when we get all of the data from the SoundCloud API that we need this should match the SoundCloud song count meaning we can move to the rest of the config. */ soundcloud_songs_ready: 0, /* Flag for if the user is moving the screen. */ is_touch_moving: false, /* How much of the song is buffered. */ buffered: 0, /* Array of bindings to certain key events. */ bindings: {}, /* Determines when a song ends, we should continue to the next song. */ continue_next: true }; module.exports = config; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _core = __webpack_require__(3); var _core2 = _interopRequireDefault(_core); var _visual = __webpack_require__(2); var _visual2 = _interopRequireDefault(_visual); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var config = __webpack_require__(0); /* |---------------------------------------------------------------------------------------------------- | HELPER FUNCTIONS |---------------------------------------------------------------------------------------------------- | For the sake of code clarity, these functions perform helper tasks | assisting the logical functions with what they need such as setting | the proper song index after an event has occured. | | METHODS | resetConfig() | writeDebugMessage( message ) | runCallback( callbackName ) | changeSong( songIndex ) */ var AmplitudeHelpers = function () { /*-------------------------------------------------------------------------- Resets the config to the default state. This is called on initialize to ensure the user's config is what matters. --------------------------------------------------------------------------*/ function resetConfig() { config.active_song = new Audio(); config.active_metadata = {}; config.active_album = ''; config.active_index = 0; config.active_playlist = ''; config.autoplay = false; config.playback_speed = 1.0; config.callbacks = {}; config.songs = []; config.playlists = {}; config.shuffled_playlists = {}; config.shuffled_statuses = {}; config.repeat = false; config.shuffle_list = {}; config.shuffle_on = false; config.shuffle_active_index = 0; config.default_album_art = ''; config.debug = false; config.handle_song_elements = true; config.volume = .5; config.pre_mute_volume = .5; config.volume_increment = 5; config.volume_decrement = 5; config.soundcloud_client = ''; config.soundcloud_use_art = false; config.soundcloud_song_count = 0; config.soundcloud_songs_ready = 0; config.continue_next = true; } /*-------------------------------------------------------------------------- Writes out debug message to the console if enabled. @param string message The string that gets printed to alert the user of a debugging error. --------------------------------------------------------------------------*/ function writeDebugMessage(message) { if (config.debug) { console.log(message); } } /*-------------------------------------------------------------------------- Runs a user defined callback method @param string callbackName The name of the callback we are going to run. --------------------------------------------------------------------------*/ function runCallback(callbackName) { /* Checks to see if a user defined a callback method for the callback we are running. */ if (config.callbacks[callbackName]) { /* Build the callback function */ var callbackFunction = config.callbacks[callbackName]; /* Write a debug message stating the callback we are running */ writeDebugMessage('Running Callback: ' + callbackName); /* Run the callback function. */ try { callbackFunction(); } catch (error) { // undocumented way to cancel events if (error.message == "CANCEL EVENT") throw error;else writeDebugMessage('Callback error: ' + error.message); } } } /*-------------------------------------------------------------------------- Changes the active song in the config. This happens in multiple scenarios: The user clicks a play button that has an index that is different than what is currently playing, the song ends and the next song begins, etc. @param int songIndex The song index we are changing to --------------------------------------------------------------------------*/ function changeSong(songIndex) { var song = config.songs[songIndex]; /* Stops the currently playing song so we can adjust what we need. */ _core2.default.stop(); /* FX-TODO: Stop Visualization */ /* Set all play buttons to pause while we change the song. */ _visual2.default.setPlayPauseButtonsToPause(); /* Since it is a new song, we reset the song sliders. These react to time updates and will eventually be updated but we force update them is if there is a song slider bound to a specific song, they won't update. */ _visual2.default.resetSongSliders(); /* Resets the progress bars */ _visual2.default.resetSongPlayedProgressBars(); /* Reset all the time place holders accordingly. */ _visual2.default.resetTimes(); /* Run a callback if an album is going to change. */ if (checkNewAlbum(song)) { runCallback('album_change'); } /* Set the new song information so we can use the active meta data later on. */ setNewSong(song, songIndex); /* Display the new visual metadata now that the config has been changed. This will show the new song. */ _visual2.default.displaySongMetadata(); /* Sets the active container. This is a class that designers can use on an element that contains the current song's controls to show it's highlighted. */ _visual2.default.setActiveContainer(); /* Sets the active song's duration */ _visual2.default.syncSongDuration(); /* Run song change callback. */ runCallback('song_change'); } /*-------------------------------------------------------------------------- Checks to see if the new song to be played is different than the song that is currently playing. To be true, the user would have selected play on a new song with a new index. To be false, the user would have clicked play/pause on the song that was playing. @param int songIndex The index of the new song to be played. --------------------------------------------------------------------------*/ function checkNewSong(songIndex) { if (songIndex != config.active_index) { return true; } else { return false; } } /*-------------------------------------------------------------------------- Checks to see if there is a new album @param string newAlbum Checks to see if the new song will have a new album. --------------------------------------------------------------------------*/ function checkNewAlbum(newAlbum) { if (config.active_album != newAlbum) { return true; } else { return false; } } /*-------------------------------------------------------------------------- Checks to see if there is a new playlist @param string playlist The playlist passed in to check against the active playlist. --------------------------------------------------------------------------*/ function checkNewPlaylist(playlist) { if (config.active_playlist != playlist) { return true; } else { return false; } } /*-------------------------------------------------------------------------- Sets the new song in the config. Sets the src of the audio object, updates the metadata and sets the active album. @param JSON song The song object of the song we are changing to. @param int index The index of the song in the songs object we are changing. --------------------------------------------------------------------------*/ function setNewSong(song, index) { config.active_song.src = song.url; config.active_metadata = song; config.active_album = song.album; config.active_index = index; } /*-------------------------------------------------------------------------- Shuffles individual songs in the config Based off of: http://www.codinghorror.com/blog/2007/12/the-danger-of-naivete.html --------------------------------------------------------------------------*/ function shuffleSongs() { /* Builds a temporary array with the length of the config. */ var shuffleTemp = new Array(config.songs.length); /* Set the temporary array equal to the songs array. */ for (var i = 0; i < config.songs.length; i++) { shuffleTemp[i] = config.songs[i]; shuffleTemp[i].original_index = i; } /* Iterate ove rthe songs and generate random numbers to swap the indexes of the shuffle array. */ for (var i = config.songs.length - 1; i > 0; i--) { var randNum = Math.floor(Math.random() * config.songs.length + 1); shuffleSwap(shuffleTemp, i, randNum - 1); } /* Set the shuffle list to the shuffle temp. */ config.shuffle_list = shuffleTemp; } /*-------------------------------------------------------------------------- Shuffle songs in a playlist @param string playlist The playlist we are shuffling. --------------------------------------------------------------------------*/ function shufflePlaylistSongs(playlist) { /* Builds a temporary array with the length of the playlist songs. */ var shuffleTemp = new Array(config.playlists[playlist].length); /* Set the temporary array equal to the playlist array. */ for (var i = 0; i < config.playlists[playlist].length; i++) { shuffleTemp[i] = config.songs[config.playlists[playlist][i]]; shuffleTemp[i].original_index = i; } /* Iterate ove rthe songs and generate random numbers to swap the indexes of the shuffle array. */ for (var i = config.playlists[playlist].length - 1; i > 0; i--) { var randNum = Math.floor(Math.random() * config.playlists[playlist].length + 1); shuffleSwap(shuffleTemp, i, randNum - 1); } /* Set the shuffle list to the shuffle temp. */ config.shuffled_playlists[playlist] = shuffleTemp; } /*-------------------------------------------------------------------------- Swaps and randomizes the song shuffle. @param JSON shuffleList The list of songs that is going to be shuffled @param int original The original index of the song in the songs array. @param int random The randomized index that will be the new index of the song in the shuffle array. --------------------------------------------------------------------------*/ function shuffleSwap(shuffleList, original, random) { var temp = shuffleList[original]; shuffleList[original] = shuffleList[random]; shuffleList[random] = temp; } /*-------------------------------------------------------------------------- Sets the active playlist @param string playlist The string of the playlist being set to active. --------------------------------------------------------------------------*/ function setActivePlaylist(playlist) { if (config.active_playlist != playlist) { runCallback('playlist_changed'); } config.active_playlist = playlist; } /*-------------------------------------------------------------------------- Determines if the string passed in is a URL or not @param string url The string we are testing to see if it's a URL. --------------------------------------------------------------------------*/ function isURL(url) { var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; return pattern.test(url); } /*-------------------------------------------------------------------------- Determines if what is passed in is an integer or not. @param string int The variable we are testing to see is an integer or not. --------------------------------------------------------------------------*/ function isInt(int) { return !isNaN(int) && parseInt(Number(int)) == int && !isNaN(parseInt(int, 10)); } /* Returns the public functions */ return { resetConfig: resetConfig, writeDebugMessage: writeDebugMessage, runCallback: runCallback, changeSong: changeSong, checkNewSong: checkNewSong, checkNewAlbum: checkNewAlbum, checkNewPlaylist: checkNewPlaylist, shuffleSongs: shuffleSongs, shufflePlaylistSongs: shufflePlaylistSongs, setActivePlaylist: setActivePlaylist, isURL: isURL, isInt: isInt }; }(); exports.default = AmplitudeHelpers; module.exports = exports['default']; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(0); var _config2 = _interopRequireDefault(_config); var _helpers = __webpack_require__(10); var _helpers2 = _interopRequireDefault(_helpers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* |---------------------------------------------------------------------------------------------------- | VISUAL SYNC METHODS |---------------------------------------------------------------------------------------------------- | These methods sync visual displays with what is happening in Amplitude | | Method Prefix: privateVisualSync | | METHODS | syncCurrentTime( currentTime, completionPercentage ) | resetTimes() | resetSongSliders() | setActiveContainer() | displaySongMetadata() | syncPlaybackSpeed() | syncVolumeSliders() | setPlayPauseButtonsToPause() | syncMainPlayPause( state ) | syncPlaylistPlayPause( playlist, state ) | syncSongPlayPause( playlist, song, state ) | syncRepeat() */ var AmplitudeVisualSync = function () { /*-------------------------------------------------------------------------- Visually displays the current time on the screen. This is called on time update for the current song. @param JSON currentTime An object containing the current time for the song in seconds, minutes, and hours. @param float completionPercentage The percent of the way through the song the user is at. --------------------------------------------------------------------------*/ function syncCurrentTime(currentTime, completionPercentage) { /* Set current hour display. */ _helpers2.default.syncCurrentHours(currentTime.hours); /* Set current minute display. */ _helpers2.default.syncCurrentMinutes(currentTime.minutes); /* Set current second display. */ _helpers2.default.syncCurrentSeconds(currentTime.seconds); /* Set current time display. */ _helpers2.default.syncCurrentTime(currentTime); /* Set all song sliders to be to the current percentage of the song played. */ syncMainSliderLocation(completionPercentage); syncPlaylistSliderLocation(_config2.default.active_playlist, completionPercentage); syncSongSliderLocation(_config2.default.active_playlist, _config2.default.active_index, completionPercentage); _helpers2.default.syncSongPlayedProgressBar(completionPercentage); } /*-------------------------------------------------------------------------- Visually sync all of the times to the initial time of 0. This is so we can keep all the players in sync --------------------------------------------------------------------------*/ function resetTimes() { _helpers2.default.resetCurrentHours(); _helpers2.default.resetCurrentMinutes(); _helpers2.default.resetCurrentSeconds(); _helpers2.default.resetCurrentTime(); } /*-------------------------------------------------------------------------- Visually syncs the song sliders back to 0. This usually happens when a song has changed, we ensure that all song sliders get reset. --------------------------------------------------------------------------*/ function resetSongSliders() { var songSliders = document.getElementsByClassName("amplitude-song-slider"); /* Iterate over all of the song sliders and set them to 0 essentially resetting them. */ for (var i = 0; i < songSliders.length; i++) { songSliders[i].value = 0; } } /*-------------------------------------------------------------------------- Sets all of the song buffered progress bars to 0 --------------------------------------------------------------------------*/ function resetSongBufferedProgressBars() { /* Gets all of the song buffered progress bars. */ var songBufferedProgressBars = document.getElementsByClassName("amplitude-buffered-progress"); /* Iterate over all of the song buffered progress bar and set them to 0 which is like re-setting them. */ for (var i = 0; i < songBufferedProgressBars.length; i++) { songBufferedProgressBars[i].value = 0; } } /*-------------------------------------------------------------------------- Sets all of the song played progress bars to 0 --------------------------------------------------------------------------*/ function resetSongPlayedProgressBars() { var songPlayedProgressBars = document.getElementsByClassName("amplitude-song-played-progress"); for (var i = 0; i < songPlayedProgressBars.length; i++) { songPlayedProgressBars[i].value = 0; } } /*-------------------------------------------------------------------------- Applies the class 'amplitude-active-song-container' to the element containing visual information regarding the active song. --------------------------------------------------------------------------*/ function setActiveContainer() { var songContainers = document.getElementsByClassName('amplitude-song-container'); /* Removes all of the active song containrs. */ for (var i = 0; i < songContainers.length; i++) { songContainers[i].classList.remove('amplitude-active-song-container'); } /* Finds the active index and adds the active song container to the element that represents the song at the index. */ if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null) { if (document.querySelectorAll('.amplitude-song-container[amplitude-song-index="' + _config2.default.active_index + '"]')) { var songContainers = document.querySelectorAll('.amplitude-song-container[amplitude-song-index="' + _config2.default.active_index + '"]'); for (i = 0; i < songContainers.length; i++) { if (!songContainers[i].hasAttribute('amplitude-playlist')) { songContainers[i].classList.add('amplitude-active-song-container'); } } } } else { if (document.querySelectorAll('.amplitude-song-container[amplitude-song-index="' + _config2.default.active_index + '"][amplitude-playlist="' + _config2.default.active_playlist + '"]')) { var songContainers = document.querySelectorAll('.amplitude-song-container[amplitude-song-index="' + _config2.default.active_index + '"][amplitude-playlist="' + _config2.default.active_playlist + '"]'); for (i = 0; i < songContainers.length; i++) { songContainers[i].classList.add('amplitude-active-song-container'); } } } } /*-------------------------------------------------------------------------- Displays the active song's metadata. This is called after a song has been changed. This method takes the active song and displays the metadata. So once the new active song is set, we update all of the screen elements. --------------------------------------------------------------------------*/ function displaySongMetadata() { /* Define the image meta data keys. These are managed separately since we aren't actually changing the inner HTML of these elements. */ var imageMetaDataKeys = ['cover_art_url', 'station_art_url', 'podcast_episode_cover_art_url']; /* These are the ignored keys that we won't be worrying about displaying. Every other key in the song object can be displayed. */ var ignoredKeys = ['url', 'live']; /* Get all of the song info elements */ var songInfoElements = document.querySelectorAll('[amplitude-song-info]'); /* Iterate over all of the song info elements. We will either set these to the new values, or clear them if the active song doesn't have the info set. */ for (var i = 0; i < songInfoElements.length; i++) { /* Get the info so we can check if the active meta data has the key. */ var info = songInfoElements[i].getAttribute('amplitude-song-info'); /* Get the song info element playlist. */ var playlist = songInfoElements[i].getAttribute('amplitude-playlist'); /* Get the main song info flag. */ var main = songInfoElements[i].getAttribute('amplitude-main-song-info'); /* If the playlists match or the element is a main element, then we set the song info. */ if (_config2.default.active_playlist == playlist || main == 'true') { /* If the active metadata has the key, then we set it, otherwise we clear it. If it's an image element then we default it to the default info if needed. */ if (_config2.default.active_metadata[info] != undefined) { if (imageMetaDataKeys.indexOf(info) >= 0) { songInfoElements[i].setAttribute('src', _config2.default.active_metadata[info]); } else { songInfoElements[i].innerHTML = _config2.default.active_metadata[info]; } } else { /* We look for the default album art because the actual key didn't exist. If the default album art doesn't exist then we set the src attribute to null. */ if (imageMetaDataKeys.indexOf(info) >= 0) { if (_config2.default.default_album_art != '') { songInfoElements[i].setAttribute('src', _config2.default.default_album_art); } else { songInfoElements[i].setAttribute('src', ''); } } else { songInfoElements[i].innerHTML = ''; } } } } } function setFirstSongInPlaylist(song, playlist) { /* Define the image meta data keys. These are managed separately since we aren't actually changing the inner HTML of these elements. */ var imageMetaDataKeys = ['cover_art_url', 'station_art_url', 'podcast_episode_cover_art_url']; /* These are the ignored keys that we won't be worrying about displaying. Every other key in the song object can be displayed. */ var ignoredKeys = ['url', 'live']; /* Get all of the song info elements */ var songInfoElements = document.querySelectorAll('[amplitude-song-info][amplitude-playlist="' + playlist + '"]'); /* Iterate over all of the song info elements. We will either set these to the new values, or clear them if the active song doesn't have the info set. */ for (var i = 0; i < songInfoElements.length; i++) { /* Get the info so we can check if the active meta data has the key. */ var info = songInfoElements[i].getAttribute('amplitude-song-info'); /* Get the song info element playlist. */ var elementPlaylist = songInfoElements[i].getAttribute('amplitude-playlist'); /* If the playlists match or the element is a main element, then we set the song info. */ if (elementPlaylist == playlist) { /* If the active metadata has the key, then we set it, otherwise we clear it. If it's an image element then we default it to the default info if needed. */ if (song[info] != undefined) { if (imageMetaDataKeys.indexOf(info) >= 0) { songInfoElements[i].setAttribute('src', song[info]); } else { songInfoElements[i].innerHTML = song[info]; } } else { /* We look for the default album art because the actual key didn't exist. If the default album art doesn't exist then we set the src attribute to null. */ if (imageMetaDataKeys.indexOf(info) >= 0) { if (song.default_album_art != '') { songInfoElements[i].setAttribute('src', song.default_album_art); } else { songInfoElements[i].setAttribute('src', ''); } } else { songInfoElements[i].innerHTML = ''; } } } } } /*-------------------------------------------------------------------------- Sets all of the visual playback speed buttons to have the right class to display the background image that represents the current playback speed. --------------------------------------------------------------------------*/ function syncPlaybackSpeed() { /* Gets all of the playback speed classes. */ var playbackSpeedClasses = document.getElementsByClassName("amplitude-playback-speed"); /* Iterates over all of the playback speed classes applying the right speed class for visual purposes. */ for (var i = 0; i < playbackSpeedClasses.length; i++) { /* Removes all of the old playback speed classes. */ playbackSpeedClasses[i].classList.remove('amplitude-playback-speed-10'); playbackSpeedClasses[i].classList.remove('amplitude-playback-speed-15'); playbackSpeedClasses[i].classList.remove('amplitude-playback-speed-20'); /* Switch the current playback speed and apply the appropriate speed class. */ switch (_config2.default.playback_speed) { case 1: playbackSpeedClasses[i].classList.add('amplitude-playback-speed-10'); break; case 1.5: playbackSpeedClasses[i].classList.add('amplitude-playback-speed-15'); break; case 2: playbackSpeedClasses[i].classList.add('amplitude-playback-speed-20'); break; } } } function syncBufferedProgressBars() { /* Gets all of the song buffered progress bars. */ var songBufferedProgressBars = document.getElementsByClassName("amplitude-buffered-progress"); /* Iterate over all of the song buffered progress bar and set them to 0 which is like re-setting them. */ for (var i = 0; i < songBufferedProgressBars.length; i++) { songBufferedProgressBars[i].value = parseFloat(parseFloat(_config2.default.buffered) / 100); } } /*-------------------------------------------------------------------------- Visually syncs the volume sliders so they are all the same if there are more than one. --------------------------------------------------------------------------*/ function syncVolumeSliders() { var amplitudeVolumeSliders = document.getElementsByClassName("amplitude-volume-slider"); /* Iterates over all of the volume sliders for the song, setting the value to the config value. */ for (var i = 0; i < amplitudeVolumeSliders.length; i++) { amplitudeVolumeSliders[i].value = _config2.default.active_song.volume * 100; } } /*-------------------------------------------------------------------------- Sets all of the play pause buttons to paused. --------------------------------------------------------------------------*/ function setPlayPauseButtonsToPause() { var playPauseElements = document.querySelectorAll('.amplitude-play-pause'); for (var i = 0; i < playPauseElements.length; i++) { _helpers2.default.setElementPause(playPauseElements[i]); } } /*-------------------------------------------------------------------------- Syncs the main play pause buttons to the state of the active song. @param string state The state of the player. --------------------------------------------------------------------------*/ function syncMainPlayPause(state) { if (typeof state != "string") state = _config2.default.active_song.paused ? "paused" : "playing"; /* Get all play pause buttons. */ var playPauseElements = document.querySelectorAll('.amplitude-play-pause[amplitude-main-play-pause="true"]'); /* Iterate over all of the play pause elements syncing the display visually. */ for (var i = 0; i < playPauseElements.length; i++) { /* Determines what classes we should add and remove from the elements. */ switch (state) { case 'playing': _helpers2.default.setElementPlay(playPauseElements[i]); break; case 'paused': _helpers2.default.setElementPause(playPauseElements[i]); break; } } } /*-------------------------------------------------------------------------- Syncs the main playlist play pause buttons to the state of the active song. @param string playlist The playlist we are setting the play pause state for. @param string state Either playing or paused for the state of the active song. --------------------------------------------------------------------------*/ function syncPlaylistPlayPause(playlist, state) { if (typeof state != "string") state = _config2.default.active_song.paused ? "paused" : "playing"; /* Get all of the main playlist play pause elements */ var playlistPlayPauseElements = document.querySelectorAll('.amplitude-play-pause[amplitude-playlist-main-play-pause="true"]'); /* Iterate over the play pause elements, syncing the state accordingly. */ for (var i = 0; i < playlistPlayPauseElements.length; i++) { /* If the element has the same playlist attribute as the playlist passed in and the state is playing, we set the element to be playing otherwise we set it to pause. Setting to pause means the element doesn't match the active playlist or the state is paused. */ if (playlistPlayPauseElements[i].getAttribute('amplitude-playlist') == playlist && state == 'playing') { _helpers2.default.setElementPlay(playlistPlayPauseElements[i]); } else { _helpers2.default.setElementPause(playlistPlayPauseElements[i]); } } } /*-------------------------------------------------------------------------- Syncs the song play pause buttons to the state of the active song. @param string playlist The playlist we are setting the play pause state for. @param int song The index of the song we are syncing the state for @param string state Either playing or paused for the state of the active song. --------------------------------------------------------------------------*/ function syncSongPlayPause(playlist, song, state) { if (typeof state != "string") state = _config2.default.active_song.paused ? "paused" : "playing"; /* If the playlist is null or empty, we make sure that any song that is a part of a playlist is set to paused. */ if (playlist == null || playlist == '') { /* Get all of the individual song play pause buttons. These have an amplitude-song-index attribute. Some have amplitude-playlist which means they are individual songs within a playlist. */ var songPlayPauseElements = document.querySelectorAll('.amplitude-play-pause[amplitude-song-index]'); /* Iterate over all of the song play pause elements */ for (var i = 0; i < songPlayPauseElements.length; i++) { /* If the song element has an attribute for amplitude-playlist then we set it to paused no matter what because the state of the player is not in a playlist mode. */ if (songPlayPauseElements[i].hasAttribute('amplitude-playlist')) { _helpers2.default.setElementPause(songPlayPauseElements[i]); } else { /* If the state of the song is playing and the song index matches the index of the song we have, we set the element to playing otherwise we set the element to paused. */ if (state == 'playing' && songPlayPauseElements[i].getAttribute('amplitude-song-index') == song) { _helpers2.default.setElementPlay(songPlayPauseElements[i]); } else { _helpers2.default.setElementPause(songPlayPauseElements[i]); } } } } else { /* Get all of the individual song play pause buttons. These have an amplitude-song-index attribute. Some have amplitude-playlist which means they are individual songs within a playlist. */ var songPlayPauseElements = document.querySelectorAll('.amplitude-play-pause[amplitude-song-index]'); /* Iterate over all of the individual play pause elements. */ for (var i = 0; i < songPlayPauseElements.length; i++) { /* Since we have an active playlist this time, we want any stand alone songs to be set to paused since the scope is within a playlist. We check to see if the element has an amplitude-playlist attribute. */ if (songPlayPauseElements[i].hasAttribute('amplitude-playlist')) { /* Check to see if the song index matches the index passed in and the playlist matches the scoped playlist we are looking for and the state of the player is playing, then we set the element to play. If those three parameters are not met, set the element to pause. */ if (songPlayPauseElements[i].getAttribute('amplitude-song-index') == song && songPlayPauseElements[i].getAttribute('amplitude-playlist') == playlist && state == 'playing') { _helpers2.default.setElementPlay(songPlayPauseElements[i]); } else { _helpers2.default.setElementPause(songPlayPauseElements[i]); } } else { /* Set any individual songs (songs outside of a playlist scope) to pause since we are in the scope of a playlist. */ _helpers2.default.setElementPause(songPlayPauseElements[i]); } } } } /*-------------------------------------------------------------------------- Syncs repeat for all of the repeat buttons. Users can apply styles to the 'amplitude-repeat-on' and 'amplitude-repeat-off' classes. They represent the state of the player. --------------------------------------------------------------------------*/ function syncRepeat() { /* Gets all of the repeat classes */ var repeatClasses = document.getElementsByClassName("amplitude-repeat"); /* Iterate over all of the repeat classes. If repeat is on, then add the 'amplitude-repeat-on' class and remove the 'amplitude-repeat-off' class. If it's off, then do the opposite. */ for (var i = 0; i < repeatClasses.length; i++) { if (_config2.default.repeat) { repeatClasses[i].classList.add('amplitude-repeat-on'); repeatClasses[i].classList.remove('amplitude-repeat-off'); } else { repeatClasses[i].classList.remove('amplitude-repeat-on'); repeatClasses[i].classList.add('amplitude-repeat-off'); } } } /*-------------------------------------------------------------------------- Syncs mute for all of the mute buttons. This represents the state of the player if it's muted or not. @param string state The muted state of the player. --------------------------------------------------------------------------*/ function syncMute(state) { /* Get all of the mute buttons. */ var muteClasses = document.getElementsByClassName("amplitude-mute"); /* Iterate over all of the mute classes. If the state of the player is not-muted then we add the amplitude-not-muted classe and remove the amplitude muted class otherwise we do the opposite. */ for (var i = 0; i < muteClasses.length; i++) { if (!state) { muteClasses[i].classList.add('amplitude-not-muted'); muteClasses[i].classList.remove('amplitude-muted'); } else { muteClasses[i].classList.remove('amplitude-not-muted'); muteClasses[i].classList.add('amplitude-muted'); } } } /*-------------------------------------------------------------------------- Syncs the global shuffle button visual state. @param bool state The shuffled state of the player. --------------------------------------------------------------------------*/ function syncShuffle(state) { /* Gets the shuffle buttons. */ var shuffleButtons = document.getElementsByClassName("amplitude-shuffle"); /* Iterate over all of the shuffle buttons. */ for (var i = 0; i < shuffleButtons.length; i++) { /* Ensure the shuffle button doesn't belong to a playlist. We have a separate method for that. */ if (shuffleButtons[i].getAttribute('amplitude-playlist') == null) { /* If the state of the player is shuffled on, true, then we add the 'amplitude-shuffle-on' class and remove the 'amplitude-shuffle-off' class. If the player is not shuffled then we do the opposite. */ if (state) { shuffleButtons[i].classList.add('amplitude-shuffle-on'); shuffleButtons[i].classList.remove('amplitude-shuffle-off'); } else { shuffleButtons[i].classList.add('amplitude-shuffle-off'); shuffleButtons[i].classList.remove('amplitude-shuffle-on'); } } } } /*-------------------------------------------------------------------------- Syncs the playlist shuffle button visual state. @param bool state The shuffled state of the player. @param string playlist The playlist string the shuffle button belongs to. --------------------------------------------------------------------------*/ function syncPlaylistShuffle(state, playlist) { /* Gets all of the shuffle buttons. */ var shuffleButtons = document.getElementsByClassName("amplitude-shuffle"); /* Iterate over all of the shuffle buttons */ for (var i = 0; i < shuffleButtons.length; i++) { /* Ensure that the playlist the shuffle button belongs to matches the playlist we are syncing the state for. */ if (shuffleButtons[i].getAttribute('amplitude-playlist') == playlist) { /* If the state of the playlist is shuffled on, true, then we add the 'amplitude-shuffle-on' class and remove the 'amplitude-shuffle-off' class. If the player is not shuffled then we do the opposite. */ if (state) { shuffleButtons[i].classList.add('amplitude-shuffle-on'); shuffleButtons[i].classList.remove('amplitude-shuffle-off'); } else { shuffleButtons[i].classList.add('amplitude-shuffle-off'); shuffleButtons[i].classList.remove('amplitude-shuffle-on'); } } } } /*-------------------------------------------------------------------------- Syncs the main slider location @param int location The location of the song as a percentage. --------------------------------------------------------------------------*/ function syncMainSliderLocation(location) { /* Ensure we have a location that's a number */ location = !isNaN(location) ? location : 0; /* Gets the main song sliders */ var mainSongSliders = document.querySelectorAll('.amplitude-song-slider[amplitude-main-song-slider="true"]'); /* Iterates over all of the main sliders and sets the value to the percentage of the song played. */ for (var i = 0; i < mainSongSliders.length; i++) { mainSongSliders[i].value = location; } } /*-------------------------------------------------------------------------- Syncs playlist song slider locations @param string playlist The playlist we are setting the song slider for. @param int location The location of the song as a percentage. --------------------------------------------------------------------------*/ function syncPlaylistSliderLocation(playlist, location) { /* Ensure we have a location that's a number */ location = !isNaN(location) ? location : 0; /* Gets the playlist song sliders */ var playlistSongSliders = document.querySelectorAll('.amplitude-song-slider[amplitude-playlist-song-slider="true"][amplitude-playlist="' + playlist + '"]'); /* Iterates over all of the playlist sliders and sets the value to the percentage of the song played. */ for (var i = 0; i < playlistSongSliders.length; i++) { playlistSongSliders[i].value = location; } } /*-------------------------------------------------------------------------- Syncs individual song slider locations @param string playlist The playlist we are setting the song slider for. @param int songIndex The index of the song we are adjusting the song slider for. @param int location The location of the song as a percentage. --------------------------------------------------------------------------*/ function syncSongSliderLocation(playlist, songIndex, location) { /* Ensure we have a location that's a number */ location = !isNaN(location) ? location : 0; /* If the playlist is set, we get all of the individual song sliders that relate to the song and the playlist. */ if (playlist != '' && playlist != null) { /* Gets the song sliders for the individual songs and the playlist */ var songSliders = document.querySelectorAll('.amplitude-song-slider[amplitude-playlist="' + playlist + '"][amplitude-song-index="' + songIndex + '"]'); /* Iterates over all of the playlist sliders and set the value to the percentage of the song played. */ for (var i = 0; i < songSliders.length; i++) { songSliders[i].value = location; } } else { /* Get the individual song slider by index */ var songSliders = document.querySelectorAll('.amplitude-song-slider[amplitude-song-index="' + songIndex + '"]'); /* Iterats over all of the song sliders that have the index of the song we are sliding. If the song doesn't have a playlist attribute, we set the location. */ for (var i = 0; i < songSliders.length; i++) { if (!songSliders[i].hasAttribute('amplitude-playlist')) { if (location != 0) { songSliders[i].value = location; } } } } } /*-------------------------------------------------------------------------- Sets the volume slider location @param int volume The volume from 0 - 1 for song volume. --------------------------------------------------------------------------*/ function syncVolumeSliderLocation(volume) { /* Gets all of the volume sliders */ var volumeSliders = document.querySelectorAll('.amplitude-volume-slider'); /* Iterates over all of the sliders and sets their volume to the volume of the song. */ for (var i = 0; i < volumeSliders.length; i++) { volumeSliders[i].value = volume; } } /*-------------------------------------------------------------------------- Syncs the song's duration @param songDuration Object containing information about the duration of the song --------------------------------------------------------------------------*/ function syncSongDuration(currentTime, songDuration) { /* Set duration hour display. */ _helpers2.default.syncDurationHours(songDuration != undefined && !isNaN(songDuration.hours) ? songDuration.hours : '00'); /* Set duration minute display. */ _helpers2.default.syncDurationMinutes(songDuration != undefined && !isNaN(songDuration.minutes) ? songDuration.minutes : '00'); /* Set duration second display. */ _helpers2.default.syncDurationSeconds(songDuration != undefined && !isNaN(songDuration.seconds) ? songDuration.seconds : '00'); /* Set duration time display. */ _helpers2.default.syncDurationTime(songDuration != undefined ? songDuration : {}); /* Set count down time display. */ _helpers2.default.syncCountDownTime(currentTime, songDuration); } /* Returns the publically available functions */ return { syncCurrentTime: syncCurrentTime, resetTimes: resetTimes, resetSongSliders: resetSongSliders, resetSongPlayedProgressBars: resetSongPlayedProgressBars, resetSongBufferedProgressBars: resetSongBufferedProgressBars, setActiveContainer: setActiveContainer, displaySongMetadata: displaySongMetadata, syncPlaybackSpeed: syncPlaybackSpeed, syncBufferedProgressBars: syncBufferedProgressBars, syncVolumeSliders: syncVolumeSliders, setPlayPauseButtonsToPause: setPlayPauseButtonsToPause, setFirstSongInPlaylist: setFirstSongInPlaylist, syncMainPlayPause: syncMainPlayPause, syncPlaylistPlayPause: syncPlaylistPlayPause, syncSongPlayPause: syncSongPlayPause, syncRepeat: syncRepeat, syncMute: syncMute, syncShuffle: syncShuffle, syncPlaylistShuffle: syncPlaylistShuffle, syncMainSliderLocation: syncMainSliderLocation, syncPlaylistSliderLocation: syncPlaylistSliderLocation, syncSongSliderLocation: syncSongSliderLocation, syncVolumeSliderLocation: syncVolumeSliderLocation, syncSongDuration: syncSongDuration }; }(); exports.default = AmplitudeVisualSync; module.exports = exports['default']; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(0); var _config2 = _interopRequireDefault(_config); var _helpers = __webpack_require__(1); var _helpers2 = _interopRequireDefault(_helpers); var _visual = __webpack_require__(2); var _visual2 = _interopRequireDefault(_visual); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* |---------------------------------------------------------------------------------------------------- | CORE FUNCTIONAL METHODS |---------------------------------------------------------------------------------------------------- | Interacts directly with native functions of the Audio element. Logic | leading up to these methods are handled by click handlers which call | helpers and visual synchronizers. These are the core functions of AmplitudeJS. | Every other function that leads to these prepare the information to be | acted upon by these functions. | | METHODS | play() | pause() | stop() | setVolume( volumeLevel ) | setSongLocation( songPercentage ) | disconnectStream() | reconnectStream() | playNow() | setPlaybackSpeed() */ var AmplitudeCore = function () { /*-------------------------------------------------------------------------- Plays the active song. If the current song is live, it reconnects the stream before playing. --------------------------------------------------------------------------*/ function play() { /* Run the before play callback */ _helpers2.default.runCallback('before_play'); /* If the audio is live we re-conenct the stream. */ if (_config2.default.active_metadata.live) { reconnectStream(); } /* Mobile remote sources need to be reconnected on play. I think this is because mobile browsers are optimized not to load all resources for speed reasons. We only do this if mobile and the paused button is not clicked. If the pause button was clicked then we don't reconnect or the user will lose their place in the stream. */ if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) && !_config2.default.paused) { reconnectStream(); } /* Play the song and set the playback rate to the playback speed. */ _config2.default.active_song.play(); _config2.default.active_song.playbackRate = _config2.default.playback_speed; /* Run the after play callback */ _helpers2.default.runCallback('after_play'); } /*-------------------------------------------------------------------------- Pauses the active song. If it's live, it disconnects the stream. --------------------------------------------------------------------------*/ function pause() { _helpers2.default.runCallback('before_pause'); /* Pause the active song. */ _config2.default.active_song.pause(); /* Flag that pause button was clicked. */ _config2.default.paused = true; if (_config2.default.active_metadata.live) { disconnectStream(); } _helpers2.default.runCallback('after_pause'); } /*-------------------------------------------------------------------------- Stops the active song by setting the current song time to 0. When the user resumes, it will be from the beginning. If it's a live stream it disconnects. --------------------------------------------------------------------------*/ function stop() { _helpers2.default.runCallback('before_stop'); if (_config2.default.active_song.currentTime != 0) { _config2.default.active_song.currentTime = 0; } _config2.default.active_song.pause(); if (_config2.default.active_metadata.live) { disconnectStream(); } _helpers2.default.runCallback('after_stop'); } /*-------------------------------------------------------------------------- Sets the song volume. @param int volumeLevel A number between 1 and 100 as a percentage of min to max for a volume level. --------------------------------------------------------------------------*/ function setVolume(volumeLevel) { /* If the volume is set to mute somewhere else, we sync the display. */ if (volumeLevel == 0) { _visual2.default.syncMute(true); } else { _visual2.default.syncMute(false); } _config2.default.active_song.volume = volumeLevel / 100; } /*-------------------------------------------------------------------------- Sets the song percentage. If it's a live song, we ignore this because we can't skip ahead. This is an issue if you have a playlist with a live source. @param int songPercentage A number between 1 and 100 as a percentage of song completion. --------------------------------------------------------------------------*/ function setSongLocation(songPercentage) { if (!_config2.default.active_metadata.live) { _config2.default.active_song.currentTime = _config2.default.active_song.duration * (song_percentage / 100); } } /*-------------------------------------------------------------------------- Skips to a location in a song @param int seconds An integer containing the seconds to skip to --------------------------------------------------------------------------*/ function skipToLocation(seconds) { /* When the active song can be played through, we can check to see if the seconds will work. We only bind the event handler once and remove it once it's fired. */ _config2.default.active_song.addEventListener('canplaythrough', function () { /* If the active song duration is greater than or equal to the amount of seconds the user wants to skip to and the seconds is greater than 0, we skip to the seconds defined. */ if (_config2.default.active_song.duration >= seconds && seconds > 0) { _config2.default.active_song.currentTime = seconds; } else { _helpers2.default.writeDebugMessage('Amplitude can\'t skip to a location greater than the duration of the audio or less than 0'); } }, { once: true }); } /*-------------------------------------------------------------------------- Disconnects the live stream --------------------------------------------------------------------------*/ function disconnectStream() { _config2.default.active_song.src = ''; _config2.default.active_song.load(); } /*-------------------------------------------------------------------------- Reconnects the live stream --------------------------------------------------------------------------*/ function reconnectStream() { _config2.default.active_song.src = _config2.default.active_metadata.url; _config2.default.active_song.load(); } /*-------------------------------------------------------------------------- When you pass a song object it plays that song right awawy. It sets the active song in the config to the song you pass in and synchronizes the visuals. Public Accessor: Amplitude.playNow( song_json ) @param song JSON representation of a song. --------------------------------------------------------------------------*/ function playNow(song) { /* Makes sure the song object has a URL associated with it or there will be nothing to play. */ if (song.url) { _config2.default.active_song.src = song.url; _config2.default.active_metadata = song; _config2.default.active_album = song.album; } else { /* Write error message since the song passed in doesn't have a URL. */ _helpers2.default.writeDebugMessage('The song needs to have a URL!'); } /* Sets the main song control status visual */ _visual2.default.syncMainPlayPause('playing'); /* Update the song meta data */ _visual2.default.displaySongMetadata(); /* Reset the song sliders, song progress bar info, and reset times. This ensures everything stays in sync. */ _visual2.default.resetSongSliders(); _visual2.default.resetSongPlayedProgressBars(); _visual2.default.resetTimes(); /* Plays the song. */ play(); } /*-------------------------------------------------------------------------- Sets the playback speed for the song. @param float playbackSpeed The speed we want the song to play back at. --------------------------------------------------------------------------*/ function setPlaybackSpeed(playbackSpeed) { /* Set the config playback speed. */ _config2.default.playback_speed = playbackSpeed; /* Set the active song playback rate. */ _config2.default.active_song.playbackRate = _config2.default.playback_speed; } /* Return publically facing functions */ return { play: play, pause: pause, stop: stop, setVolume: setVolume, setSongLocation: setSongLocation, skipToLocation: skipToLocation, disconnectStream: disconnectStream, reconnectStream: reconnectStream, playNow: playNow, setPlaybackSpeed: setPlaybackSpeed }; }(); exports.default = AmplitudeCore; module.exports = exports['default']; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(0); var _config2 = _interopRequireDefault(_config); var _helpers = __webpack_require__(1); var _helpers2 = _interopRequireDefault(_helpers); var _handlers = __webpack_require__(7); var _handlers2 = _interopRequireDefault(_handlers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* |---------------------------------------------------------------------------------------------------- | EVENTS METHODS |---------------------------------------------------------------------------------------------------- | These methods are called when we need to bind events to certain elements. | | METHODS: | initializeEvents() | bindPlay() | bindPause() | bindPlayPause() | bindStop() | bindMute() | bindVolumeUp() | bindVolumeDown() | bindSongSlider() | bindVolumeSlider() | bindNext() | bindPrev() | bindShuffle() | bindRepeat() | bindPlaybackSpeed() | bindSkipTo() | bindProgress() */ var AmplitudeEvents = function () { /*-------------------------------------------------------------------------- Initializes the handlers for the events listened to by Amplitude --------------------------------------------------------------------------*/ function initializeEvents() { /* Write out debug message */ _helpers2.default.writeDebugMessage('Beginning initialization of event handlers..'); /* Sets flag that the screen is moving and not a tap */ document.addEventListener('touchmove', function () { _config2.default.is_touch_moving = true; }); /* On touch end if it was a touch move event, set moving to false */ document.addEventListener('touchend', function () { if (_config2.default.is_touch_moving) { _config2.default.is_touch_moving = false; } }); /* On time update for the audio element, update visual displays that represent the time on either a visualized element or time display. */ bindTimeUpdate(); /* Binds key down event handlers for matching key codes to functions. */ bindKeyDownEventHandlers(); /* When the audio element has ended playing, we handle the song ending. In a single song or multiple modular song instance, this just synchronizes the visuals for time and song time visualization, but for a playlist it determines whether it should play the next song or not. */ bindSongEnded(); /* Binds progress event so we can see how much of the song is loaded. */ bindProgress(); /* Binds 'amplitude-play' event handlers */ bindPlay(); /* Binds 'amplitude-pause' event handlers. */ bindPause(); /* Binds 'amplitude-play-pause' event handlers. */ bindPlayPause(); /* Binds 'amplitude-stop' event handlers. */ bindStop(); /* Binds 'amplitude-mute' event handlers. */ bindMute(); /* Binds 'amplitude-volume-up' event handlers */ bindVolumeUp(); /* Binds 'amplitude-volume-down' event handlers */ bindVolumeDown(); /* Binds 'amplitude-song-slider' event handlers */ bindSongSlider(); /* Binds 'amplitude-volume-slider' event handlers. */ bindVolumeSlider(); /* Binds 'amplitude-next' event handlers. */ bindNext(); /* Binds 'amplitude-prev' event handlers. */ bindPrev(); /* Binds 'amplitude-shuffle' event handlers. */ bindShuffle(); /* Binds 'amplitude-repeat' event handlers. */ bindRepeat(); /* Binds 'amplitude-playback-speed' event handlers. */ bindPlaybackSpeed(); /* Binds 'amplitude-skip-to' event handlers. */ bindSkipTo(); } /*-------------------------------------------------------------------------- On time update for the audio element, update visual displays that represent the time on either a visualized element or time display. --------------------------------------------------------------------------*/ function bindTimeUpdate() { _config2.default.active_song.removeEventListener('timeupdate', _handlers2.default.updateTime); _config2.default.active_song.addEventListener('timeupdate', _handlers2.default.updateTime); // also bind change of duratuion _config2.default.active_song.removeEventListener('durationchange', _handlers2.default.updateTime); _config2.default.active_song.addEventListener('durationchange', _handlers2.default.updateTime); } /*-------------------------------------------------------------------------- On keydown, we listen to what key got pressed so we can map the key to a function. This allows the user to map pause and play, next, etc. to key presses. --------------------------------------------------------------------------*/ function bindKeyDownEventHandlers() { document.removeEventListener("keydown", _helpers2.default.keydown); document.addEventListener("keydown", _handlers2.default.keydown); } /*-------------------------------------------------------------------------- When the audio element has ended playing, we handle the song ending. In a single song or multiple modular song instance, this just synchronizes the visuals for time and song time visualization, but for a playlist it determines whether it should play the next song or not. --------------------------------------------------------------------------*/ function bindSongEnded() { _config2.default.active_song.removeEventListener('ended', _handlers2.default.songEnded); _config2.default.active_song.addEventListener('ended', _handlers2.default.songEnded); } /*-------------------------------------------------------------------------- As the audio is loaded, the progress event gets fired. We bind into this to grab the buffered percentage of the song. We can then add more elements to show the buffered amount. --------------------------------------------------------------------------*/ function bindProgress() { _config2.default.active_song.removeEventListener('progress', _handlers2.default.progess); _config2.default.active_song.addEventListener('progress', _handlers2.default.progress); } /*-------------------------------------------------------------------------- BINDS: class="amplitude-play" Binds click and touchend events for amplitude play buttons. --------------------------------------------------------------------------*/ function bindPlay() { /* Gets all of the elements with the class amplitude-play */ var play_classes = document.getElementsByClassName("amplitude-play"); /* Iterates over all of the play classes and binds the event interaction method to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < play_classes.length; i++) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { play_classes[i].removeEventListener('touchend', _handlers2.default.play); play_classes[i].addEventListener('touchend', _handlers2.default.play); } else { play_classes[i].removeEventListener('click', _handlers2.default.play); play_classes[i].addEventListener('click', _handlers2.default.play); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-pause" Binds click and touchend events for amplitude pause buttons. --------------------------------------------------------------------------*/ function bindPause() { /* Gets all of the elements with the class amplitude-pause */ var pause_classes = document.getElementsByClassName("amplitude-pause"); /* Iterates over all of the pause classes and binds the event interaction method to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < pause_classes.length; i++) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { pause_classes[i].removeEventListener('touchend', _handlers2.default.pause); pause_classes[i].addEventListener('touchend', _handlers2.default.pause); } else { pause_classes[i].removeEventListener('click', _handlers2.default.pause); pause_classes[i].addEventListener('click', _handlers2.default.pause); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-play-pause" Binds click and touchend events for amplitude play pause buttons. --------------------------------------------------------------------------*/ function bindPlayPause() { /* Gets all of the elements with the class amplitude-play-pause */ var play_pause_classes = document.getElementsByClassName("amplitude-play-pause"); /* Iterates over all of the play/pause classes and binds the event interaction method to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < play_pause_classes.length; i++) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { play_pause_classes[i].removeEventListener('touchend', _handlers2.default.playPause); play_pause_classes[i].addEventListener('touchend', _handlers2.default.playPause); } else { play_pause_classes[i].removeEventListener('click', _handlers2.default.playPause); play_pause_classes[i].addEventListener('click', _handlers2.default.playPause); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-stop" Binds click and touchend events for amplitude stop buttons --------------------------------------------------------------------------*/ function bindStop() { /* Gets all of the elements with the class amplitude-stop */ var stop_classes = document.getElementsByClassName("amplitude-stop"); /* Iterates over all of the stop classes and binds the event interaction method to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < stop_classes.length; i++) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { stop_classes[i].removeEventListener('touchend', _handlers2.default.stop); stop_classes[i].addEventListener('touchend', _handlers2.default.stop); } else { stop_classes[i].removeEventListener('click', _handlers2.default.stop); stop_classes[i].addEventListener('click', _handlers2.default.stop); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-mute" Binds click and touchend events for amplitude mute buttons --------------------------------------------------------------------------*/ function bindMute() { /* Gets all of the elements with the class amplitue-mute */ var mute_classes = document.getElementsByClassName("amplitude-mute"); /* Iterates over all of the mute classes and binds the event interaction method to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < mute_classes.length; i++) { /* WARNING: If iOS, we don't do anything because iOS does not allow the volume to be adjusted through anything except the buttons on the side of the device. */ if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { /* Checks for an iOS device and displays an error message if debugging is turned on. */ if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) { _helpers2.default.writeDebugMessage('iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4'); } else { mute_classes[i].removeEventListener('touchend', _handlers2.default.mute); mute_classes[i].addEventListener('touchend', _handlers2.default.mute); } } else { mute_classes[i].removeEventListener('click', _handlers2.default.mute); mute_classes[i].addEventListener('click', _handlers2.default.mute); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-volume-up" Binds click and touchend events for amplitude volume up buttons --------------------------------------------------------------------------*/ function bindVolumeUp() { /* Gets all of the elements with the class amplitude-volume-up */ var volume_up_classes = document.getElementsByClassName("amplitude-volume-up"); /* Iterates over all of the volume up classes and binds the event interaction methods to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < volume_up_classes.length; i++) { /* WARNING: If iOS, we don't do anything because iOS does not allow the volume to be adjusted through anything except the buttons on the side of the device. */ if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { /* Checks for an iOS device and displays an error message if debugging is turned on. */ if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) { _helpers2.default.writeDebugMessage('iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4'); } else { volume_up_classes[i].removeEventListener('touchend', _handlers2.default.volumeUp); volume_up_classes[i].addEventListener('touchend', _handlers2.default.volumeUp); } } else { volume_up_classes[i].removeEventListener('click', _handlers2.default.volumeUp); volume_up_classes[i].addEventListener('click', _handlers2.default.volumeUp); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-volume-down" Binds click and touchend events for amplitude volume down buttons --------------------------------------------------------------------------*/ function bindVolumeDown() { /* Gets all of the elements with the class amplitude-volume-down */ var volume_down_classes = document.getElementsByClassName("amplitude-volume-down"); /* Iterates over all of the volume down classes and binds the event interaction methods to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < volume_down_classes.length; i++) { /* WARNING: If iOS, we don't do anything because iOS does not allow the volume to be adjusted through anything except the buttons on the side of the device. */ if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { /* Checks for an iOS device and displays an error message if debugging is turned on. */ if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) { _helpers2.default.writeDebugMessage('iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4'); } else { volume_down_classes[i].removeEventListener('touchend', _handlers2.default.volumeDown); volume_down_classes[i].addEventListener('touchend', _handlers2.default.volumeDown); } } else { volume_down_classes[i].removeEventListener('click', _handlers2.default.volumeDown); volume_down_classes[i].addEventListener('click', _handlers2.default.volumeDown); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-song-slider" Binds change and input events for amplitude song slider inputs --------------------------------------------------------------------------*/ function bindSongSlider() { /* Gets browser so if we need to apply overrides, like we usually have to do for anything cool in IE, we can do that. */ var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); /* Gets all of the elements with the class amplitude-song-slider */ var song_sliders = document.getElementsByClassName("amplitude-song-slider"); /* Iterates over all of the song slider classes and binds the event interaction methods to the element. If the browser is IE we listen to the change event where if it is anything else, it's the input method. */ for (var i = 0; i < song_sliders.length; i++) { if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) { song_sliders[i].removeEventListener('change', _handlers2.default.songSlider); song_sliders[i].addEventListener('change', _handlers2.default.songSlider); } else { song_sliders[i].removeEventListener('input', _handlers2.default.songSlider); song_sliders[i].addEventListener('input', _handlers2.default.songSlider); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-volume-slider" Binds change and input events for amplitude volume slider inputs --------------------------------------------------------------------------*/ function bindVolumeSlider() { /* Gets browser so if we need to apply overrides, like we usually have to do for anything cool in IE, we can do that. */ var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); /* Gets all of the elements with the class amplitude-volume-slider */ var volume_sliders = document.getElementsByClassName("amplitude-volume-slider"); /* Iterates over all of the volume slider classes and binds the event interaction methods to the element. If the browser is IE we listen to the change event where if it is anything else, it's the input method. */ for (var i = 0; i < volume_sliders.length; i++) { /* WARNING: If iOS, we don't do anything because iOS does not allow the volume to be adjusted through anything except the buttons on the side of the device. */ if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) { _helpers2.default.writeDebugMessage('iOS does NOT allow volume to be set through javascript: https://developer.apple.com/library/safari/documentation/AudioVideo/Conceptual/Using_HTML5_Audio_Video/Device-SpecificConsiderations/Device-SpecificConsiderations.html#//apple_ref/doc/uid/TP40009523-CH5-SW4'); } else { if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) { volume_sliders[i].removeEventListener('change', _handlers2.default.volumeSlider); volume_sliders[i].addEventListener('change', _handlers2.default.volumeSlider); } else { volume_sliders[i].removeEventListener('input', _handlers2.default.volumeSlider); volume_sliders[i].addEventListener('input', _handlers2.default.volumeSlider); } } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-next" Binds click and touchend events for amplitude next buttons. --------------------------------------------------------------------------*/ function bindNext() { /* Gets all of the elements with the class amplitude-next */ var next_classes = document.getElementsByClassName("amplitude-next"); /* Iterates over all of the next classes and binds the event interaction methods to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < next_classes.length; i++) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { next_classes[i].removeEventListener('touchend', _handlers2.default.next); next_classes[i].addEventListener('touchend', _handlers2.default.next); } else { next_classes[i].removeEventListener('click', _handlers2.default.next); next_classes[i].addEventListener('click', _handlers2.default.next); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-prev" Binds click and touchend events for amplitude prev buttons. --------------------------------------------------------------------------*/ function bindPrev() { /* Gets all of the elements with the class amplitude-prev */ var prev_classes = document.getElementsByClassName("amplitude-prev"); /* Iterates over all of the prev classes and binds the event interaction methods to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < prev_classes.length; i++) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { prev_classes[i].removeEventListener('touchend', _handlers2.default.prev); prev_classes[i].addEventListener('touchend', _handlers2.default.prev); } else { prev_classes[i].removeEventListener('click', _handlers2.default.prev); prev_classes[i].addEventListener('click', _handlers2.default.prev); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-shuffle" Binds click and touchend events for amplitude shuffle buttons. --------------------------------------------------------------------------*/ function bindShuffle() { /* Gets all of the elements with the class amplitude-shuffle */ var shuffle_classes = document.getElementsByClassName("amplitude-shuffle"); /* Iterates over all of the shuffle classes and binds the event interaction methods to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < shuffle_classes.length; i++) { /* Since we are re-binding everything we remove any classes that signify a state of the shuffle control. */ shuffle_classes[i].classList.remove('amplitude-shuffle-on'); shuffle_classes[i].classList.add('amplitude-shuffle-off'); if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { shuffle_classes[i].removeEventListener('touchend', _handlers2.default.shuffle); shuffle_classes[i].addEventListener('touchend', _handlers2.default.shuffle); } else { shuffle_classes[i].removeEventListener('click', _handlers2.default.shuffle); shuffle_classes[i].addEventListener('click', _handlers2.default.shuffle); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-repeat" Binds click and touchend events for amplitude repeat buttons. --------------------------------------------------------------------------*/ function bindRepeat() { /* Gets all of the elements with the class amplitude-repeat */ var repeat_classes = document.getElementsByClassName("amplitude-repeat"); /* Iterates over all of the repeat classes and binds the event interaction methods to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < repeat_classes.length; i++) { /* Since we are re-binding everything we remove any classes that signify a state of the repeat control. */ repeat_classes[i].classList.remove('amplitude-repeat-on'); repeat_classes[i].classList.add('amplitude-repeat-off'); if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { repeat_classes[i].removeEventListener('touchend', _handlers2.default.repeat); repeat_classes[i].addEventListener('touchend', _handlers2.default.repeat); } else { repeat_classes[i].removeEventListener('click', _handlers2.default.repeat); repeat_classes[i].addEventListener('click', _handlers2.default.repeat); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-playback-speed" Binds click and touchend events for amplitude playback speed buttons. --------------------------------------------------------------------------*/ function bindPlaybackSpeed() { /* Gets all of the elements with the class amplitude-playback-speed */ var playback_speed_classes = document.getElementsByClassName("amplitude-playback-speed"); /* Iterates over all of the playback speed classes and binds the event interaction methods to the element. If the browser is mobile, then the event is touchend otherwise it is click. */ for (var i = 0; i < playback_speed_classes.length; i++) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { playback_speed_classes[i].removeEventListener('touchend', _handlers2.default.playbackSpeed); playback_speed_classes[i].addEventListener('touchend', _handlers2.default.playbackSpeed); } else { playback_speed_classes[i].removeEventListener('click', _handlers2.default.playbackSpeed); playback_speed_classes[i].addEventListener('click', _handlers2.default.playbackSpeed); } } } /*-------------------------------------------------------------------------- BINDS: class="amplitude-skip-to" Binds click and touchend events for amplitude skip to buttons. --------------------------------------------------------------------------*/ function bindSkipTo() { /* Gets all of the skip to elements with the class 'amplitude-skip-to' */ var skipToClasses = document.getElementsByClassName("amplitude-skip-to"); /* Iterates over all of the skip to classes and binds the event interaction methods to the element. If the browser is mobile, then the event is touchend otherwise it's a click. */ for (var i = 0; i < skipToClasses.length; i++) { if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { skipToClasses[i].removeEventListener('touchend', _handlers2.default.skipTo); skipToClasses[i].addEventListener('touchend', _handlers2.default.skipTo); } else { skipToClasses[i].removeEventListener('click', _handlers2.default.skipTo); skipToClasses[i].addEventListener('click', _handlers2.default.skipTo); } } } return { initializeEvents: initializeEvents }; }(); /* Import the necessary classes and config to use with the events. */ exports.default = AmplitudeEvents; module.exports = exports['default']; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(0); var _config2 = _interopRequireDefault(_config); var _visual = __webpack_require__(2); var _visual2 = _interopRequireDefault(_visual); var _core = __webpack_require__(3); var _core2 = _interopRequireDefault(_core); var _helpers = __webpack_require__(1); var _helpers2 = _interopRequireDefault(_helpers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* |------------------------------------------------------------------------------- | EVENT HANDLER HELPER METHODS |------------------------------------------------------------------------------- | These methods help handle interactions whether it's computation or shuffling | songs. | | METHODS | computeCurrentTimes() | computeSongDuration() | computeSongCompletionPercentage() */ var AmplitudeEventHelpers = function () { /*-------------------------------------------------------------------------- Computes the current song time. Breaks down where the song is into hours, minutes, seconds and formats it to be displayed to the user. --------------------------------------------------------------------------*/ function computeCurrentTimes() { /* Initialize the current time object that will be returned. */ var currentTime = {}; /* Computes the current seconds for the song. */ var currentSeconds = (Math.floor(_config2.default.active_song.currentTime % 60) < 10 ? '0' : '') + Math.floor(_config2.default.active_song.currentTime % 60); /* Computes the current minutes for the song. */ var currentMinutes = Math.floor(_config2.default.active_song.currentTime / 60); /* Initialize the current hours variable. */ var currentHours = '00'; /* If the current minutes is less than 10, we add a leading 0. */ if (currentMinutes < 10) { currentMinutes = '0' + currentMinutes; } /* If the user is more than 60 minutes into the song, then we extract the hours. */ if (currentMinutes > 60) { currentHours = Math.floor(currentMinutes / 60); currentMinutes = currentMinutes % 60; /* If the user is less than 10 hours in, we append the additional 0 to the hours. */ if (currentHours < 10) { currentHours = '0' + currentHours; } /* If the user is less than 10 minutes in, we append the additional 0 to the minutes. */ if (currentMinutes < 10) { currentMinutes = '0' + currentMinutes; } } /* Build a clean current time object and send back the appropriate information. */ currentTime.seconds = currentSeconds; currentTime.minutes = currentMinutes; currentTime.hours = currentHours; return currentTime; } /*-------------------------------------------------------------------------- Computes the current song duration. Breaks down where the song is into hours, minutes, seconds and formats it to be displayed to the user. --------------------------------------------------------------------------*/ function computeSongDuration() { /* Initialize the song duration object that will be returned. */ var songDuration = {}; /* Computes the duration of the song's seconds. */ var songDurationSeconds = (Math.floor(_config2.default.active_song.duration % 60) < 10 ? '0' : '') + Math.floor(_config2.default.active_song.duration % 60); /* Computes the duration of the song's minutes. */ var songDurationMinutes = Math.floor(_config2.default.active_song.duration / 60); /* Initialize the hours duration variable. */ var songDurationHours = '00'; /* If the song duration minutes is less than 10, we add a leading 0. */ if (songDurationMinutes < 10) { songDurationMinutes = '0' + songDurationMinutes; } /* If there is more than 60 minutes in the song, then we extract the hours. */ if (songDurationMinutes > 60) { songDurationHours = Math.floor(songDurationMinutes / 60); songDurationMinutes = songDurationMinutes % 60; /* If the song duration hours is less than 10 we append the additional 0. */ if (songDurationHours < 10) { songDurationHours = '0' + songDurationHours; } /* If the song duration minutes is less than 10 we append the additional 0. */ if (songDurationMinutes < 10) { songDurationMinutes = '0' + songDurationMinutes; } } /* Build a clean song duration object and send back the appropriate information. */ songDuration.seconds = songDurationSeconds; songDuration.minutes = songDurationMinutes; songDuration.hours = songDurationHours; return songDuration; } /*-------------------------------------------------------------------------- Computes the song completion percentage. --------------------------------------------------------------------------*/ function computeSongCompletionPercentage() { return _config2.default.active_song.currentTime / _config2.default.active_song.duration * 100; } /*-------------------------------------------------------------------------- Sets the current song's playback speed @param float speed The float with a base of 1 representing the speed --------------------------------------------------------------------------*/ function setPlaybackSpeed(speed) { _core2.default.setPlaybackSpeed(speed); } /*-------------------------------------------------------------------------- Sets the state of the repeat for the current song. @param bool repeat A boolean representing whether the repeat should be on or off --------------------------------------------------------------------------*/ function setRepeat(repeat) { _config2.default.repeat = repeat; } /*-------------------------------------------------------------------------- Sets the main play pause buttons to the current state of the song. --------------------------------------------------------------------------*/ function setMainPlayPause() { /* Determines what action we should take based on the state of the song. */ if (_config2.default.active_song.paused) { /* The song was paused so we sync visually for the song that is playing and we play the song. */ _visual2.default.syncMainPlayPause('playing'); /* If there is an active playlist, then we need to sync that playlist's play pause button to the state of playing. */ _visual2.default.syncPlaylistPlayPause(_config2.default.active_playlist, 'playing'); /* Sync the song play pause buttons */ _visual2.default.syncSongPlayPause(_config2.default.active_playlist, _config2.default.active_index, 'playing'); /* Play the song */ _core2.default.play(); } else { /* The song was playing so we sync visually for the song to be paused and we pause the song. */ _visual2.default.syncMainPlayPause('paused'); /* If there is an active playlist, then we need to sync that playlist's play pause button to the state of paused. */ _visual2.default.syncPlaylistPlayPause(_config2.default.active_playlist, 'paused'); /* Sync the song play pause buttons */ _visual2.default.syncSongPlayPause(_config2.default.active_playlist, _config2.default.active_index, 'paused'); /* Pause the song */ _core2.default.pause(); } } /*-------------------------------------------------------------------------- Sets the playlist main play pause buttons to the current state of the song. @param string playlist The playlist the main play pause button controls --------------------------------------------------------------------------*/ function setPlaylistPlayPause(playlist) { /* The only thing that can change when you click a playlist play pause is the playlist. Main play pauses have no change in song, song play pauses can change playlist and song. */ if (_helpers2.default.checkNewPlaylist(playlist)) { _helpers2.default.setActivePlaylist(playlist); /* Play first song in the playlist since we just switched playlists, we start from the first song. If the user has shuffle on for the playlist, then we go from the first song in the shuffle playlist array. */ if (_config2.default.shuffled_statuses[playlist]) { _helpers2.default.changeSong(_config2.default.shuffled_playlists[playlist][0].original_index); } else { _helpers2.default.changeSong(_config2.default.playlists[playlist][0]); } } /* Determines what action we should take based on the state of the song. */ if (_config2.default.active_song.paused) { /* The song was paused so we sync visually for the song that is playing and we play the song. */ _visual2.default.syncMainPlayPause('playing'); /* If there is an active playlist, then we need to sync that playlist's play pause button to the state of playing. */ _visual2.default.syncPlaylistPlayPause(_config2.default.active_playlist, 'playing'); /* Sync the song play pause buttons */ _visual2.default.syncSongPlayPause(_config2.default.active_playlist, _config2.default.active_index, 'playing'); /* Play the song */ _core2.default.play(); } else { /* The song was playing so we sync visually for the song to be paused and we pause the song. */ _visual2.default.syncMainPlayPause('paused'); /* If there is an active playlist, then we need to sync that playlist's play pause button to the state of paused. */ _visual2.default.syncPlaylistPlayPause(_config2.default.active_playlist, 'paused'); /* Sync the song play pause buttons */ _visual2.default.syncSongPlayPause(_config2.default.active_playlist, _config2.default.active_index, 'paused'); /* Pause the song */ _core2.default.pause(); } } /*-------------------------------------------------------------------------- Sets the song play pause buttons to the current state of the song. @param string playlist The playlist the song is a part of @param int songIndex The index of the song being played/paused --------------------------------------------------------------------------*/ function setSongPlayPause(playlist, songIndex) { /* There can be multiple playlists on the page and there can be multiple songs on the page AND there can be songs in multiple playlists, so we have some checking to do. */ /* Check to see if the playlist has changed. If it has, set the active playlist. */ if (_helpers2.default.checkNewPlaylist(playlist)) { _helpers2.default.setActivePlaylist(playlist); /* If there's a new playlist then we reset the song since the song could be in 2 playlists, but the user selects another playlist. */ _helpers2.default.changeSong(songIndex); } /* Check to see if the song has changed. If it has, set the active song. If it was in a playlist, the song wouldn't change here, since we already set the song when we checked for a playlist. */ if (_helpers2.default.checkNewSong(songIndex)) { /* The song selected is different, so we change the song. */ _helpers2.default.changeSong(songIndex); } /* Determines what action we should take based on the state of the song. */ if (_config2.default.active_song.paused) { /* The song was paused so we sync visually for the song that is playing and we play the song. */ _visual2.default.syncMainPlayPause('playing'); /* If there is an active playlist, then we need to sync that playlist's play pause button to the state of playing. */ _visual2.default.syncPlaylistPlayPause(_config2.default.active_playlist, 'playing'); /* Sync the song play pause buttons */ _visual2.default.syncSongPlayPause(_config2.default.active_playlist, _config2.default.active_index, 'playing'); /* Play the song */ _core2.default.play(); } else { /* The song was playing so we sync visually for the song to be paused and we pause the song. */ _visual2.default.syncMainPlayPause('paused'); /* If there is an active playlist, then we need to sync that playlist's play pause button to the state of paused. */ _visual2.default.syncPlaylistPlayPause(_config2.default.active_playlist, 'paused'); /* Sync the song play pause buttons */ _visual2.default.syncSongPlayPause(_config2.default.active_playlist, _config2.default.active_index, 'paused'); /* Pause the song */ _core2.default.pause(); } } /*-------------------------------------------------------------------------- Sets the shuffle state for a playlist @param string playlist The playlist being shuffled --------------------------------------------------------------------------*/ function setShuffle(playlist) { /* If the playlist is null, then we are dealing with the global shuffle status. */ if (playlist == null) { /* If shuffle is on, we toggle it off. If shuffle is off, we toggle on. */ if (_config2.default.shuffle_on) { _config2.default.shuffle_on = false; _config2.default.shuffle_list = {}; } else { _config2.default.shuffle_on = true; _helpers2.default.shuffleSongs(); } /* Visually sync the shuffle statuses */ _visual2.default.syncShuffle(_config2.default.shuffle_on); } else { /* If the playlist shuffled is on, we toggle it off. If the playlist shuffled is off, we toggle it on. */ if (_config2.default.shuffled_statuses[playlist]) { _config2.default.shuffled_statuses[playlist] = false; _config2.default.shuffled_playlists[playlist] = []; } else { _config2.default.shuffled_statuses[playlist] = true; _helpers2.default.shufflePlaylistSongs(playlist); } /* Visually sync the playlist shuffle statuses. */ _visual2.default.syncPlaylistShuffle(_config2.default.shuffled_statuses[playlist], playlist); } } /*-------------------------------------------------------------------------- Sets the next song when next is clicked @param songEnded (default false) If the song ended, this is set to true so we take into effect the repeat setting. --------------------------------------------------------------------------*/ function setNext() { var songEnded = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; /* Initializes the next index variable. This will be the index of the song that is next. */ var nextIndex = 0; /* Ensure we don't loop in the playlist if config.repeat is not true */ var endOfList = false; /* If the shuffle is on, we use the shuffled list of songs to determine our next song. */ if (_config2.default.shuffle_on) { /* If the active shuffle index + 1 is less than the length, then we use the next shuffle otherwise we go to the beginning of the shuffle list. */ if (parseInt(_config2.default.shuffle_active_index) + 1 < _config2.default.shuffle_list.length) { _config2.default.shuffle_active_index = parseInt(_config2.default.shuffle_active_index) + 1; /* Set the next index to be the index of the song in the shuffle list. */ nextIndex = _config2.default.shuffle_list[parseInt(_config2.default.shuffle_active_index)].original_index; } else { _config2.default.shuffle_active_index = 0; nextIndex = 0; endOfList = true; } } else { /* If the active index + 1 is less than the length of the songs, then we use the next song otherwise we go to the beginning of the song list. */ if (parseInt(_config2.default.active_index) + 1 < _config2.default.songs.length) { _config2.default.active_index = parseInt(_config2.default.active_index) + 1; } else { _config2.default.active_index = 0; endOfList = true; } /* Sets the next index. */ nextIndex = _config2.default.active_index; } /* Stops the active song. */ _core2.default.stop(); /* Change the song to the index we need. */ _helpers2.default.changeSong(nextIndex); /* If it's the end of the list and repeat is not on, do nothing. */ if (endOfList && !_config2.default.repeat) {} else { /* If the song has ended and repeat is on, play the song. */ if (!(songEnded && !_config2.default.repeat && endOfList)) { _core2.default.play(); } } /* Syncs the main play pause button, playlist play pause button and song play pause. */ _visual2.default.syncMainPlayPause(); _visual2.default.syncSongPlayPause(null, nextIndex); /* Call after next callback */ _helpers2.default.runCallback('after_next'); } /*-------------------------------------------------------------------------- Sets the next song in a playlist @param string playlist The playlist being shuffled @param songEnded (default false) If the song ended, this is set to true so we take into effect the repeat setting. --------------------------------------------------------------------------*/ function setNextPlaylist(playlist) { var songEnded = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; /* Initializes the next index */ var nextIndex = 0; /* Used to determine whether the playlist looped over If it did, only play if repeat is allowed, end otherwise @TODO: Different settings for song loop, in-playlist loop and global loop */ var endOfList = false; /* If the playlist is shuffled we get the next index of the playlist. */ if (_config2.default.shuffled_statuses[playlist]) { /* Gets the shuffled playlist's active song index. */ var shuffledPlaylistActiveSongIndex = parseInt(_config2.default.shuffled_active_indexes[playlist]); /* If the index + 1 is less than the length of the playlist, we increment the next index otherwise we take the first index of 0. */ if (shuffledPlaylistActiveSongIndex + 1 < _config2.default.shuffled_playlists[playlist].length) { /* Set the shuffled playlist active song index. */ _config2.default.shuffled_active_indexes[playlist] = shuffledPlaylistActiveSongIndex + 1; /* Get the index of the song that we will be switching to. */ nextIndex = _config2.default.shuffled_playlists[playlist][_config2.default.shuffled_active_indexes[playlist]].original_index; } else { /* Sets the active shuffled playlist active index to 0 and gets the original index of the song at the shuffled index of 0. */ _config2.default.shuffled_active_indexes[playlist] = 0; nextIndex = _config2.default.shuffled_playlists[playlist][0].original_index; endOfList = true; } } else { /* Gets the index of the active song within the scope of the playlist. */ var playlistActiveSongIndex = _config2.default.playlists[playlist].indexOf(parseInt(_config2.default.active_index)); /* Checks to see if the next index is still less than the length of the playlist. If it is, use the next index othwerwise get the first song in the playlist. */ if (playlistActiveSongIndex + 1 < _config2.default.playlists[playlist].length) { _config2.default.active_index = parseInt(_config2.default.playlists[playlist][playlistActiveSongIndex + 1]); } else { _config2.default.active_index = parseInt(_config2.default.playlists[playlist][0]); endOfList = true; } /* Sets the next inex to the active index in the config. */ nextIndex = _config2.default.active_index; } /* Stops the active song playing. */ _core2.default.stop(); /* Changes the song to the next song in the playlist. */ _helpers2.default.changeSong(nextIndex); _helpers2.default.setActivePlaylist(playlist); /* If the song has ended and repeat is on, play the song. */ if (!(songEnded && !_config2.default.repeat && endOfList)) _core2.default.play(); /* Syncs the main play pause button, playlist play pause button and song play pause. */ _visual2.default.syncMainPlayPause(); _visual2.default.syncPlaylistPlayPause(playlist); _visual2.default.syncSongPlayPause(playlist, nextIndex); /* Call after next callback */ _helpers2.default.runCallback('after_next'); } /*-------------------------------------------------------------------------- Sets the previous song --------------------------------------------------------------------------*/ function setPrev() { /* Initializes the prev index variable. This will be the index of the song that is next. */ var prevIndex = 0; /* If the shuffle is on for the individual songs, we get the previous song. */ if (_config2.default.shuffle_on) { /* If the previous index is greater than or equal to 0, we use the active index - 1. */ if (parseInt(_config2.default.shuffle_active_index) - 1 >= 0) { /* Sets the new active to be 1 less than the current active index. */ _config2.default.shuffle_active_index = parseInt(_config2.default.shuffle_active_index) - 1; /* Gets the index of the song in the song array for the new index. */ prevIndex = _config2.default.shuffle_list[parseInt(_config2.default.shuffle_active_index)].original_index; } else { /* Set the active index and previous index. */ _config2.default.shuffle_active_index = _config2.default.shuffle_list.length - 1; prevIndex = _config2.default.shuffle_list[parseInt(_config2.default.shuffle_list.length) - 1].original_index; } } else { /* If the active index - 1 is greater than or equal to 0, we subtract 1 from the active index otherwise we set the active index to the end of the songs array index. */ if (parseInt(_config2.default.active_index) - 1 >= 0) { _config2.default.active_index = parseInt(_config2.default.active_index) - 1; } else { _config2.default.active_index = _config2.default.songs.length - 1; } /* Set the previous index. */ prevIndex = _config2.default.active_index; } /* Stops the active song. */ _core2.default.stop(); /* Change the song to the index we need. */ _helpers2.default.changeSong(prevIndex); /* Play the next song. */ _core2.default.play(); /* Sync the play/pause buttons to the current state of the player. */ _visual2.default.syncMainPlayPause('playing'); _visual2.default.syncSongPlayPause(null, prevIndex, 'playing'); /* Call after prev callback */ _helpers2.default.runCallback('after_prev'); } /*-------------------------------------------------------------------------- Sets the previous song in a playlist @param string The Playlist we are setting the previous for. --------------------------------------------------------------------------*/ function setPrevPlaylist(playlist) { /* Initializes the prev index variable. This will be the index of the song that is next. */ var prevIndex = 0; /* If the shuffle is on for the playlist, we get the previous song. */ if (_config2.default.shuffled_statuses[playlist]) { /* Gets the active song index for the shuffled playlist */ var shuffledPlaylistActiveSongIndex = parseInt(_config2.default.shuffled_active_indexes[playlist]); /* If the shuffled song active index is greater than or equal to 0, we use the active index - 1. */ if (shuffledPlaylistActiveSongIndex - 1 >= 0) { /* Sets the active index to the active song index - 1 */ _config2.default.shuffled_active_indexes[playlist] = shuffledPlaylistActiveSongIndex - 1; /* Gets the index of the song in the song array for the new index. */ prevIndex = _config2.default.shuffled_playlists[playlist][_config2.default.shuffled_active_indexes[playlist]].original_index; } else { /* Set the active index and previous index. */ _config2.default.shuffled_active_indexes[playlist] = _config2.default.shuffled_playlists[playlist].length - 1; prevIndex = _config2.default.shuffled_playlists[playlist][_config2.default.shuffled_playlists[playlist].length - 1].original_index; } } else { /* Gets the active song index for the playlist */ var playlistActiveSongIndex = _config2.default.playlists[playlist].indexOf(parseInt(_config2.default.active_index)); /* If the active song index in the playlist - 1 is greater than or equal to 0, then we use the active song index - 1. */ if (playlistActiveSongIndex - 1 >= 0) { _config2.default.active_index = parseInt(_config2.default.playlists[playlist][playlistActiveSongIndex - 1]); } else { _config2.default.active_index = parseInt(_config2.default.playlists[playlist][_config2.default.playlists[playlist].length - 1]); } /* Set the previous index to the active index for use later. */ prevIndex = _config2.default.active_index; } /* Stops the active song. */ _core2.default.stop(); /* Changes the song to the prev song in the playlist. */ _helpers2.default.changeSong(prevIndex); _helpers2.default.setActivePlaylist(playlist); /* Plays the song */ _core2.default.play(); /* Syncs the main play pause button, playlist play pause button and song play pause. */ _visual2.default.syncMainPlayPause('playing'); _visual2.default.syncPlaylistPlayPause(playlist, 'playing'); _visual2.default.syncSongPlayPause(playlist, prevIndex, 'playing'); /* Call after prev callback */ _helpers2.default.runCallback('after_prev'); } /*-------------------------------------------------------------------------- Runs an event on key down @param int key The key code the event is bound to. --------------------------------------------------------------------------*/ function runKeyEvent(key) { /* Checks to see if the user bound an event to the code pressed. */ if (_config2.default.bindings[key] != undefined) { /* Determine which event should be run if bound. */ switch (_config2.default.bindings[key]) { /* Fires a play pause event. */ case 'play_pause': setSongPlayPause(_config2.default.active_playlist, _config2.default.active_index); break; /* Fires a next event. */ case 'next': /* Check to see if the current state of the player is in playlist mode or not playlist mode. */ if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null) { setNext(); } else { setNextPlaylist(_config2.default.active_playlist); } break; /* Fires a previous event. */ case 'prev': /* Check to see if the current playlist has been set or null and set the previous song. */ if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null) { AmplitudeEventHelpers.setPrev(); } else { AmplitudeEventHelpers.setPrevPlaylist(_config2.default.active_playlist); } break; /* Fires a stop event. */ case 'stop': /* Sets all of the play/pause buttons to pause */ _visual2.default.setPlayPauseButtonsToPause(); /* Stops the active song. */ _core2.default.stop(); break; /* Fires a shuffle event. */ case 'shuffle': /* Check to see if the current playlist has been set or null and set the previous song. */ if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null) { AmplitudeEventHelpers.setShuffle(null); } else { AmplitudeEventHelpers.setShuffle(_config2.default.active_playlist); } break; /* Fires a repeat event. */ case 'repeat': /* Sets repeat to the opposite of what it was set to */ AmplitudeEventHelpers.setRepeat(!_config2.default.repeat); /* Visually sync repeat */ _visual2.default.syncRepeat(); break; } } } /* Return the publically scoped functions */ return { computeCurrentTimes: computeCurrentTimes, computeSongDuration: computeSongDuration, computeSongCompletionPercentage: computeSongCompletionPercentage, setPlaybackSpeed: setPlaybackSpeed, setRepeat: setRepeat, setMainPlayPause: setMainPlayPause, setPlaylistPlayPause: setPlaylistPlayPause, setSongPlayPause: setSongPlayPause, setShuffle: setShuffle, setNext: setNext, setNextPlaylist: setNextPlaylist, setPrev: setPrev, setPrevPlaylist: setPrevPlaylist, runKeyEvent: runKeyEvent }; }(); exports.default = AmplitudeEventHelpers; module.exports = exports['default']; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _core = __webpack_require__(3); var _core2 = _interopRequireDefault(_core); var _helpers = __webpack_require__(1); var _helpers2 = _interopRequireDefault(_helpers); var _events = __webpack_require__(4); var _events2 = _interopRequireDefault(_events); var _soundcloud = __webpack_require__(9); var _soundcloud2 = _interopRequireDefault(_soundcloud); var _visual = __webpack_require__(2); var _visual2 = _interopRequireDefault(_visual); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var config = __webpack_require__(0); /* |---------------------------------------------------------------------------------------------------- | INITIALIZER FOR AMPLITUDE JS |---------------------------------------------------------------------------------------------------- | These methods initialize AmplitudeJS and make sure everything is ready to run | | METHODS | initialize( userConfig ) | countPlaylists( playlists ) | checkValidSongsInPlaylists() | playlistShuffleStatuses() | playlistShuffleLists() | eventHandlers() */ var AmplitudeInitializer = function () { /*-------------------------------------------------------------------------- The main init function. The user will call this through Amplitude.init({}) and pass in their settings. Public Accessor: Amplitude.init( user_config_json ); @param userConfig A JSON object of user defined values that help configure and initialize AmplitudeJS. --------------------------------------------------------------------------*/ function initialize(userConfig) { var ready = false; /* Reset the config on init so we have a clean slate. This is if the user has to re-init. */ _helpers2.default.resetConfig(); /* Initialize event handlers on init. This will clear any old event handlers on the amplitude element and re-bind what is necessary. */ _events2.default.initializeEvents(); /* Initializes debugging right away so we can use it for the rest of the configuration. */ config.debug = userConfig.debug != undefined ? userConfig.debug : false; /* Checks to see if the user has songs defined. */ if (userConfig.songs) { /* Checks to see if the user has some songs in the songs array. */ if (userConfig.songs.length != 0) { /* Copies over the user defined songs. and prepares Amplitude for the rest of the configuration. */ config.songs = userConfig.songs; /* Flag amplitude as ready. */ ready = true; } else { _helpers2.default.writeDebugMessage('Please add some songs, to your songs object!'); } } else { _helpers2.default.writeDebugMessage('Please provide a songs object for AmplitudeJS to run!'); } /* Initializes the audio context. In this method it checks to see if the user wants to use visualizations or not before proceeding. AMPFX-TODO: MAKE HANDLED BY AMPLITUDE FX. */ //privateHelpInitializeAudioContext(); /* Checks if the user has any playlists defined. If they do we have to initialize the functionality for the playlists. */ if (userConfig.playlists && countPlaylists(userConfig.playlists) > 0) { /* Copy the playlists over to Amplitude */ config.playlists = userConfig.playlists; /* Initialize default live settings */ initializeDefaultLiveSettings(); /* Check to see if the user has valid song indexes in their playlist. */ checkValidSongsInPlaylists(); /* Initialize the shuffle status of the playlists. */ initializePlaylistShuffleStatuses(); /* Initialize temporary place holders for shuffle lists. */ initializePlaylistShuffleLists(); /* Initializes the active shuffled indexes for shuffled playlists. */ initializePlaylistShuffleIndexes(); /* Initializes the first song in the playlist */ initializeFirstSongInPlaylistMetaData(); } /* When the preliminary config is ready, we are ready to proceed. */ if (ready) { /* Copies over the soundcloud information to the global config which will determine where we go from there. */ config.soundcloud_client = userConfig.soundcloud_client != undefined ? userConfig.soundcloud_client : ''; /* Checks if we want to use the art loaded from soundcloud. */ config.soundcloud_use_art = userConfig.soundcloud_use_art != undefined ? userConfig.soundcloud_use_art : ''; /* If the user provides a soundcloud client then we assume that there are URLs in their songs that will reference SoundcCloud. We then copy over the user config they provided to the temp_user_config so we don't mess up the global or their configs and load the soundcloud information. */ var tempUserConfig = {}; if (config.soundcloud_client != '') { tempUserConfig = userConfig; /* Load up SoundCloud for use with AmplitudeJS. */ _soundcloud2.default.loadSoundCloud(tempUserConfig); } else { /* The user is not using Soundcloud with Amplitude at this point so we just finish the configuration with the users's preferences. */ setConfig(userConfig); } } /* Debug out what was initialized with AmplitudeJS. */ _helpers2.default.writeDebugMessage('Initialized With: '); _helpers2.default.writeDebugMessage(config); } /*-------------------------------------------------------------------------- Rebinds all of the elements in the display --------------------------------------------------------------------------*/ function rebindDisplay() { _events2.default.initializeEvents(); _visual2.default.displaySongMetadata(); } /*-------------------------------------------------------------------------- Finishes the initalization of the config. Takes all of the user defined parameters and makes sure they override the defaults. The important config information is assigned in the publicInit() function. This function can be called from 2 different locations: 1. Right away on init after the important settings are defined. 2. After all of the Soundcloud URLs are resolved properly and soundcloud is configured. We will need the proper URLs from Soundcloud to stream through Amplitude so we get those right away before we set the information and the active song @param JSON userConfig The config provided by the user. --------------------------------------------------------------------------*/ function setConfig(userConfig) { /* Check to see if the user entered a start song */ if (userConfig.start_song != undefined) { /* Ensure what has been entered is an integer. */ if (_helpers2.default.isInt(userConfig.start_song)) { _helpers2.default.changeSong(userConfig.start_song); } else { _helpers2.default.writeDebugMessage("You must enter an integer index for the start song."); } } else { _helpers2.default.changeSong(0); } config.continue_next = userConfig.continue_next != undefined ? userConfig.continue_next : true; /* If the user defined a playback speed, we copy over their preference here, otherwise we default to normal playback speed of 1.0. */ config.playback_speed = userConfig.playback_speed != undefined ? userConfig.playback_speed : 1.0; /* Sets the audio playback speed. */ _core2.default.setPlaybackSpeed(config.playback_speed); /* If the user wants the song to be pre-loaded for instant playback, they set it to true. By default it's set to just load the metadata. */ config.active_song.preload = userConfig.preload != undefined ? userConfig.preload : "auto"; /* Initializes the user defined callbacks. This should be a JSON object that contains a key->value store of the callback name and the name of the function the user needs to call. */ config.callbacks = userConfig.callbacks != undefined ? userConfig.callbacks : {}; /* Initializes the user defined key bindings. This should be a JSON object that contains a key->value store of the key event number pressed and the method to be run. */ config.bindings = userConfig.bindings != undefined ? userConfig.bindings : {}; /* The user can define a starting volume in a range of 0-100 with 0 being muted and 100 being the loudest. After the config is set Amplitude sets the active song's volume to the volume defined by the user. */ config.volume = userConfig.volume != undefined ? userConfig.volume : 50; /* The user can set the volume increment and decrement values between 1 and 100 for when the volume up or down button is pressed. The default is an increase or decrease of 5. */ config.volume_increment = userConfig.volume_increment != undefined ? userConfig.volume_increment : 5; config.volume_decrement = userConfig.volume_decrement != undefined ? userConfig.volume_decrement : 5; /* Set the volume to what is defined in the config. The user can define this, so we should set it up that way. */ _core2.default.setVolume(config.volume); /* Since the user can define a start volume, we want our volume sliders to sync with the user defined start value. */ _visual2.default.syncVolumeSliders(); /* If the user defines default album art, this image will display if the active song doesn't have album art defined. */ if (userConfig.default_album_art != undefined) { config.default_album_art = userConfig.default_album_art; } else { config.default_album_art = ''; } /* Syncs all of the visual time elements to 00. */ _visual2.default.resetTimes(); /* Sets all of the play pause buttons to pause. */ _visual2.default.setPlayPauseButtonsToPause(); /* If the user has autoplay enabled, then begin playing the song. Everything should be configured for this to be ready to play. */ if (userConfig.autoplay) { config.active_playlist = null; /* Sync the main and song play pause buttons. */ _visual2.default.syncMainPlayPause('playing'); _visual2.default.syncSongPlayPause(null, 0, 'playing'); /* Start playing the song */ _core2.default.play(); } /* Run after init callback */ _helpers2.default.runCallback('after_init'); } /*-------------------------------------------------------------------------- Counts the number of playlists the user has configured. This ensures that the user has at least 1 playlist so we can validate the songs defined in the playlist are correct and they didn't enter an invalid ID. --------------------------------------------------------------------------*/ function countPlaylists(playlists) { /* Initialize the placeholders to iterate through the playlists and find out how many we have to account for. */ var size = 0, key; /* Iterate over playlists and if the user has the playlist defined, increment the size of playlists. */ for (key in playlists) { if (playlists.hasOwnProperty(key)) { size++; } } /* Debug how many playlists are in the config. */ _helpers2.default.writeDebugMessage('You have ' + size + ' playlist(s) in your config'); /* Return the number of playlists in the config. */ return size; } /*-------------------------------------------------------------------------- Ensures the indexes in the playlists are valid indexes. The song has to exist in the Amplitude config to be played correctly. --------------------------------------------------------------------------*/ function checkValidSongsInPlaylists() { /* Iterate over all of the config's playlists */ for (var key in config.playlists) { /* Checks if the playlist key is accurate. */ if (config.playlists.hasOwnProperty(key)) { /* Checks if the playlist has songs. */ if (config.playlists[key].songs) { /* Iterate over all of the songs in the playlist */ for (var i = 0; i < config.playlists[key].songs.length; i++) { /* Check to see if the index for the song in the playlist exists in the songs config. */ if (!config.songs[config.playlists[key].songs[i]]) { _helpers2.default.writeDebugMessage('The song index: ' + config.playlists[key].songs[i] + ' in playlist with key: ' + key + ' is not defined in your songs array!'); } } } } } } /*-------------------------------------------------------------------------- Initializes the shuffle statuses for each of the playlists. These will be referenced when we shuffle individual playlists. --------------------------------------------------------------------------*/ function initializePlaylistShuffleStatuses() { /* Iterate over all of the playlists the user defined adding the playlist key to the shuffled playlist array and creating and empty object to house the statuses. */ for (var key in config.playlists) { config.shuffled_statuses[key] = false; } } /*-------------------------------------------------------------------------- Initializes the shuffled playlist placeholders. These will be set for playlists that are shuffled and contain the shuffled songs. --------------------------------------------------------------------------*/ function initializePlaylistShuffleLists() { /* Iterate over all of the playlists the user defined adding the playlist key to the shuffled playlists array and creating and empty object to house the shuffled playlists */ for (var key in config.playlists) { config.shuffled_playlists[key] = []; } } /*-------------------------------------------------------------------------- Initializes the shuffled playlist indexes array. These will be set for playlists that are shuffled and contain the active shuffled index. --------------------------------------------------------------------------*/ function initializePlaylistShuffleIndexes() { /* Iterates over all of the playlists adding a key to the shuffled_active_indexes array that contains the active shuffled index. */ for (var key in config.playlists) { config.shuffled_active_indexes[key] = 0; } } /*-------------------------------------------------------------------------- Intializes the display for the first song in the playlist meta data. --------------------------------------------------------------------------*/ function initializeFirstSongInPlaylistMetaData() { /* Iterates over all of the playlists setting the meta data for the first song. */ for (var key in config.playlists) { _visual2.default.setFirstSongInPlaylist(config.songs[config.playlists[key][0]], key); } } /*-------------------------------------------------------------------------- Intializes the default live settings for all of the songs. --------------------------------------------------------------------------*/ function initializeDefaultLiveSettings() { for (var i = 0; i < config.songs.length; i++) { if (config.songs[i].live == undefined) { config.songs[i].live = false; } } } /* Returns the publicly accessible methods */ return { initialize: initialize, setConfig: setConfig, rebindDisplay: rebindDisplay }; }(); exports.default = AmplitudeInitializer; module.exports = exports['default']; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(0); var _config2 = _interopRequireDefault(_config); var _helpers = __webpack_require__(5); var _helpers2 = _interopRequireDefault(_helpers); var _visual = __webpack_require__(2); var _visual2 = _interopRequireDefault(_visual); var _core = __webpack_require__(3); var _core2 = _interopRequireDefault(_core); var _helpers3 = __webpack_require__(1); var _helpers4 = _interopRequireDefault(_helpers3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* |------------------------------------------------------------------------------- | EVENT HANDLER FUNCTIONS |------------------------------------------------------------------------------- | These functions handle the events that we bound to each element and | prepare for a function to be called. These kind of act like filters/middleware. | | METHODS | updateTime() | songEnded() | play() | pause() | playPause() | stop() | mute() | volumeUp() | volumeDown() | songSlider() | volumeSlider() | next() | prev() | shuffle() | repeat() | playbackSpeed() | skipTo() */ exports.default = { /*-------------------------------------------------------------------------- HANDLER FOR: timeupdate When the time updates on the active song, we sync the current time displays --------------------------------------------------------------------------*/ updateTime: function updateTime() { /* Help from: http://jsbin.com/badimipi/1/edit?html,js,output */ if (_config2.default.active_song.buffered.length - 1 >= 0) { var bufferedEnd = _config2.default.active_song.buffered.end(_config2.default.active_song.buffered.length - 1); var duration = _config2.default.active_song.duration; _config2.default.buffered = bufferedEnd / duration * 100; } /* Sync the buffered progress bars. */ _visual2.default.syncBufferedProgressBars(); /* If the current song is not live, then we can update the time information. Otherwise the current time updates wouldn't mean much since the time is infinite. */ if (!_config2.default.active_metadata.live) { /* Compute the current time */ var currentTime = _helpers2.default.computeCurrentTimes(); /* Compute the song completion percentage */ var songCompletionPercentage = _helpers2.default.computeSongCompletionPercentage(); /* Computes the song duration */ var songDuration = _helpers2.default.computeSongDuration(); /* Sync the current time elements with the current location of the song and the song duration elements with the duration of the song. */ _visual2.default.syncCurrentTime(currentTime, songCompletionPercentage); _visual2.default.syncSongDuration(currentTime, songDuration); /* Runs the callback defined for the time update. */ _helpers4.default.runCallback('time_update'); } }, /*-------------------------------------------------------------------------- HANDLER FOR: keydown When the keydown event is fired, we determine which function should be run based on what was passed in. --------------------------------------------------------------------------*/ keydown: function keydown() { _helpers2.default.runKeyEvent(event.which); }, /*-------------------------------------------------------------------------- HANDLER FOR: ended When the song has ended, handles what to do next --------------------------------------------------------------------------*/ songEnded: function songEnded() { if (_config2.default.continue_next) { /* If the active playlist is not set, we set the next song that's in the songs array. */ if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null) { _helpers2.default.setNext(true); } else { /* Set the next song in the playlist */ _helpers2.default.setNextPlaylist(_config2.default.active_playlist, true); } } else { if (!_config2.default.is_touch_moving) { /* Sets all of the play/pause buttons to pause */ _visual2.default.setPlayPauseButtonsToPause(); /* Stops the active song. */ _core2.default.stop(); } } }, /*-------------------------------------------------------------------------- HANDLER FOR: progress As the song is buffered, we can display the buffered percentage in a progress bar. --------------------------------------------------------------------------*/ progress: function progress() { /* Help from: http://jsbin.com/badimipi/1/edit?html,js,output */ if (_config2.default.active_song.buffered.length - 1 >= 0) { var bufferedEnd = _config2.default.active_song.buffered.end(_config2.default.active_song.buffered.length - 1); var duration = _config2.default.active_song.duration; _config2.default.buffered = bufferedEnd / duration * 100; } /* Sync the buffered progress bars. */ _visual2.default.syncBufferedProgressBars(); }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-play' Handles an event on a play button in Amplitude. --------------------------------------------------------------------------*/ play: function play() { if (!_config2.default.is_touch_moving) { /* Gets the attribute for song index so we can check if there is a need to change the song. In some scenarios there might be multiple play classes on the page. In that case it is possible the user could click a different play class and change the song. */ var playButtonSongIndex = this.getAttribute('amplitude-song-index'); var playButtonPlaylistIndex = this.getAttribute('amplitude-playlist'); if (playButtonPlaylistIndex == null && playButtonSongIndex == null) { _helpers2.default.setSongPlayPause(_config2.default.active_playlist, _config2.default.active_index); } /* */ if (playButtonPlaylistIndex != null && playButtonPlaylistIndex != '') { if (_helpers4.default.checkNewPlaylist(playButtonPlaylistIndex)) { _helpers4.default.setActivePlaylist(playButtonPlaylistIndex); if (playButtonSongIndex != null) { _helpers4.default.changeSong(playButtonSongIndex); _helpers2.default.setPlaylistPlayPause(playButtonPlaylistIndex); } else { _helpers4.default.changeSong(_config2.default.playlists[playButtonPlaylistIndex][0]); _helpers2.default.setPlaylistPlayPause(playButtonPlaylistIndex); } } else { if (playButtonSongIndex != null) { _helpers4.default.changeSong(playButtonSongIndex); _helpers2.default.setPlaylistPlayPause(playButtonPlaylistIndex); } else { _helpers4.default.changeSong(_config2.default.active_index); _helpers2.default.setPlaylistPlayPause(playButtonPlaylistIndex); } } } /* */ if ((playButtonPlaylistIndex == null || playButtonPlaylistIndex == '') && playButtonSongIndex != null && playButtonSongIndex != '') { if (_helpers4.default.checkNewSong(playButtonSongIndex) || _config2.default.active_playlist != playButtonPlaylistIndex) { _helpers4.default.changeSong(playButtonSongIndex); } _helpers2.default.setSongPlayPause(playButtonPlaylistIndex, playButtonSongIndex); } /* Start the visualizations for the song. AMPFX-TODO: MAKE HANDLED BY AMPLITUDE FX */ //privateStartVisualization(); } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-pause' --------------------------------------------------------------------------*/ pause: function pause() { if (!_config2.default.is_touch_moving) { var pauseButtonSongIndex = this.getAttribute('amplitude-song-index'); var pauseButtonPlaylistIndex = this.getAttribute('amplitude-playlist'); if (pauseButtonSongIndex == null && pauseButtonPlaylistIndex == null) { _helpers2.default.setSongPlayPause(_config2.default.active_playlist, _config2.default.active_index); _core2.default.pause(); } if (pauseButtonPlaylistIndex != null || pauseButtonPlaylistIndex != '' && _config2.default.active_playlist == pauseButtonPlaylistIndex) { /* The song was playing so we sync visually for the song to be paused and we pause the song. */ _visual2.default.syncMainPlayPause('paused'); /* If there is an active playlist, then we need to sync that playlist's play pause button to the state of paused. */ _visual2.default.syncPlaylistPlayPause(_config2.default.active_playlist, 'paused'); /* Sync the song play pause buttons */ _visual2.default.syncSongPlayPause(_config2.default.active_playlist, _config2.default.active_index, 'paused'); _core2.default.pause(); } if ((pauseButtonPlaylistIndex == null || pauseButtonPlaylistIndex == '') && pauseButtonSongIndex == _config2.default.active_index) { /* The song was playing so we sync visually for the song to be paused and we pause the song. */ _visual2.default.syncMainPlayPause('paused'); /* If there is an active playlist, then we need to sync that playlist's play pause button to the state of paused. */ _visual2.default.syncPlaylistPlayPause(_config2.default.active_playlist, 'paused'); /* Sync the song play pause buttons */ _visual2.default.syncSongPlayPause(_config2.default.active_playlist, _config2.default.active_index, 'paused'); _core2.default.pause(); } } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-play-pause' Handles an event on a play pause button. --------------------------------------------------------------------------*/ playPause: function playPause() { if (!_config2.default.is_touch_moving) { /* Checks to see if the element has an attribute for amplitude-main-play-pause and syncs accordingly */ if (this.getAttribute('amplitude-main-play-pause') != null) { _helpers2.default.setMainPlayPause(); /* Syncs playlist main play pause buttons */ } else if (this.getAttribute('amplitude-playlist-main-play-pause') != null) { var playlist = this.getAttribute('amplitude-playlist'); _helpers2.default.setPlaylistPlayPause(playlist); /* Syncs amplitude individual song buttons */ } else { var playlist = this.getAttribute('amplitude-playlist'); var songIndex = this.getAttribute('amplitude-song-index'); _helpers2.default.setSongPlayPause(playlist, songIndex); } } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-stop' Handles an event on a stop element. AMP-FX TODO: Before stopping, make sure that AmplitudeFX visualization is stopped as well. --------------------------------------------------------------------------*/ stop: function stop() { if (!_config2.default.is_touch_moving) { /* Sets all of the play/pause buttons to pause */ _visual2.default.setPlayPauseButtonsToPause(); /* Stops the active song. */ _core2.default.stop(); } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-mute' Handles an event on a mute element. --------------------------------------------------------------------------*/ mute: function mute() { if (!_config2.default.is_touch_moving) { /* If the current volume in the config is 0, we set the volume to the pre_mute level. This means that the audio is already muted and needs to be restored to the pre_mute level. Otherwise, we set pre_mute volume to the current volume and set the config volume to 0, muting the audio. */ if (_config2.default.volume == 0) { _config2.default.active_song.muted = false; _config2.default.volume = _config2.default.pre_mute_volume; _visual2.default.syncMute(false); } else { _config2.default.active_song.muted = true; _config2.default.pre_mute_volume = _config2.default.volume; _config2.default.volume = 0; _visual2.default.syncMute(true); } /* Calls the core function to set the volume to the computed value based on the user's intent. */ _core2.default.setVolume(_config2.default.volume); /* Syncs the volume sliders so the visuals align up with the functionality. If the volume is at 0, then the sliders should represent that so the user has the right starting point. */ _visual2.default.syncVolumeSliders(_config2.default.volume); } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-volume-up' Handles a click on a volume up element. --------------------------------------------------------------------------*/ volumeUp: function volumeUp() { if (!_config2.default.is_touch_moving) { /* The volume range is from 0 to 1 for an audio element. We make this a base of 100 for ease of working with. If the new value is less than 100, we use the new calculated value which gets converted to the proper unit for the audio element. If the new value is greater than 100, we set the volume to 1 which is the max for the audio element. */ if (_config2.default.volume + _config2.default.volume_increment <= 100) { _config2.default.volume = _config2.default.volume + _config2.default.volume_increment; } else { _config2.default.volume = 100; } /* Calls the core function to set the volume to the computed value based on the user's intent. */ _core2.default.setVolume(_config2.default.volume); /* Syncs the volume sliders so the visuals align up with the functionality. If the volume is at 0, then the sliders should represent that so the user has the right starting point. */ _visual2.default.syncVolumeSliders(_config2.default.volume); } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-volume-down' Handles a click on a volume down element. --------------------------------------------------------------------------*/ volumeDown: function volumeDown() { if (!_config2.default.is_touch_moving) { /* The volume range is from 0 to 1 for an audio element. We make this a base of 100 for ease of working with. If the new value is less than 100, we use the new calculated value which gets converted to the proper unit for the audio element. If the new value is greater than 100, we set the volume to 1 which is the max for the audio element. */ if (_config2.default.volume - _config2.default.volume_increment > 0) { _config2.default.volume = _config2.default.volume - _config2.default.volume_increment; } else { _config2.default.volume = 0; } /* Calls the core function to set the volume to the computed value based on the user's intent. */ _core2.default.setVolume(_config2.default.volume); /* Syncs the volume sliders so the visuals align up with the functionality. If the volume is at 0, then the sliders should represent that so the user has the right starting point. */ _visual2.default.syncVolumeSliders(_config2.default.volume); } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-song-slider' Handles a change on the song slider --------------------------------------------------------------------------*/ songSlider: function songSlider() { /* Gets the percentage of the song we will be setting the location for. */ var locationPercentage = this.value; /* Checks to see if the element has an attribute for amplitude-main-play-pause and syncs accordingly */ if (this.getAttribute('amplitude-main-song-slider') != null) { /* If the active song is not live, set the current time */ if (!_config2.default.active_metadata.live) { var currentTime = _config2.default.active_song.duration * (locationPercentage / 100); if (isFinite(currentTime)) { _config2.default.active_song.currentTime = currentTime; } } _visual2.default.syncMainSliderLocation(locationPercentage); if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null) { _visual2.default.syncPlaylistSliderLocation(_config2.default.active_playlist, locationPercentage); } } /* Syncs playlist main play pause buttons */ if (this.getAttribute('amplitude-playlist-song-slider') != null) { var playlist = this.getAttribute('amplitude-playlist'); /* We don't want to song slide a playlist that's not the active placylist. */ if (_config2.default.active_playlist == playlist) { /* If the active song is not live, set the current time */ if (!_config2.default.active_metadata.live) { _config2.default.active_song.currentTime = _config2.default.active_song.duration * (locationPercentage / 100); } _visual2.default.syncMainSliderLocation(locationPercentage); _visual2.default.syncPlaylistSliderLocation(playlist, locationPercentage); } } /* Syncs amplitude individual song buttons */ if (this.getAttribute('amplitude-playlist-song-slider') == null && this.getAttribute('amplitude-main-song-slider') == null) { var playlist = this.getAttribute('amplitude-playlist'); var songIndex = this.getAttribute('amplitude-song-index'); if (_config2.default.active_index == songIndex) { /* If the active song is not live, set the current time */ if (!_config2.default.active_metadata.live) { _config2.default.active_song.currentTime = _config2.default.active_song.duration * (locationPercentage / 100); } _visual2.default.syncMainSliderLocation(); if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null && _config2.default.active_playlist == playlist) { _visual2.default.syncPlaylistSliderLocation(playlist, location); } _visual2.default.syncSongSliderLocation(playlist, songIndex, location); } } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-volume-slider' Handles a change on the volume slider --------------------------------------------------------------------------*/ volumeSlider: function volumeSlider() { /* Calls the core function to set the volume to the computed value based on the user's intent. */ _core2.default.setVolume(this.value); /* Sync the volume slider locations */ _visual2.default.syncVolumeSliderLocation(this.value); }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-next' Handles an event on the next button --------------------------------------------------------------------------*/ next: function next() { if (!_config2.default.is_touch_moving) { /* Checks to see if the button is a playlist next button or if it's a global playlist button. */ if (this.getAttribute('amplitude-playlist') == '' || this.getAttribute('amplitude-playlist') == null) { /* Check to see if the current state of the player is in playlist mode or not playlist mode. */ if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null) { _helpers2.default.setNext(); } else { _helpers2.default.setNextPlaylist(_config2.default.active_playlist); } } else { /* Gets the playlist of the next button. */ var playlist = this.getAttribute('amplitude-playlist'); /* Sets the next playlist */ _helpers2.default.setNextPlaylist(playlist); } } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-prev' Handles an event on the previous button --------------------------------------------------------------------------*/ prev: function prev() { if (!_config2.default.is_touch_moving) { /* Checks to see if the previous button is a playlist previous button or if it's a global playlist button. */ if (this.getAttribute('amplitude-playlist') == '' || this.getAttribute('amplitude-playlist') == null) { /* Check to see if the current playlist has been set or null and set the previous song. */ if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null) { _helpers2.default.setPrev(); } else { _helpers2.default.setPrevPlaylist(_config2.default.active_playlist); } } else { /* Gets the playlist of the previous button. */ var playlist = this.getAttribute('amplitude-playlist'); /* Sets the previous playlist */ _helpers2.default.setPrevPlaylist(playlist); } } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-shuffle' Handles an event on the shuffle button --------------------------------------------------------------------------*/ shuffle: function shuffle() { if (!_config2.default.is_touch_moving) { /* Check to see if the shuffle button belongs to a playlist */ if (this.getAttribute('amplitude-playlist') == '' || this.getAttribute('amplitude-playlist') == null) { /* Sets the shuffle button to null */ _helpers2.default.setShuffle(null); } else { /* Gets the playlist attribute of the shuffle button and set shuffle to on for the playlist. */ var playlist = this.getAttribute('amplitude-playlist'); _helpers2.default.setShuffle(playlist); } } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-repeat' Handles an event on the repeat button --------------------------------------------------------------------------*/ repeat: function repeat() { if (!_config2.default.is_touch_moving) { /* Sets repeat to the opposite of what it was set to */ _helpers2.default.setRepeat(!_config2.default.repeat); /* Visually sync repeat */ _visual2.default.syncRepeat(); } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-playback-speed' Handles an event on the playback speed button --------------------------------------------------------------------------*/ playbackSpeed: function playbackSpeed() { if (!_config2.default.is_touch_moving) { /* We increment the speed by .5 everytime we click the button to change the playback speed. Once we are actively playing back at 2, we start back at 1 which is normal speed. */ switch (_config2.default.playback_speed) { case 1: _helpers2.default.setPlaybackSpeed(1.5); break; case 1.5: _helpers2.default.setPlaybackSpeed(2); break; case 2: _helpers2.default.setPlaybackSpeed(1); break; } /* Visually sync the playback speed. */ _visual2.default.syncPlaybackSpeed(); } }, /*-------------------------------------------------------------------------- HANDLER FOR: 'amplitude-skip-to' Handles an event on a skip to button. --------------------------------------------------------------------------*/ skipTo: function skipTo() { if (!_config2.default.is_touch_moving) { /* Determines if the skip to button is in the scope of a playlist. */ if (this.hasAttribute('amplitude-playlist')) { var playlist = this.getAttribute('amplitude-playlist'); if (_helpers4.default.checkNewPlaylist(playlist)) { _helpers4.default.setActivePlaylist(playlist); } /* Gets the location, playlist and song index that is being skipped to. */ var seconds = parseInt(this.getAttribute('amplitude-location')); var songIndex = parseInt(this.getAttribute('amplitude-song-index')); /* Changes the song to where it's being skipped and then play the song. */ _helpers4.default.changeSong(songIndex); _core2.default.play(); _visual2.default.syncMainPlayPause('playing'); _visual2.default.syncPlaylistPlayPause(playlist, 'playing'); _visual2.default.syncSongPlayPause(playlist, songIndex, 'playing'); /* Skip to the location in the song. */ _core2.default.skipToLocation(seconds); } else { /* Gets the location and song index that is being skipped to. */ var seconds = parseInt(this.getAttribute('amplitude-location')); var songIndex = parseInt(this.getAttribute('amplitude-song-index')); /* Changes the song to where it's being skipped and then play the song. */ _helpers4.default.changeSong(songIndex); _core2.default.play(); _visual2.default.syncMainPlayPause('playing'); _visual2.default.syncSongPlayPause(null, songIndex, 'playing'); /* Skip to the location in the song. */ _core2.default.skipToLocation(seconds); } } } }; module.exports = exports['default']; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _init = __webpack_require__(6); var _init2 = _interopRequireDefault(_init); var _core = __webpack_require__(3); var _core2 = _interopRequireDefault(_core); var _helpers = __webpack_require__(1); var _helpers2 = _interopRequireDefault(_helpers); var _events = __webpack_require__(4); var _events2 = _interopRequireDefault(_events); var _helpers3 = __webpack_require__(5); var _helpers4 = _interopRequireDefault(_helpers3); var _visual = __webpack_require__(2); var _visual2 = _interopRequireDefault(_visual); var _config = __webpack_require__(0); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* Amplitude should just be an interface to the public functions. Everything else should be handled by other objects */ var Amplitude = function () { /*-------------------------------------------------------------------------- The main init function. The user will call this through Amplitude.init({}) and pass in their settings. Public Accessor: Amplitude.init( user_config_json ); @param user_config A JSON object of user defined values that help configure and initialize AmplitudeJS. --------------------------------------------------------------------------*/ function init(userConfig) { _init2.default.initialize(userConfig); } /*-------------------------------------------------------------------------- Binds new elements that were added to the page. --------------------------------------------------------------------------*/ function bindNewElements() { _init2.default.rebindDisplay(); } /*-------------------------------------------------------------------------- Returns the active playlist --------------------------------------------------------------------------*/ function getActivePlaylist() { return _config2.default.active_playlist; } /*-------------------------------------------------------------------------- Returns the current playback speed --------------------------------------------------------------------------*/ function getPlaybackSpeed() { return _config2.default.playback_speed; } /*-------------------------------------------------------------------------- Gets the repeat state of the player. --------------------------------------------------------------------------*/ function getRepeat() { return _config2.default.repeat; } /*-------------------------------------------------------------------------- Returns the shuffle state of the player. --------------------------------------------------------------------------*/ function getShuffle() { return _config2.default.shuffle_on; } /*-------------------------------------------------------------------------- Returns the shuffle state of the playlist. @param playlist The key representing the playlist ID to see if it's shuffled or not. --------------------------------------------------------------------------*/ function getShufflePlaylist(playlist) { return _config2.default.shuffled_statuses[playlist]; } /*-------------------------------------------------------------------------- Gets the default album art for the player --------------------------------------------------------------------------*/ function getDefaultAlbumArt() { return _config2.default.default_album_art; } /*-------------------------------------------------------------------------- Sets the default album art for the player @param url A string representing the URL of the new default album art. --------------------------------------------------------------------------*/ function setDefaultAlbumArt(url) { _config2.default.default_album_art = url; } /*-------------------------------------------------------------------------- Allows the user to get the percentage of the song played. Public Accessor: Amplitude.getSongPlayedPercentage(); --------------------------------------------------------------------------*/ function getSongPlayedPercentage() { /* Returns the percentage of the song played. */ return _config2.default.active_song.currentTime / _config2.default.active_song.duration * 100; } /*-------------------------------------------------------------------------- Allows the user to set how far into the song they want to be. This is helpful for implementing custom range sliders. Only works on the current song. Public Accessor: Amplitude.setSongPlayedPercentage( float ); @param Float percentage The percentage of the song played --------------------------------------------------------------------------*/ function setSongPlayedPercentage(percentage) { /* Ensures the percentage is a number and is between 0 and 100. */ if (typeof percentage == 'number' && percentage > 0 && percentage < 100) { /* Sets the current time of the song to the percentage. */ _config2.default.active_song.currentTime = _config2.default.active_song.duration * (percentage / 100); } } /*-------------------------------------------------------------------------- Allows the user to turn on debugging. Public Accessor: Amplitude.setDebug( bool ); @param BOOL state Turns debugging on and off. --------------------------------------------------------------------------*/ function setDebug(state) { /* Sets the global config debug on or off. */ _config2.default.debug = state; } /*-------------------------------------------------------------------------- Returns the active song meta data for the user to do what is needed. Public Accessor: Amplitude.getActiveSongMetadata(); @returns JSON Object with the active song information --------------------------------------------------------------------------*/ function getActiveSongMetadata() { return _config2.default.active_metadata; } /*-------------------------------------------------------------------------- Returns a song in the songs array at that index Public Accessor: Amplitude.getSongByIndex( song_index ) @param int index The integer for the index of the song in the songs array. @returns JSON representation for the song at a specific index. --------------------------------------------------------------------------*/ function getSongByIndex(index) { return _config2.default.songs[index]; } /*-------------------------------------------------------------------------- Returns a song at a playlist index Public Accessor: Amplitude.getSongAtPlaylistIndex( playlist, index @param int index The integer for the index of the song in the playlist. @param string playlist The key of the playlist we are getting the song at the index for @returns JSON representation for the song at a specific index. --------------------------------------------------------------------------*/ function getSongAtPlaylistIndex(playlist, index) { var songIndex = _config2.default.playlists[playlist][index]; return _config2.default.songs[songIndex]; } /*-------------------------------------------------------------------------- Adds a song to the end of the config array. This will allow Amplitude to play the song in a playlist type setting. Public Accessor: Amplitude.addSong( song_json ) @param song JSON representation of a song. @returns int New index of the song. --------------------------------------------------------------------------*/ function addSong(song) { /* Ensures we have a songs array to push to. */ if (_config2.default.songs == undefined) { _config2.default.songs = []; } _config2.default.songs.push(song); return _config2.default.songs.length - 1; } /*-------------------------------------------------------------------------- When you pass a song object it plays that song right awawy. It sets the active song in the config to the song you pass in and synchronizes the visuals. Public Accessor: Amplitude.playNow( song ) @param song JSON representation of a song. --------------------------------------------------------------------------*/ function playNow(song) { _core2.default.playNow(song); } /* TODO: Implement Add Song To Playlist Functionality */ function addSongToPlaylist(song, playlist) {} /*-------------------------------------------------------------------------- Allows the user to play whatever the active song is directly through Javascript. Normally ALL of Amplitude functions that access the core features are called through event handlers. Public Accessor: Amplitude.play(); --------------------------------------------------------------------------*/ function play() { _core2.default.play(); } /*-------------------------------------------------------------------------- Allows the user to pause whatever the active song is directly through Javascript. Normally ALL of Amplitude functions that access the core features are called through event handlers. Public Accessor: Amplitude.pause(); --------------------------------------------------------------------------*/ function pause() { _core2.default.pause(); } /*-------------------------------------------------------------------------- Returns the audio object used to play the audio Public Accessor: Amplitude.getAudio(); --------------------------------------------------------------------------*/ function getAudio() { return _config2.default.active_song; } /*-------------------------------------------------------------------------- Plays the next song either in the playlist or globally. Public Accessor: Amplitude.next( playlist ); @param string playlist The playlist key --------------------------------------------------------------------------*/ function next() { var playlist = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; /* If the playlist is empty or null, then we check the active playlist */ if (playlist == '' || playlist == null) { /* If the active playlist is null, then we set the next global song or we set the next in the playlist. */ if (_config2.default.active_playlist == null || _config2.default.active_playlist == '') { _helpers4.default.setNext(); } else { _helpers4.default.setNextPlaylist(_config2.default.active_playlist); } } else { /* Set the next in the playlist for the key provided. */ _helpers4.default.setNextPlaylist(playlist); } } /*-------------------------------------------------------------------------- Plays the prev song either in the playlist or globally. Public Accessor: Amplitude.prev( playlist ); @param string playlist The playlist key --------------------------------------------------------------------------*/ function prev() { var playlist = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; /* If the playlist is empty or null, then we check the active playlist */ if (playlist == '' || playlist == null) { /* If the active playlist is null, then we set the prev global song or we set the prev in the playlist. */ if (_config2.default.active_playlist == null || _config2.default.active_playlist == '') { _helpers4.default.setPrev(); } else { _helpers4.default.setPrevPlaylist(_config2.default.active_playlist); } } else { /* Set the prev in the playlist for the key provided. */ _helpers4.default.setPrevPlaylist(playlist); } } /*-------------------------------------------------------------------------- Gets all of the songs in the songs array Public Accessor: Amplitude.getSongs( ); --------------------------------------------------------------------------*/ function getSongs() { return _config2.default.songs; } /*-------------------------------------------------------------------------- Gets all of the songs in a playlist Public Accessor: Amplitude.getSongsInPlaylist( playlist ); @param string playlist The playlist key --------------------------------------------------------------------------*/ function getSongsInPlaylist(playlist) { var songsArray = []; for (var i = 0; i < _config2.default.playlist[playlist].length; i++) { songsArray.push(_config2.default.songs[i]); } return songsArray; } /*-------------------------------------------------------------------------- Get current state of songs. If shuffled, this will return the shuffled songs. Public Accessor: Amplitude.getSongsState(); --------------------------------------------------------------------------*/ function getSongsState() { if (_config2.default.shuffle_on) { return _config2.default.shuffle_list; } else { return _config2.default.songs; } } /*-------------------------------------------------------------------------- Get current state of songs in playlist. If shuffled, this will return the shuffled songs. Public Accessor: Amplitude.getSongsStatePlaylist( playlist ); @param string playlist The playlist key --------------------------------------------------------------------------*/ function getSongsStatePlaylist(playlist) { var songsArray = []; if (_config2.default.shuffled_status[playlist]) { for (var i = 0; i < _config2.default.shuffled_playlists[playlist].length; i++) { songsArray.push(_config2.default.songs[i]); } } else { for (var i = 0; i < _config2.default.playlist[playlist].length; i++) { songsArray.push(_config2.default.songs[i]); } } return songsArray; } /*-------------------------------------------------------------------------- Gets the active index of the player Public Accessor: Amplitude.getActiveIndex() --------------------------------------------------------------------------*/ function getActiveIndex() { return parseInt(_config2.default.active_index); } /*-------------------------------------------------------------------------- Gets the active index with respect to the state of the player whether it is shuffled or not. Public Accessor: Amplitude.getActiveIndexState() --------------------------------------------------------------------------*/ function getActiveIndexState() { if (_config2.default.shuffle_on) { return parseInt(_config2.default.shuffle_active_index); } else { return parseInt(_config2.default.active_index); } } /*-------------------------------------------------------------------------- Get the version of AmplitudeJS Public Accessor: Amplitude.getVersion() --------------------------------------------------------------------------*/ function getVersion() { return _config2.default.version; } /*-------------------------------------------------------------------------- Get the buffered amount for the current song Public Accessor: Amplitude.getBuffered() --------------------------------------------------------------------------*/ function getBuffered() { return _config2.default.buffered; } /*-------------------------------------------------------------------------- Skip to a certain location in a selected song. Public Accessor: Amplitude.getBuffered() --------------------------------------------------------------------------*/ function skipTo(seconds, songIndex) { var playlist = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; if (playlist != null) { if (_helpers2.default.checkNewPlaylist(playlist)) { _helpers2.default.setActivePlaylist(playlist); } } seconds = parseInt(seconds); /* Changes the song to where it's being skipped and then play the song. */ _helpers2.default.changeSong(songIndex); _core2.default.play(); _visual2.default.syncMainPlayPause('playing'); if (playlist != null) { _visual2.default.syncPlaylistPlayPause(playlist, 'playing'); } _visual2.default.syncSongPlayPause(playlist, songIndex, 'playing'); /* Skip to the location in the song. */ _core2.default.skipToLocation(seconds); } /* Returns all of the publically accesible methods. */ return { init: init, bindNewElements: bindNewElements, getActivePlaylist: getActivePlaylist, getPlaybackSpeed: getPlaybackSpeed, getRepeat: getRepeat, getShuffle: getShuffle, getShufflePlaylist: getShufflePlaylist, getDefaultAlbumArt: getDefaultAlbumArt, setDefaultAlbumArt: setDefaultAlbumArt, getSongPlayedPercentage: getSongPlayedPercentage, setSongPlayedPercentage: setSongPlayedPercentage, setDebug: setDebug, getActiveSongMetadata: getActiveSongMetadata, getSongByIndex: getSongByIndex, getSongAtPlaylistIndex: getSongAtPlaylistIndex, addSong: addSong, playNow: playNow, play: play, pause: pause, audio: getAudio, next: next, prev: prev, getSongs: getSongs, getSongsInPlaylist: getSongsInPlaylist, getSongsState: getSongsState, getSongsStatePlaylist: getSongsStatePlaylist, getActiveIndex: getActiveIndex, getActiveIndexState: getActiveIndexState, getVersion: getVersion, getBuffered: getBuffered, skipTo: skipTo }; }(); /* Amplitude.js Version: 3.2.0 Author: Dan Pastori Company: 521 Dimensions */ exports.default = Amplitude; module.exports = exports['default']; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(0); var _config2 = _interopRequireDefault(_config); var _helpers = __webpack_require__(1); var _helpers2 = _interopRequireDefault(_helpers); var _init = __webpack_require__(6); var _init2 = _interopRequireDefault(_init); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* |---------------------------------------------------------------------------------------------------- | SOUNDCLOUD |---------------------------------------------------------------------------------------------------- | These helpers wrap around the basic methods of the Soundcloud API | and get the information we need from SoundCloud to make the songs | streamable through Amplitude */ var AmplitudeSoundcloud = function () { /* Defines the temp user config */ var tempUserConfig = {}; /*-------------------------------------------------------------------------- Loads the soundcloud SDK for use with Amplitude so the user doesn't have to load it themselves. With help from: http://stackoverflow.com/questions/950087/include-a-javascript-file-in-another-javascript-file --------------------------------------------------------------------------*/ function loadSoundCloud(userConfig) { tempUserConfig = userConfig; var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; /* URL to the remote soundcloud SDK */ script.src = 'https://connect.soundcloud.com/sdk.js'; script.onreadystatechange = initSoundcloud; script.onload = initSoundcloud; head.appendChild(script); } /*-------------------------------------------------------------------------- Initializes soundcloud with the key provided. --------------------------------------------------------------------------*/ function initSoundcloud() { /* Calls the SoundCloud initialize function from their API and sends it the client_id that the user passed in. */ SC.initialize({ client_id: _config2.default.soundcloud_client }); /* Gets the streamable URLs to run through Amplitue. This is VERY important since Amplitude can't stream the copy and pasted link from the SoundCloud page, but can resolve the streaming URLs from the link. */ getStreamableURLs(); } /*-------------------------------------------------------------------------- Gets the streamable URL from the URL provided for all of the soundcloud links. This will loop through and set all of the information for the soundcloud urls. --------------------------------------------------------------------------*/ function getStreamableURLs() { var soundcloud_regex = /^https?:\/\/(soundcloud.com|snd.sc)\/(.*)$/; for (var i = 0; i < _config2.default.songs.length; i++) { /* If the URL matches soundcloud, we grab that url and get the streamable link if there is one. */ if (_config2.default.songs[i].url.match(soundcloud_regex)) { _config2.default.soundcloud_song_count++; resolveStreamable(_config2.default.songs[i].url, i); } } } /*-------------------------------------------------------------------------- Due to Soundcloud SDK being asynchronous, we need to scope the index of the song in another function. The privateGetSoundcloudStreamableURLs function does the actual iteration and scoping. --------------------------------------------------------------------------*/ function resolveStreamable(url, index) { SC.get('/resolve/?url=' + url, function (sound) { /* If streamable we get the url and bind the client ID to the end so Amplitude can just stream the song normally. We then overwrite the url the user provided with the streamable URL. */ if (sound.streamable) { _config2.default.songs[index].url = sound.stream_url + '?client_id=' + _config2.default.soundcloud_client; /* If the user want's to use soundcloud art, we overwrite the cover_art_url with the soundcloud artwork url. */ if (_config2.default.soundcloud_use_art) { _config2.default.songs[index].cover_art_url = sound.artwork_url; } /* Grab the extra metadata from soundcloud and bind it to the song. The user can get this through the public function: getActiveSongMetadata */ _config2.default.songs[index].soundcloud_data = sound; } else { /* If not streamable, then we print a message to the user stating that the song with name X and artist X is not streamable. This gets printed ONLY if they have debug turned on. */ _helpers2.default.writeDebugMessage(_config2.default.songs[index].name + ' by ' + _config2.default.songs[index].artist + ' is not streamable by the Soundcloud API'); } /* Increments the song ready counter. */ _config2.default.soundcloud_songs_ready++; /* When all songs are accounted for, then amplitude is ready to rock and we set the rest of the config. */ if (_config2.default.soundcloud_songs_ready == _config2.default.soundcloud_song_count) { _init2.default.setConfig(tempUserConfig); } }); } /* Returns the publically accessible methods */ return { loadSoundCloud: loadSoundCloud }; }(); exports.default = AmplitudeSoundcloud; module.exports = exports['default']; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _config = __webpack_require__(0); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /* |------------------------------------------------------------------------------- | VISUAL SYNC HELPER METHODS |------------------------------------------------------------------------------- | These methods help sync visual displays. They essentially make the visual sync | methods smaller and more maintainable. | | METHODS | syncCurrentHours( hours ) | resetCurrentHours() | syncCurrentMinutes( minutes ) | resetCurrentMinutes() | syncCurrentSeconds( seconds ) | resetCurrentSeconds() | syncCurrentTime( currentTime ) | syncCurrentHours( hours ) | syncCurrentMinutes( minutes ) | syncCurrentSeconds( seconds ) | syncCurrentTime( time ) | resetCurrentTime() | setElementPlay( element ) | setElementPause( element ) */ var AmplitudeVisualSyncHelpers = function () { /*-------------------------------------------------------------------------- Updates any elements that display the current hour for the song. @param int hours An integer conaining how many hours into the song. --------------------------------------------------------------------------*/ function syncCurrentHours(hours) { /* Gets all of the song hour selectors. */ if (_config2.default.active_playlist != null && _config2.default.active_playlist != '') { var hourSelectors = ['.amplitude-current-hours[amplitude-main-current-hours="true"]', '.amplitude-current-hours[amplitude-playlist-current-hours="true"][amplitude-playlist="' + _config2.default.active_playlist + '"]', '.amplitude-current-hours[amplitude-song-index="' + _config2.default.active_index + '"]']; } else { var hourSelectors = ['.amplitude-current-hours[amplitude-main-current-hours="true"]', '.amplitude-current-hours[amplitude-song-index="' + _config2.default.active_index + '"]']; } /* Ensures that there are some hour selectors. */ if (document.querySelectorAll(hourSelectors.join()).length > 0) { /* Get all of the hour selectors */ var currentHourSelectors = document.querySelectorAll(hourSelectors.join()); /* Set the current hour selector's inner html to hours passed in. */ for (var i = 0; i < currentHourSelectors.length; i++) { /* If the selector is a main selector, we set the hours. */ if (currentHourSelectors[i].getAttribute('amplitude-main-current-hours') == 'true') { currentHourSelectors[i].innerHTML = hours; } else { /* If the active playlist is not null or empty and the attribute of the playlist is equal to the active playlist, then we set the inner html. */ if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null && currentHourSelectors[i].getAttribute('amplitude-playlist') == _config2.default.active_playlist) { currentHourSelectors[i].innerHTML = hours; /* If the active playlist is not set and the selector does not have a playlist then we set the hours. This means that the current selector is an individual song selector. */ } else if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null && !currentHourSelectors[i].hasAttribute('amplitude-playlist')) { currentHourSelectors[i].innerHTML = hours; /* If nothing else matches, set the selector's inner HTML to '00' */ } else { currentHourSelectors[i].innerHTML = '00'; } } } } } /*-------------------------------------------------------------------------- Resets the current hours displays to 00 --------------------------------------------------------------------------*/ function resetCurrentHours() { /* Gets the hour display elements */ var hourSelectors = document.querySelectorAll('.amplitude-current-hours'); /* Iterates over all of the hour selectors and sets the inner HTML to 00. */ for (var i = 0; i < hourSelectors.length; i++) { hourSelectors[i].innerHTML = '00'; } } /*-------------------------------------------------------------------------- Updates any elements that display the current minutes for the song. @param int minutes An integer conaining how many minutes into the song. --------------------------------------------------------------------------*/ function syncCurrentMinutes(minutes) { /* Gets all of the song minute selectors. */ if (_config2.default.active_playlist != null && _config2.default.active_playlist != '') { var minuteSelectors = ['.amplitude-current-minutes[amplitude-main-current-minutes="true"]', '.amplitude-current-minutes[amplitude-playlist-current-minutes="true"][amplitude-playlist="' + _config2.default.active_playlist + '"]', '.amplitude-current-minutes[amplitude-song-index="' + _config2.default.active_index + '"]']; } else { var minuteSelectors = ['.amplitude-current-minutes[amplitude-main-current-minutes="true"]', '.amplitude-current-minutes[amplitude-song-index="' + _config2.default.active_index + '"]']; } var currentMinuteSelectors = document.querySelectorAll(minuteSelectors.join()); /* Set the current minute selector's inner html to minutes passed in. */ for (var i = 0, l = currentMinuteSelectors.length; i < l; i++) { /* If the selector is a main selector, we set the seconds. */ if (currentMinuteSelectors[i].getAttribute('amplitude-main-current-minutes') == 'true') { currentMinuteSelectors[i].innerHTML = minutes; } else { /* If the active playlist is not null or empty and the attribute of the playlist is equal to the active playlist, then we set the inner html. */ if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null && currentMinuteSelectors[i].getAttribute('amplitude-playlist') == _config2.default.active_playlist) { currentMinuteSelectors[i].innerHTML = minutes; /* If the active playlist is not set and the selector does not have a playlist then we set the minutes. This means that the current selector is an individual song selector. */ } else if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null && !currentMinuteSelectors[i].hasAttribute('amplitude-playlist')) { currentMinuteSelectors[i].innerHTML = minutes; /* If nothing else matches, set the selector's inner HTML to '00' */ } else { currentMinuteSelectors[i].innerHTML = '00'; } } } } /*-------------------------------------------------------------------------- Resets the current minutes displays to 00 --------------------------------------------------------------------------*/ function resetCurrentMinutes() { /* Gets the minutes display elements */ var minuteSelectors = document.querySelectorAll('.amplitude-current-minutes'); /* Iterates over all of the minute selectors and sets the inner HTML to 00. */ for (var i = 0; i < minuteSelectors.length; i++) { minuteSelectors[i].innerHTML = '00'; } } /*-------------------------------------------------------------------------- Updates any elements that display the current seconds for the song. @param int minutes An integer conaining how many seconds into the song. --------------------------------------------------------------------------*/ function syncCurrentSeconds(seconds) { /* Gets all of the song second selectors. If the active playlist is not null, then we get the playlist selectors. */ if (_config2.default.active_playlist != null && _config2.default.active_playlist != '') { var secondSelectors = ['.amplitude-current-seconds[amplitude-main-current-seconds="true"]', '.amplitude-current-seconds[amplitude-playlist-current-seconds="true"][amplitude-playlist="' + _config2.default.active_playlist + '"]', '.amplitude-current-seconds[amplitude-song-index="' + _config2.default.active_index + '"]']; } else { var secondSelectors = ['.amplitude-current-seconds[amplitude-main-current-seconds="true"]', '.amplitude-current-seconds[amplitude-song-index="' + _config2.default.active_index + '"]']; } /* Get all of the second selectors */ var currentSecondSelectors = document.querySelectorAll(secondSelectors.join()); /* Iterate over all of the second selectors. */ for (var i = 0, l = currentSecondSelectors.length; i < l; i++) { /* If the selector is a main selector, we set the seconds. */ if (currentSecondSelectors[i].getAttribute('amplitude-main-current-seconds') == 'true') { currentSecondSelectors[i].innerHTML = seconds; } else { /* If the active playlist is not null or empty and the attribute of the playlist is equal to the active playlist, then we set the inner html. */ if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null && currentSecondSelectors[i].getAttribute('amplitude-playlist') == _config2.default.active_playlist) { currentSecondSelectors[i].innerHTML = seconds; /* If the active playlist is not set and the selector does not have a playlist then we set the seconds. This means that the current selector is an individual song selector. */ } else if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null && !currentSecondSelectors[i].hasAttribute('amplitude-playlist')) { currentSecondSelectors[i].innerHTML = seconds; /* If nothing else matches, set the selector's inner HTML to '00' */ } else { currentSecondSelectors[i].innerHTML = '00'; } } } } /*-------------------------------------------------------------------------- Resets the current seconds displays to 00 --------------------------------------------------------------------------*/ function resetCurrentSeconds() { /* Gets the seconds display elements */ var secondSelectors = document.querySelectorAll('.amplitude-current-seconds'); /* Iterates over all of the seconds selectors and sets the inner HTML to 00. */ for (var i = 0; i < secondSelectors.length; i++) { secondSelectors[i].innerHTML = '00'; } } /*-------------------------------------------------------------------------- Updates any elements that display the current time for the song. This is a computed field that will be commonly used. @param JSON currentTime A json object conaining the parts for the current time for the song. --------------------------------------------------------------------------*/ function syncCurrentTime(currentTime) { /* Gets all of the song time selectors. */ var timeSelectors = ['.amplitude-current-time[amplitude-main-current-time="true"]', '.amplitude-current-time[amplitude-playlist-main-current-time="' + _config2.default.active_playlist + '"]', '.amplitude-current-time[amplitude-song-index="' + _config2.default.active_index + '"]']; /* Get all of the time selectors. */ var currentTimeSelectors = document.querySelectorAll(timeSelectors.join()); /* Set the time selector's inner html to the current time for the song. The current time is computed by joining minutes and seconds. */ for (var i = 0, l = currentTimeSelectors.length; i < l; i++) { currentTimeSelectors[i].innerHTML = currentTime.minutes + ':' + currentTime.seconds; } } /*-------------------------------------------------------------------------- Resets the current time displays to 00:00 --------------------------------------------------------------------------*/ function resetCurrentTime() { /* Gets the time selector display elements */ var timeSelectors = document.querySelectorAll('.amplitude-current-time'); /* Iterates over all of the time selectors and sets the inner HTML to 00. */ for (var i = 0; i < timeSelectors.length; i++) { timeSelectors[i].innerHTML = '00:00'; } } /*-------------------------------------------------------------------------- Syncs the song played progress bars. These are HTML5 progress elements. --------------------------------------------------------------------------*/ function syncSongPlayedProgressBar(songPlayedPercentage) { syncMainSongPlayedProgressBars(songPlayedPercentage); syncPlaylistSongPlayedProgressBars(songPlayedPercentage); syncIndividualSongPlayedProgressBars(songPlayedPercentage); } /*-------------------------------------------------------------------------- Sync how much has been played with a progress bar. This is the main progress bar. @param float songPlayedPercentage The percent of the song completed. --------------------------------------------------------------------------*/ function syncMainSongPlayedProgressBars(songPlayedPercentage) { /* Ensure that the song completion percentage is a number */ if (!isNaN(songPlayedPercentage)) { /* Get all of the song progress bars */ var songPlayedProgressBars = document.querySelectorAll('.amplitude-song-played-progress[amplitude-main-song-played-progress="true"]'); for (var i = 0; i < songPlayedProgressBars.length; i++) { var max = songPlayedProgressBars[i].max; songPlayedProgressBars[i].value = songPlayedPercentage / 100 * max; } } } /*-------------------------------------------------------------------------- Sync how much has been played with a progress bar. This is the playlist progress bar. @param float songPlayedPercentage The percent of the song completed. --------------------------------------------------------------------------*/ function syncPlaylistSongPlayedProgressBars(songPlayedPercentage) { /* Ensure that the song completion percentage is a number */ if (!isNaN(songPlayedPercentage)) { /* Get all of the song progress bars */ var songPlayedProgressBars = document.querySelectorAll('.amplitude-song-played-progress[amplitude-playlist-song-played-progress="true"][amplitude-playlist="' + _config2.default.active_playlist + '"]'); for (var i = 0; i < songPlayedProgressBars.length; i++) { var max = songPlayedProgressBars[i].max; songPlayedProgressBars[i].value = songPlayedPercentage / 100 * max; } } } /*-------------------------------------------------------------------------- Sync how much has been played with a progress bar. This is for an individual song. @param float songPlayedPercentage The percent of the song completed. --------------------------------------------------------------------------*/ function syncIndividualSongPlayedProgressBars(songPlayedPercentage) { /* Ensure that the song completion percentage is a number */ if (!isNaN(songPlayedPercentage)) { /* If the active playlist is not null, we get the individual song played progress for the playlist. */ if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null) { /* Get all of the song progress bars */ var songPlayedProgressBars = document.querySelectorAll('.amplitude-song-played-progress[amplitude-playlist="' + _config2.default.active_playlist + '"][amplitude-song-index="' + _config2.default.active_index + '"]'); for (var i = 0; i < songPlayedProgressBars.length; i++) { var max = songPlayedProgressBars[i].max; songPlayedProgressBars[i].value = songPlayedPercentage / 100 * max; } } else { /* Get all of the song progress bars */ var songPlayedProgressBars = document.querySelectorAll('.amplitude-song-played-progress[amplitude-song-index="' + _config2.default.active_index + '"]'); for (var i = 0; i < songPlayedProgressBars.length; i++) { var max = songPlayedProgressBars[i].max; songPlayedProgressBars[i].value = songPlayedPercentage / 100 * max; } } } } /*-------------------------------------------------------------------------- Sets an element to be playing by removing the 'amplitude-paused' class and adding the 'amplitude-playing' class @param element element The element getting the playing class added. --------------------------------------------------------------------------*/ function setElementPlay(element) { element.classList.add('amplitude-playing'); element.classList.remove('amplitude-paused'); } /*-------------------------------------------------------------------------- Sets an element to be paused by adding the 'amplitude-paused' class and removing the 'amplitude-playing' class @param element element The element getting the paused class added. --------------------------------------------------------------------------*/ function setElementPause(element) { element.classList.remove('amplitude-playing'); element.classList.add('amplitude-paused'); } /*-------------------------------------------------------------------------- Updates any elements that display the duration hour for the song. @param int hours An integer conaining how many hours are in the song --------------------------------------------------------------------------*/ function syncDurationHours(hours) { /* Gets all of the song hour selectors. */ if (_config2.default.active_playlist != null && _config2.default.active_playlist != '') { var hourSelectors = ['.amplitude-duration-hours[amplitude-main-duration-hours="true"]', '.amplitude-duration-hours[amplitude-playlist-duration-hours="true"][amplitude-playlist="' + _config2.default.active_playlist + '"]', '.amplitude-duration-hours[amplitude-song-index="' + _config2.default.active_index + '"]']; } else { var hourSelectors = ['.amplitude-duration-hours[amplitude-main-duration-hours="true"]', '.amplitude-duration-hours[amplitude-song-index="' + _config2.default.active_index + '"]']; } /* Ensures that there are some hour selectors. */ if (document.querySelectorAll(hourSelectors.join()).length > 0) { /* Get all of the hour selectors */ var durationHourSelectors = document.querySelectorAll(hourSelectors.join()); /* Set the duration hour selector's inner html to hours passed in. */ for (var i = 0; i < durationHourSelectors.length; i++) { /* If the selector is a main selector, we set the hours. */ if (durationHourSelectors[i].getAttribute('amplitude-main-duration-hours') == 'true') { durationHourSelectors[i].innerHTML = hours; } else { /* If the active playlist is not null or empty and the attribute of the playlist is equal to the active playlist, then we set the inner html. */ if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null && durationHourSelectors[i].getAttribute('amplitude-playlist') == _config2.default.active_playlist) { durationHourSelectors[i].innerHTML = hours; /* If the active playlist is not set and the selector does not have a playlist then we set the hours. This means that the duration selector is an individual song selector. */ } else if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null && !durationHourSelectors[i].hasAttribute('amplitude-playlist')) { durationHourSelectors[i].innerHTML = hours; /* If nothing else matches, set the selector's inner HTML to '00' */ } else { durationHourSelectors[i].innerHTML = '00'; } } } } } /*-------------------------------------------------------------------------- Updates any elements that display the duration minutes for the song. @param int minutes An integer conaining how many minutes into the song. --------------------------------------------------------------------------*/ function syncDurationMinutes(minutes) { /* Gets all of the song minute selectors. */ if (_config2.default.active_playlist != null && _config2.default.active_playlist != '') { var minuteSelectors = ['.amplitude-duration-minutes[amplitude-main-duration-minutes="true"]', '.amplitude-duration-minutes[amplitude-playlist-duration-minutes="true"][amplitude-playlist="' + _config2.default.active_playlist + '"]', '.amplitude-duration-minutes[amplitude-song-index="' + _config2.default.active_index + '"]']; } else { var minuteSelectors = ['.amplitude-duration-minutes[amplitude-main-duration-minutes="true"]', '.amplitude-duration-minutes[amplitude-song-index="' + _config2.default.active_index + '"]']; } /* Get all of the minute selectors */ var durationMinuteSelectors = document.querySelectorAll(minuteSelectors.join()); /* Set the duration minute selector's inner html to minutes passed in. */ for (var i = 0; i < durationMinuteSelectors.length; i++) { /* If the selector is a main selector, we set the seconds. */ if (durationMinuteSelectors[i].getAttribute('amplitude-main-duration-minutes') == 'true') { durationMinuteSelectors[i].innerHTML = minutes; } else { /* If the active playlist is not null or empty and the attribute of the playlist is equal to the active playlist, then we set the inner html. */ if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null && durationMinuteSelectors[i].getAttribute('amplitude-playlist') == _config2.default.active_playlist) { durationMinuteSelectors[i].innerHTML = minutes; /* If the active playlist is not set and the selector does not have a playlist then we set the minutes. This means that the duration selector is an individual song selector. */ } else if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null && !durationMinuteSelectors[i].hasAttribute('amplitude-playlist')) { durationMinuteSelectors[i].innerHTML = minutes; /* If nothing else matches, set the selector's inner HTML to '00' */ } else { durationMinuteSelectors[i].innerHTML = '00'; } } } } /*-------------------------------------------------------------------------- Updates any elements that display the duration seconds for the song. @param int minutes An integer conaining how many seconds into the song. --------------------------------------------------------------------------*/ function syncDurationSeconds(seconds) { /* Gets all of the song second selectors. If the active playlist is not null, then we get the playlist selectors. */ if (_config2.default.active_playlist != null && _config2.default.active_playlist != '') { var secondSelectors = ['.amplitude-duration-seconds[amplitude-main-duration-seconds="true"]', '.amplitude-duration-seconds[amplitude-playlist-duration-seconds="true"][amplitude-playlist="' + _config2.default.active_playlist + '"]', '.amplitude-duration-seconds[amplitude-song-index="' + _config2.default.active_index + '"]']; } else { var secondSelectors = ['.amplitude-duration-seconds[amplitude-main-duration-seconds="true"]', '.amplitude-duration-seconds[amplitude-song-index="' + _config2.default.active_index + '"]']; } /* Get all of the second selectors */ var durationSecondSelectors = document.querySelectorAll(secondSelectors.join()); /* Iterate over all of the second selectors. */ for (var i = 0; i < durationSecondSelectors.length; i++) { /* If the selector is a main selector, we set the seconds. */ if (durationSecondSelectors[i].getAttribute('amplitude-main-duration-seconds') == 'true') { durationSecondSelectors[i].innerHTML = seconds; } else { /* If the active playlist is not null or empty and the attribute of the playlist is equal to the active playlist, then we set the inner html. */ if (_config2.default.active_playlist != '' && _config2.default.active_playlist != null && durationSecondSelectors[i].getAttribute('amplitude-playlist') == _config2.default.active_playlist) { durationSecondSelectors[i].innerHTML = seconds; /* If the active playlist is not set and the selector does not have a playlist then we set the seconds. This means that the duration selector is an individual song selector. */ } else if (_config2.default.active_playlist == '' || _config2.default.active_playlist == null && !durationSecondSelectors[i].hasAttribute('amplitude-playlist')) { durationSecondSelectors[i].innerHTML = seconds; /* If nothing else matches, set the selector's inner HTML to '00' */ } else { durationSecondSelectors[i].innerHTML = '00'; } } } } /*-------------------------------------------------------------------------- Updates any elements that display the duration time for the song. This is a computed field that will be commonly used. @param JSON durationTime A json object conaining the parts for the duration time for the song. --------------------------------------------------------------------------*/ function syncDurationTime(durationTime) { /* Gets all of the song time selectors. */ var timeSelectors = ['.amplitude-duration-time[amplitude-main-duration-time="true"]', '.amplitude-duration-time[amplitude-playlist-main-duration-time="' + _config2.default.active_playlist + '"]', '.amplitude-duration-time[amplitude-song-index="' + _config2.default.active_index + '"]']; /* Get all of the time selectors. */ var durationTimeSelectors = document.querySelectorAll(timeSelectors.join()); /* Set the time selector's inner html to the duration time for the song. The duration time is computed by joining minutes and seconds. */ for (var i = 0; i < durationTimeSelectors.length; i++) { if (!isNaN(durationTime.minutes) && !isNaN(durationTime.seconds)) { durationTimeSelectors[i].innerHTML = durationTime.minutes + ':' + durationTime.seconds; } else { durationTimeSelectors[i].innerHTML = '00:00'; } } } /*-------------------------------------------------------------------------- Updates the elements that show how much time is remaining in the song. @param JSON currentTime A json object containing the parts for the current time for the song. @param JSON durationTime A json object conaining the parts for the duration time for the song. --------------------------------------------------------------------------*/ function syncCountDownTime(currentTime, songDuration) { /* Initialize time remaining. */ var timeRemaining = '00:00'; /* Ensure that all values are defined. */ if (currentTime != undefined && songDuration != undefined) { /* Initialize the total current seconds and total duration seconds */ var totalCurrentSeconds = parseInt(currentTime.seconds) + parseInt(currentTime.minutes) * 60 + parseInt(currentTime.hours) * 60 * 60; var totalDurationSeconds = parseInt(songDuration.seconds) + parseInt(songDuration.minutes) * 60 + parseInt(songDuration.hours) * 60 * 60; /* If the two variables are numbers we continue the computing. */ if (!isNaN(totalCurrentSeconds) && !isNaN(totalDurationSeconds)) { /* Find the total remaining seconds. */ var timeRemainingTotalSeconds = totalDurationSeconds - totalCurrentSeconds; /* Find how many seconds are remaining. */ var timeRemainingSeconds = (Math.floor(timeRemainingTotalSeconds % 60) < 10 ? '0' : '') + Math.floor(timeRemainingTotalSeconds % 60); /* Find how many minutes are remaining. */ var timeRemainingMinutes = (Math.floor(timeRemainingTotalSeconds / 60) < 10 ? '0' : '') + Math.floor(timeRemainingTotalSeconds / 60); /* Build the time remaining. */ timeRemaining = timeRemainingMinutes + ':' + timeRemainingSeconds; } } /* Gets all of the song time selectors. */ var timeSelectors = ['.amplitude-time-remaining[amplitude-main-time-remaining="true"]', '.amplitude-time-remaining[amplitude-playlist-main-time-remaining="' + _config2.default.active_playlist + '"]', '.amplitude-time-remaining[amplitude-song-index="' + _config2.default.active_index + '"]']; /* Get all of the time selectors. */ var timeRemainingSelectors = document.querySelectorAll(timeSelectors.join()); /* Set the time selector's inner html to the duration time for the song. The duration time is computed by joining minutes and seconds. */ for (var i = 0; i < timeRemainingSelectors.length; i++) { timeRemainingSelectors[i].innerHTML = timeRemaining; } } /* Return the publically available functions. */ return { syncCurrentHours: syncCurrentHours, syncCurrentMinutes: syncCurrentMinutes, syncCurrentSeconds: syncCurrentSeconds, syncCurrentTime: syncCurrentTime, resetCurrentHours: resetCurrentHours, resetCurrentMinutes: resetCurrentMinutes, resetCurrentSeconds: resetCurrentSeconds, resetCurrentTime: resetCurrentTime, syncSongPlayedProgressBar: syncSongPlayedProgressBar, setElementPlay: setElementPlay, setElementPause: setElementPause, syncDurationHours: syncDurationHours, syncDurationMinutes: syncDurationMinutes, syncDurationSeconds: syncDurationSeconds, syncDurationTime: syncDurationTime, syncCountDownTime: syncCountDownTime }; }(); exports.default = AmplitudeVisualSyncHelpers; module.exports = exports['default']; /***/ }) /******/ ]); });
packages/strapi-plugin-content-manager/admin/src/containers/Edit/index.js
lucusteen/strap
/* * * Edit * */ import React from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import _ from 'lodash'; import { router } from 'app'; import { define } from 'i18n'; import Container from 'components/Container'; import EditForm from 'components/EditForm'; import { makeSelectSchema } from 'containers/App/selectors'; import EditFormRelations from 'components/EditFormRelations'; import { setInitialState, setCurrentModelName, setIsCreating, loadRecord, setRecordAttribute, editRecord, deleteRecord, } from './actions'; import { makeSelectRecord, makeSelectLoading, makeSelectCurrentModelName, makeSelectEditing, makeSelectDeleting, makeSelectIsCreating, } from './selectors'; import messages from './messages.json'; define(messages); export class Edit extends React.Component { componentWillMount() { this.props.setInitialState(); this.props.setCurrentModelName(this.props.routeParams.slug.toLowerCase()); // Detect that the current route is the `create` route or not if (this.props.routeParams.id === 'create') { this.props.setIsCreating(); } else { this.props.loadRecord(this.props.routeParams.id); } } render() { const PluginHeader = this.props.exposedComponents.PluginHeader; let content = <p>Loading...</p>; let relations; if (!this.props.loading && this.props.schema && this.props.currentModelName) { content = ( <EditForm record={this.props.record} currentModelName={this.props.currentModelName} schema={this.props.schema} setRecordAttribute={this.props.setRecordAttribute} editRecord={this.props.editRecord} editing={this.props.editing} /> ); relations = ( <EditFormRelations currentModelName={this.props.currentModelName} record={this.props.record} schema={this.props.schema} setRecordAttribute={this.props.setRecordAttribute} /> ); } // Define plugin header actions const pluginHeaderActions = [ { label: messages.cancel, class: 'btn-default', onClick: () => { router.push(`/plugins/content-manager/${this.props.currentModelName}`); }, }, { label: this.props.editing ? messages.editing : messages.submit, class: 'btn-primary', onClick: this.props.editRecord, disabled: this.props.editing, }, ]; // Add the `Delete` button only in edit mode if (!this.props.isCreating) { pluginHeaderActions.push({ label: messages.delete, class: 'btn-danger', onClick: this.props.deleteRecord, disabled: this.props.deleting, }); } // Plugin header config const pluginHeaderTitle = _.get(this.props.schema, [this.props.currentModelName, 'label']) || 'Content Manager'; const pluginHeaderDescription = this.props.isCreating ? 'New entry' : `#${this.props.record && this.props.record.get('id')}`; return ( <div className="col-md-12"> <div className="container-fluid"> <PluginHeader title={{ id: 'plugin-content-manager-title', defaultMessage: `${pluginHeaderTitle}`, }} description={{ id: 'plugin-content-manager-description', defaultMessage: `${pluginHeaderDescription}`, }} actions={pluginHeaderActions} /> <Container> <div className="row"> <div className="col-md-8"> {content} {relations} </div> </div> </Container> </div> </div> ); } } Edit.propTypes = { currentModelName: React.PropTypes.oneOfType([ React.PropTypes.bool, React.PropTypes.string, ]), deleteRecord: React.PropTypes.func.isRequired, deleting: React.PropTypes.bool.isRequired, editing: React.PropTypes.bool.isRequired, editRecord: React.PropTypes.func.isRequired, exposedComponents: React.PropTypes.object.isRequired, isCreating: React.PropTypes.bool.isRequired, loading: React.PropTypes.bool.isRequired, loadRecord: React.PropTypes.func.isRequired, record: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.bool, ]), routeParams: React.PropTypes.object.isRequired, schema: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.bool, ]), setCurrentModelName: React.PropTypes.func.isRequired, setInitialState: React.PropTypes.func.isRequired, setIsCreating: React.PropTypes.func.isRequired, setRecordAttribute: React.PropTypes.func.isRequired, }; const mapStateToProps = createStructuredSelector({ record: makeSelectRecord(), loading: makeSelectLoading(), currentModelName: makeSelectCurrentModelName(), editing: makeSelectEditing(), deleting: makeSelectDeleting(), isCreating: makeSelectIsCreating(), schema: makeSelectSchema(), }); function mapDispatchToProps(dispatch) { return { setInitialState: () => dispatch(setInitialState()), setCurrentModelName: currentModelName => dispatch(setCurrentModelName(currentModelName)), setIsCreating: () => dispatch(setIsCreating()), loadRecord: id => dispatch(loadRecord(id)), setRecordAttribute: (key, value) => dispatch(setRecordAttribute(key, value)), editRecord: () => dispatch(editRecord()), deleteRecord: () => { // TODO: improve confirmation UX. if (window.confirm('Are you sure ?')) { // eslint-disable-line no-alert dispatch(deleteRecord()); } }, dispatch, }; } export default connect(mapStateToProps, mapDispatchToProps)(Edit);
webpack/scenes/Subscriptions/Details/SubscriptionDetailInfo.js
pmoravec/katello
import React from 'react'; import PropTypes from 'prop-types'; import { Table } from 'react-bootstrap'; import { translate as __ } from 'foremanReact/common/I18n'; import subscriptionAttributes from './SubscriptionAttributes'; import subscriptionPurposeAttributes from './SubscriptionPurposeAttributes'; const SubscriptionDetailInfo = ({ subscriptionDetails }) => { const subscriptionLimits = (subDetails) => { const limits = []; if (subDetails.sockets) { limits.push(__('Sockets: %s').replace('%s', subDetails.sockets)); } if (subDetails.cores) { limits.push(__('Cores: %s').replace('%s', subDetails.cores)); } if (subDetails.ram) { limits.push(__('RAM: %s GB').replace('%s', subDetails.ram)); } if (limits.length > 0) { return limits.join(', '); } return ''; }; const subscriptionDetailValue = (subDetails, key) => (subDetails[key] == null ? '' : String(subDetails[key])); const formatInstanceBased = (subDetails) => { if (subDetails.instance_multiplier == null || subDetails.instance_multiplier === '' || subDetails.instance_multiplier === 0) { return __('No'); } return __('Yes'); }; return ( <div> <h2>{__('Subscription Info')}</h2> <Table> <tbody> {Object.keys(subscriptionAttributes).map(key => ( <tr key={key}> <td><b>{__(subscriptionAttributes[key])}</b></td> <td>{subscriptionDetailValue(subscriptionDetails, key)}</td> </tr> ))} <tr> <td><b>{__('Limits')}</b></td> <td>{subscriptionLimits(subscriptionDetails)}</td> </tr> <tr> <td><b>{__('Instance-based')}</b></td> <td>{formatInstanceBased(subscriptionDetails)}</td> </tr> </tbody> </Table> <h2>{__('System Purpose')}</h2> <Table> <tbody> {Object.keys(subscriptionPurposeAttributes).map(key => ( <tr key={key}> <td><b>{__(subscriptionPurposeAttributes[key])}</b></td> <td>{subscriptionDetailValue(subscriptionDetails, key)}</td> </tr> ))} </tbody> </Table> </div> ); }; SubscriptionDetailInfo.propTypes = { subscriptionDetails: PropTypes.shape({}).isRequired, }; export default SubscriptionDetailInfo;
src/Modal.js
dragogonone/ws_react
import React from 'react'; import SkyLight from 'react-skylight'; import styles from './Modal.css' export default class Modal extends React.Component { constructor(props){ super(props); } // componentDidMount(){ // showModal(); // } showModal(){ this.refs.simpleDialog.show() } render() { let contents = this.props.contents; return ( <div> <section> <button onClick={this.showModal.bind(this)}>{contents.title}</button> </section> <SkyLight dialogStyles={styles.myDialogStyles} hideOnOverlayClicked ref="simpleDialog"> <div className={styles.base}> <div className={styles.title}>{contents.title}</div> <div className={styles.main_img}><img src={contents.main_img} alt="メイン画像"/></div> <div className={styles.description}>{contents.description}</div> <div className={styles.company}> <img className={styles.logo} src={contents.logo} alt="企業ロゴ"/> <span className={styles.companyName}>{contents.companyName}</span> </div> </div> </SkyLight> </div> ) } } Modal.displayName = 'Modal';
app/js/bundle.min.js
React-Team-AM/react-template
!function e(t,r,a){function n(s,o){if(!r[s]){if(!t[s]){var c="function"==typeof require&&require;if(!o&&c)return c(s,!0);if(i)return i(s,!0);var l=new Error("Cannot find module '"+s+"'");throw l.code="MODULE_NOT_FOUND",l}var m=r[s]={exports:{}};t[s][0].call(m.exports,function(e){var r=t[s][1][e];return n(r?r:e)},m,m.exports,e,t,r,a)}return r[s].exports}for(var i="function"==typeof require&&require,s=0;s<a.length;s++)n(a[s]);return n}({1:[function(e,t,r){"use strict";var a=e("react"),n=e("react-addons-css-transition-group"),i=e("./NBItems").NBButton,s=e("./NBItems").NBTitle,o=e("./NBItems").NBEmpty,c=e("react-router"),l=c.Link,m=a.createClass({displayName:"Navbar",render:function(){return a.createElement("div",{className:"navbar"},a.createElement("div",{className:"navbar-inner"},a.createElement(o,{position:"left"}),a.createElement(s,{text:"Breath Cycle"}),a.createElement(i,{path:"/settings",icon:"icon-bars",position:"right"})))}}),p=a.createClass({displayName:"Button",propTypes:{path:a.PropTypes.string.isRequired,icon:a.PropTypes.string.isRequired},render:function(){var e=this.props.path,t=this.props.icon,r=this.props.text;return a.createElement("div",{className:"menu-item"},a.createElement(l,{className:"link button-fill",to:e},a.createElement("i",{className:"icon "+t}),a.createElement("span",null,r)))}}),u=a.createClass({displayName:"PageContent",componentWillMount:function(){},render:function(){return a.createElement("div",{className:"page"},a.createElement("div",{className:"page-content"},a.createElement(m,null),a.createElement(n,{transitionName:{appear:"slideLeft-enter",leave:"slideLeft-leave"},transitionEnterTimeout:1e3,transitionLeaveTimeout:500,transitionAppearTimeout:500,transitionAppear:!0,transitionLeave:!0},a.createElement("div",{className:"content-block"},a.createElement("div",{className:"list-block media-list"},a.createElement("div",{className:"buttons-menu"},a.createElement("div",{className:"title-wrapper"},a.createElement("span",{className:"titleP1"},"CrossFit "),a.createElement("span",{className:"titleP2"},"Trainer")),a.createElement(p,{path:"/TimerPage",icon:"icon-timer",text:"Таймер"}),a.createElement(p,{path:"/TimerPage",icon:"icon-timer",text:"Начать тренировку"}),a.createElement(p,{path:"/TimerPage",icon:"icon-timer",text:"Упражнения"})))))))}});t.exports=u},{"./NBItems":2,react:"react","react-addons-css-transition-group":"react-addons-css-transition-group","react-router":"react-router"}],2:[function(e,t,r){"use strict";var a=e("react"),n=e("react-router"),i=n.Link,s=a.createClass({displayName:"NBButton",propTypes:{position:a.PropTypes.string.isRequired,icon:a.PropTypes.string.isRequired,path:a.PropTypes.string.isRequired},render:function(){var e=this.props.position,t=this.props.icon,r=this.props.path;return a.createElement("div",{className:e},a.createElement(i,{className:"icon icon-only",to:r},a.createElement("i",{className:"icon "+t})))}}),o=a.createClass({displayName:"NBTitle",propTypes:{text:a.PropTypes.string.isRequired},render:function(){var e=this.props.text;return a.createElement("div",{className:"center"},e)}}),c=a.createClass({displayName:"NBEmpty",propTypes:{position:a.PropTypes.string.isRequired},render:function(){var e=this.props.position;return a.createElement("div",{className:e},a.createElement("a",{className:"icon icon-only"},a.createElement("i",{className:"icon "})))}});t.exports={NBButton:s,NBTitle:o,NBEmpty:c}},{react:"react","react-router":"react-router"}],3:[function(e,t,r){"use strict";var a=e("react"),n=e("react-addons-css-transition-group"),i=e("./NBItems").NBButton,s=e("./NBItems").NBTitle,o=e("./NBItems").NBEmpty,c=a.createClass({displayName:"Navbar",render:function(){return a.createElement("div",{className:"navbar"},a.createElement("div",{className:"navbar-inner"},a.createElement(i,{path:"/",icon:"icon-back",position:"left"}),a.createElement(s,{text:"Settings"}),a.createElement(o,{position:"right"})))}}),l=(a.createClass({displayName:"Button",render:function(){return a.createElement("div",null)}}),a.createClass({displayName:"PageContent",componentWillMount:function(){},render:function(){return a.createElement("div",{className:"page"},a.createElement("div",{className:"page-content"},a.createElement(c,null),a.createElement(n,{transitionName:{appear:"slideLeft-enter",leave:"slideLeft-leave"},transitionEnterTimeout:1e3,transitionLeaveTimeout:500,transitionAppearTimeout:500,transitionAppear:!0,transitionLeave:!0},a.createElement("div",{className:"content-block"},"Content some text alalala ashdihaish uasodj iioash iodhias"))))}}));t.exports=l},{"./NBItems":2,react:"react","react-addons-css-transition-group":"react-addons-css-transition-group"}],4:[function(e,t,r){"use strict";var a=e("react"),n=e("react-dom"),i=e("react-router").Router,s=e("react-router").Route,o=e("react-router").hashHistory,c=e("./MainMenu"),l=e("./TimerPage"),m=a.createClass({displayName:"App",render:function(){var e=this.props.path;return console.log(e),a.createElement(i,{hash:!0,history:o},a.createElement(s,{path:"/",component:c}),a.createElement(s,{path:"TimerPage",component:l}))}});n.render(a.createElement(m,{path:location.pathname}),document.getElementById("root"))},{"./MainMenu":1,"./TimerPage":3,react:"react","react-dom":"react-dom","react-router":"react-router"}]},{},[4]);
app/index.js
FilipStenbeck/alittlereactthing
import React from 'react'; import { render } from 'react-dom' import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import { Provider } from 'react-redux' import { Router, Route, browserHistory } from 'react-router' import PeopleContainer from './containers/peopleContainer'; import { reducer } from './reducers'; import { fetchPeople } from './actions' //Setup the store and initial state of the app let store = createStore(reducer, applyMiddleware(thunk)) store.dispatch(fetchPeople()); //Save store on windows for easy access from the dev-tool console window.store = store; render( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={PeopleContainer}/> <Route path="/people" component={PeopleContainer}/> <Route path="/people/:filter" component={PeopleContainer}/> </Router> </Provider>, document.getElementById('app') );
app/javascript/mastodon/features/ui/components/block_modal.js
ikuradon/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { injectIntl, FormattedMessage } from 'react-intl'; import { makeGetAccount } from '../../../selectors'; import Button from '../../../components/button'; import { closeModal } from '../../../actions/modal'; import { blockAccount } from '../../../actions/accounts'; import { initReport } from '../../../actions/reports'; const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = state => ({ account: getAccount(state, state.getIn(['blocks', 'new', 'account_id'])), }); return mapStateToProps; }; const mapDispatchToProps = dispatch => { return { onConfirm(account) { dispatch(blockAccount(account.get('id'))); }, onBlockAndReport(account) { dispatch(blockAccount(account.get('id'))); dispatch(initReport(account)); }, onClose() { dispatch(closeModal()); }, }; }; export default @connect(makeMapStateToProps, mapDispatchToProps) @injectIntl class BlockModal extends React.PureComponent { static propTypes = { account: PropTypes.object.isRequired, onClose: PropTypes.func.isRequired, onBlockAndReport: PropTypes.func.isRequired, onConfirm: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; componentDidMount() { this.button.focus(); } handleClick = () => { this.props.onClose(); this.props.onConfirm(this.props.account); } handleSecondary = () => { this.props.onClose(); this.props.onBlockAndReport(this.props.account); } handleCancel = () => { this.props.onClose(); } setRef = (c) => { this.button = c; } render () { const { account } = this.props; return ( <div className='modal-root__modal block-modal'> <div className='block-modal__container'> <p> <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} /> </p> </div> <div className='block-modal__action-bar'> <Button onClick={this.handleCancel} className='block-modal__cancel-button'> <FormattedMessage id='confirmation_modal.cancel' defaultMessage='Cancel' /> </Button> <Button onClick={this.handleSecondary} className='confirmation-modal__secondary-button'> <FormattedMessage id='confirmations.block.block_and_report' defaultMessage='Block & Report' /> </Button> <Button onClick={this.handleClick} ref={this.setRef}> <FormattedMessage id='confirmations.block.confirm' defaultMessage='Block' /> </Button> </div> </div> ); } }
examples/src/components/MultiSelectField.js
susielu/react-select
import React from 'react'; import Select from 'react-select'; function logChange() { console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments))); } var MultiSelectField = React.createClass({ displayName: 'MultiSelectField', propTypes: { label: React.PropTypes.string, }, getInitialState () { return { disabled: false, value: [] }; }, handleSelectChange (value, values) { logChange('New value:', value, 'Values:', values); this.setState({ value: value }); }, toggleDisabled (e) { this.setState({ 'disabled': e.target.checked }); }, render () { var ops = [ { label: 'Chocolate', value: 'chocolate' }, { label: 'Vanilla', value: 'vanilla' }, { label: 'Strawberry', value: 'strawberry' }, { label: 'Caramel', value: 'caramel' }, { label: 'Cookies and Cream', value: 'cookiescream' }, { label: 'Peppermint', value: 'peppermint' } ]; return ( <div className="section"> <h3 className="section-heading">{this.props.label}</h3> <Select multi disabled={this.state.disabled} value={this.state.value} placeholder="Select your favourite(s)" options={ops} onChange={this.handleSelectChange} /> <div className="checkbox-list"> <label className="checkbox"> <input type="checkbox" className="checkbox-control" checked={this.state.disabled} onChange={this.toggleDisabled} /> <span className="checkbox-label">Disabled</span> </label> </div> </div> ); } }); module.exports = MultiSelectField;
src/svg-icons/maps/add-location.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsAddLocation = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm4 8h-3v3h-2v-3H8V8h3V5h2v3h3v2z"/> </SvgIcon> ); MapsAddLocation = pure(MapsAddLocation); MapsAddLocation.displayName = 'MapsAddLocation'; MapsAddLocation.muiName = 'SvgIcon'; export default MapsAddLocation;
admin/client/App/screens/List/components/ListColumnsForm.js
jstockwin/keystone
import React from 'react'; import assign from 'object-assign'; import Popout from '../../../shared/Popout'; import PopoutList from '../../../shared/Popout/PopoutList'; import { FormField, FormInput } from 'elemental'; import ListHeaderButton from './ListHeaderButton'; import { setActiveColumns } from '../actions'; var ListColumnsForm = React.createClass({ displayName: 'ListColumnsForm', getInitialState () { return { selectedColumns: {}, searchString: '', }; }, getSelectedColumnsFromStore () { var selectedColumns = {}; this.props.activeColumns.forEach(col => { selectedColumns[col.path] = true; }); return selectedColumns; }, togglePopout (visible) { this.setState({ selectedColumns: this.getSelectedColumnsFromStore(), isOpen: visible, searchString: '', }); }, toggleColumn (path, value) { const newColumns = assign({}, this.state.selectedColumns); if (value) { newColumns[path] = value; } else { delete newColumns[path]; } this.setState({ selectedColumns: newColumns, }); }, applyColumns () { this.props.dispatch(setActiveColumns(Object.keys(this.state.selectedColumns))); this.togglePopout(false); }, updateSearch (e) { this.setState({ searchString: e.target.value }); }, renderColumns () { const availableColumns = this.props.availableColumns; const { searchString } = this.state; let filteredColumns = availableColumns; if (searchString) { filteredColumns = filteredColumns .filter(column => column.type !== 'heading') .filter(column => new RegExp(searchString).test(column.field.label.toLowerCase())); } return filteredColumns.map((el, i) => { if (el.type === 'heading') { return <PopoutList.Heading key={'heading_' + i}>{el.content}</PopoutList.Heading>; } const path = el.field.path; const selected = this.state.selectedColumns[path]; return ( <PopoutList.Item key={'column_' + el.field.path} icon={selected ? 'check' : 'dash'} iconHover={selected ? 'dash' : 'check'} isSelected={!!selected} label={el.field.label} onClick={() => { this.toggleColumn(path, !selected); }} /> ); }); }, render () { return ( <div> <ListHeaderButton active={this.state.isOpen} id="listHeaderColumnButton" glyph="list-unordered" label="Columns" onClick={() => this.togglePopout(!this.state.isOpen)} /> <Popout isOpen={this.state.isOpen} onCancel={() => this.togglePopout(false)} relativeToID="listHeaderColumnButton"> <Popout.Header title="Columns" /> <Popout.Body scrollable> <FormField style={{ borderBottom: '1px dashed rgba(0,0,0,0.1)', paddingBottom: '1em' }}> <FormInput autoFocus value={this.state.searchString} onChange={this.updateSearch} placeholder="Find a column..." /> </FormField> <PopoutList> {this.renderColumns()} </PopoutList> </Popout.Body> <Popout.Footer primaryButtonAction={this.applyColumns} primaryButtonLabel="Apply" secondaryButtonAction={() => this.togglePopout(false)} secondaryButtonLabel="Cancel" /> </Popout> </div> ); }, }); module.exports = ListColumnsForm;
src/resources/assets/react-app/components/Announcements.js
darrenmerrett/ruf
import React, { Component } from 'react'; class Announcements extends Component { render() { return null; } } export default Announcements;
src/list/selection/list.js
JabX/focus-components
// Dependencies import React from 'react'; import builder from 'focus-core/component/builder'; import types from 'focus-core/component/types'; import { reduce, isArray, find } from 'lodash'; //Add a ref to the props if the component is not pure add nothing in the other case. import { addRefToPropsIfNotPure, LINE } from '../../utils/is-react-class-component'; import {translate} from 'focus-core/translation'; // Mixins import {mixin as infiniteScrollMixin} from '../mixin/infinite-scroll'; import referenceMixin from '../../common/mixin/reference-property'; // Components import Button from '../../components/button'; const listMixin = { /** * Display name. */ displayName: 'SelectionList', /** * Mixin dependancies. */ mixins: [infiniteScrollMixin, referenceMixin], /** * Default properties for the list. * @returns {{isSelection: boolean}} the default properties */ getDefaultProps: function getListDefaultProps() { return { data: [], isSelection: true, selectionStatus: 'partial', selectionData: [], isLoading: false, operationList: [], idField: 'id' }; }, /** * list property validation. * @type {Object} */ propTypes: { LineComponent: types('func'), buttonComponent: types('func'), data: types('array'), idField: types('string'), isLoading: types('bool'), isSelection: types('bool'), loader: types('func'), onLineClick: types('func'), onSelection: types('func'), operationList: types(['array', 'object']), selectionData: types('array'), selectionStatus: types('string') }, getInitialState() { return { selectedItems: null } }, componentWillReceiveProps({selectionStatus, data}) { switch (selectionStatus) { case 'none': this.setState({ selectedItems: new Map() }); break; case 'selected': let selectedItems = new Map(); data.forEach(item => { selectedItems.set(JSON.stringify(item), item) }); this.setState({ selectedItems }); break; } }, /** * Return selected items in the list. * @return {Array} selected items */ getSelectedItems() { const {selectedItems} = this.state; if (selectedItems !== null) { const selectedItems = []; for (let [item, isSelected] of this.state.selectedItems) { if (isSelected) selectedItems.push(JSON.parse(item)); } return selectedItems; } else { return reduce(this.refs, (acc, ref) => { if (ref.getValue) { const {item, isSelected} = ref.getValue(); if (isSelected) acc.push(item); } return acc; }, []); } }, _handleLineSelection(data, isSelected) { const {selectedItems} = this.state; const newSelectedItems = new Map(); if (selectedItems !== null) { for (let [key, value] of selectedItems) { newSelectedItems.set(key, value); } } newSelectedItems.set(JSON.stringify(data), isSelected); this.setState({ selectedItems: newSelectedItems }, () => { if (this.props.onSelection) { this.props.onSelection(data, isSelected); } }); }, /** * Render lines of the list. * @returns {*} DOM for lines */ _renderLines() { const {data, LineComponent: Line, selectionData, idField, selectionStatus, ...otherProps} = this.props; if (selectionData && selectionData.length > 0) { console.warn('[DEPRECATED] You are using \'selectionData\' prop which is now DEPRECATED. Please use \'selectionnableInitializer\' on line component.'); } // LEGACY CODE const customLineComponent = otherProps.lineComponent; if (customLineComponent) { console.warn('%c DEPRECATED : You are using the lineComponent prop in a list component, this will be removed in the next release of Focus Components. Please use LineComponent prop instead.', 'color: #FF9C00; font-weight: bold'); } const FinalLineComponent = customLineComponent || Line; // END OF LEGACY CODE if (!isArray(data)) { console.error( 'List: Lines: it seems data is not an array, please check the value in your store, it could also be related to your action in case of a load (have a look to shouldDumpStoreOnActionCall option).' ); } return data.map((line, idx) => { let isSelected; const selection = find(selectionData, { [idField]: line[idField] }); if (selection) { isSelected = selection.isSelected; } else { switch (selectionStatus) { case 'none': isSelected = false; break; case 'selected': isSelected = true; break; case 'partial': isSelected = undefined; break; default: isSelected = false; } } const listFinalProps = addRefToPropsIfNotPure( FinalLineComponent, { ...otherProps, data: line, isSelected, key: line[idField] || idx, onSelection: this._handleLineSelection, reference: this._getReference() }, `${LINE}${idx}`); return <FinalLineComponent {...listFinalProps} />; }); }, /** * Render loading state * @return {HTML} the loading state */ _renderLoading() { const {isLoading, loader} = this.props; if (isLoading) { if (loader) { return loader(); } return ( <li className='sl-loading'>{translate('list.loading')} ...</li> ); } }, /** * Render manual fetch state * @return {HTML} the rendered manual fetch state */ _renderManualFetch() { const {isManualFetch, hasMoreData} = this.props; if (isManualFetch && hasMoreData) { const style = { className: 'primary' }; return ( <li className='sl-button'> <Button handleOnClick={this.handleShowMore} label='list.button.showMore' style={style} type='button' /> </li> ); } }, shouldComponentUpdate({selectionStatus}, {selectedItems}) { return selectedItems === this.state.selectedItems || selectedItems.size === 0 || selectionStatus !== this.props.selectionStatus; }, /** * Render the list. * @returns {XML} DOM of the component */ render() { const {isSelection} = this.props; return ( <ul data-focus='selection-list' data-selection={isSelection}> {this._renderLines()} {this._renderLoading()} {this._renderManualFetch()} </ul> ); } }; const builtComp = builder(listMixin); const {component, mixin} = builtComp; export { component, mixin } export default builtComp;
app/components/common/NavMobile/index.js
vkurzweg/aloha
/** * * Nav * */ import React from 'react'; import styled from 'styled-components'; import AppBar from 'material-ui/AppBar'; import Drawer from 'material-ui/Drawer'; import MenuItem from 'material-ui/MenuItem'; import { browserHistory } from 'react-router'; import { Image } from 'cloudinary-react'; const StyledAppBar = styled(AppBar)` width: 100%; background: #2bf7d0; background: -moz-linear-gradient(left, #2bf7d0 0%, #8ae5ab 95%); background: -webkit-linear-gradient(left, #2bf7d0 0%,#8ae5ab 95%); background: linear-gradient(to right, #2bf7d0 0%,#8ae5ab 95%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#2bf7d0', endColorstr='#8ae5ab',GradientType=1 ); `; const StyledDrawer = styled(Drawer)` background: #2bf7d0; background: -moz-linear-gradient(left, #2bf7d0 0%, #8ae5ab 95%); background: -webkit-linear-gradient(left, #2bf7d0 0%,#8ae5ab 95%); background: linear-gradient(to right, #2bf7d0 0%,#8ae5ab 95%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#2bf7d0', endColorstr='#8ae5ab',GradientType=1 ); `; const A = styled.a` font-family: 'Lobster', sans-serif; text-decoration: none; font-size: 22px; color: black; &:hover { color: #FF80AB; } `; const items = [ { name: 'Rates & Booking', url: '/rates', }, { name: 'FAQ', url: '/faq', }, { name: 'Photography', url: '/gallery', }, { name: 'Instructors - California', url: '/instructors', }, { name: 'Instructors - Hawaii', url: '/instructors-hawaii', }, { name: 'Retreats', url: '/retreats', }, { name: 'Press', url: '/press', }, { name: 'Contact', url: '/contact', }, ]; class Nav extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { open: false, }; this.handleToggle = this.handleToggle.bind(this); this.handleClose = this.handleClose.bind(this); } handleToggle() { this.setState({ open: !this.state.open }); } handleClose(url) { this.setState({ open: false }); browserHistory.push(url); } render() { const brand = <A href="http://www.alohabrothers.surf" target="blank" style={{ fontFamily: 'Lobster' }}>Aloha Brothers Surf Lessons <Image cloudName="kurzweg" publicId="aloha-logo" quality="auto" width="35" responsive /></A>; return ( <div> <div style={{ position: 'fixed', width: '100%', zIndex: '100', top: '0' }}> <StyledAppBar title={brand} titleStyle={{ textDecoration: 'none', marginTop: '-2%', textAlign: 'left' }} iconElementLeft={<Image cloudName="kurzweg" publicId="menu" responsive alt="menu icon" style={{ padding: '1%' }} />} iconStyleLeft={{ padding: '1%' }} onLeftIconButtonTouchTap={this.handleToggle} /> <StyledDrawer docked={false} width={200} open={this.state.open} onRequestChange={(open) => this.setState({ open })} > {items.map((item, idx) => { return ( <MenuItem key={idx} onTouchTap={this.handleClose.bind(null, item.url)}>{item.name}</MenuItem> ); })} <A href="http://www.dingdelight.surf" target="blank" style={{ fontFamily: 'Lobster Two', textAlign: 'center', marginLeft: '8%', color: '#7C4DFF' }} >ding delight</A> </StyledDrawer> </div> </div> ); } } Nav.propTypes = { }; export default Nav; // { // name: 'Ding Repair', // url: '/dingrepair', // }, { // name: 'Retreats', // url: '/retreats', // }, { // name: 'Camping', // url: '/camping', // }, // const StyledAppBar = styled(AppBar)` // background: -moz-linear-gradient(45deg, rgba(124,77,255,1) 0%, rgba(179,188,245,1) 100%); /* ff3.6+ */ // background: -webkit-gradient(linear, left bottom, right top, color-stop(0%, rgba(124,77,255,1)), color-stop(100%, rgba(179,188,245,1))); /* safari4+,chrome */ // background: -webkit-linear-gradient(45deg, rgba(124,77,255,1) 0%, rgba(179,188,245,1) 100%); /* safari5.1+,chrome10+ */ // background: -o-linear-gradient(45deg, rgba(124,77,255,1) 0%, rgba(179,188,245,1) 100%); /* opera 11.10+ */ // background: -ms-linear-gradient(45deg, rgba(124,77,255,1) 0%, rgba(179,188,245,1) 100%); /* ie10+ */ // background: linear-gradient(45deg, rgba(124,77,255,1) 0%, rgba(179,188,245,1) 100%); /* w3c */ // filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#B3BCF5', endColorstr='#7C4DFF',GradientType=1 ); /* ie6-9 */ `; // const brand = <A href="/">Aloha Brothers Surf Lessons</A>;
client/app/bundles/PartyMode/parties/containers/partyItems/ItemLabel.js
lrosskamp/makealist-public
import React from 'react' import { connect } from 'react-redux' import ItemLabel from '../../components/partyItems/ItemLabel' import ui from '../../../ui' import members from '../../../members' import * as globalSelectors from '../../../selectors' const mapStateToProps = (state, ownProps) =>({ withCount: ui.listEntriesForm.selectors.getWithCountBoolean( globalSelectors.getListEntriesForm(state) ), members: members.selectors.getMembers(state.members, ownProps.item.memberIds) }) export default connect(mapStateToProps)(ItemLabel)
src/index.js
priyankasarma/ReduxSimpleStarter
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import _ from 'lodash'; import YTSearch from 'youtube-api-search'; import SearchBar from './components/search-bar'; import VideoList from './components/video-list'; import VideoDetail from './components/video-detail'; const API_KEY = 'AIzaSyB9FLYRn6acyI4zTp4cSKbe5A154DHg70M'; // Create a new component that produces some HTML class App extends Component { constructor(props) { super(props); this.state = { videos: [], selectedVideo: null }; this.videoSearch('surfboards') } videoSearch(term) { YTSearch({ key: API_KEY, term: term }, videos => { this.setState({ videos: videos, selectedVideo: videos[0] }); }); } render() { const videoSearch = _.debounce((term) => this.videoSearch(term), 300); return ( <div> <SearchBar onSearchTermChange={videoSearch}/> <VideoDetail video={this.state.selectedVideo}/> <VideoList onVideoSelect={selectedVideo => this.setState({selectedVideo})} videos={ this.state.videos } /> </div> ); } } // Render the generated HTML in the DOM of the web page ReactDOM.render(<App />, document.querySelector('.container'));
app/utils/injectSaga.js
kaizen7-nz/gold-star-chart
import React from 'react'; import PropTypes from 'prop-types'; import hoistNonReactStatics from 'hoist-non-react-statics'; import getInjectors from './sagaInjectors'; /** * Dynamically injects a saga, passes component's props as saga arguments * * @param {string} key A key of the saga * @param {function} saga A root saga that will be injected * @param {string} [mode] By default (constants.RESTART_ON_REMOUNT) the saga will be started on component mount and * cancelled with `task.cancel()` on component un-mount for improved performance. Another two options: * - constants.DAEMON—starts the saga on component mount and never cancels it or starts again, * - constants.ONCE_TILL_UNMOUNT—behaves like 'RESTART_ON_REMOUNT' but never runs it again. * */ export default ({ key, saga, mode }) => (WrappedComponent) => { class InjectSaga extends React.Component { static WrappedComponent = WrappedComponent; static contextTypes = { store: PropTypes.object.isRequired, }; static displayName = `withSaga(${(WrappedComponent.displayName || WrappedComponent.name || 'Component')})`; componentWillMount() { const { injectSaga } = this.injectors; injectSaga(key, { saga, mode }, this.props); } componentWillUnmount() { const { ejectSaga } = this.injectors; ejectSaga(key); } injectors = getInjectors(this.context.store); render() { return <WrappedComponent {...this.props} />; } } return hoistNonReactStatics(InjectSaga, WrappedComponent); };
geonode/contrib/monitoring/frontend/src/components/organisms/error-list/index.js
kartoza/geonode
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import HoverPaper from '../../atoms/hover-paper'; import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import styles from './styles'; import actions from './actions'; const mapStateToProps = (state) => ({ errorList: state.errorList.response, interval: state.interval.interval, timestamp: state.interval.timestamp, }); @connect(mapStateToProps, actions) class ErrorList extends React.Component { static contextTypes = { router: PropTypes.object.isRequired, } static propTypes = { errorList: PropTypes.object, get: PropTypes.func.isRequired, interval: PropTypes.number, timestamp: PropTypes.instanceOf(Date), } constructor(props) { super(props); this.handleClick = (row, column, event) => { this.context.router.push(`/errors/${event.target.dataset.id}`); }; } componentWillMount() { this.props.get(this.props.interval); } componentWillReceiveProps(nextProps) { if (nextProps && nextProps.interval) { if (this.props.timestamp !== nextProps.timestamp) { this.props.get(nextProps.interval); } } } render() { const errorList = this.props.errorList; const errors = this.props.errorList ? errorList.exceptions.map( error => <TableRow key={error.id}> <TableRowColumn data-id={error.id}>{error.id}</TableRowColumn> <TableRowColumn data-id={error.id}>{error.error_type}</TableRowColumn> <TableRowColumn data-id={error.id}>{error.service.name}</TableRowColumn> <TableRowColumn data-id={error.id}>{error.created}</TableRowColumn> </TableRow> ) : ''; return ( <HoverPaper style={styles.content}> <div style={styles.header}> <h3 style={styles.title}>Errors</h3> </div> <Table onCellClick={this.handleClick}> <TableHeader displaySelectAll={false}> <TableRow> <TableHeaderColumn>ID</TableHeaderColumn> <TableHeaderColumn>Type</TableHeaderColumn> <TableHeaderColumn>Service</TableHeaderColumn> <TableHeaderColumn>Date</TableHeaderColumn> </TableRow> </TableHeader> <TableBody showRowHover stripedRows displayRowCheckbox={false}> {errors} </TableBody> </Table> </HoverPaper> ); } } export default ErrorList;
src/Parser/Shaman/Shared/MaelstromChart/MaelstromTab.js
enragednuke/WoWAnalyzer
import React from 'react'; import Tab from 'Main/Tab'; import Analyzer from 'Parser/Core/Analyzer'; import MaelstromChart from './Maelstrom'; import MaelstromTracker from './MaelstromTracker'; class MaelstromTab extends Analyzer { static dependencies = { maelstromTracker: MaelstromTracker, }; tab() { return { title: 'Maelstrom Chart', url: 'maelstrom', render: () => ( <Tab title='Maelstrom' style={{ padding: '15px 22px' }}> <MaelstromChart start={this.owner.fight.start_time} end={this.owner.fight.end_time} maelstromMax={this.maelstromTracker._maxMaelstrom} maelstromPerSecond={this.maelstromTracker.maelstromBySecond} tracker={this.maelstromTracker.tracker} activeMaelstromGenerated={this.maelstromTracker.activeMaelstromGenerated} activeMaelstromWasted={this.maelstromTracker.activeMaelstromWasted} generatorCasts={this.maelstromTracker.generatorCasts} activeMaelstromWastedTimeline={this.maelstromTracker.activeMaelstromWastedTimeline} /> </Tab> ), }; } } export default MaelstromTab;
Examples/UIExplorer/js/Navigator/BreadcrumbNavSample.js
salanki/react-native
/** * 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. * * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * 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 NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ 'use strict'; var React = require('react'); var ReactNative = require('react-native'); var { Navigator, StyleSheet, ScrollView, Text, TouchableHighlight, TouchableOpacity } = ReactNative; var _getRandomRoute = function() { return { title: '#' + Math.ceil(Math.random() * 1000), }; }; class NavButton extends React.Component { render() { return ( <TouchableHighlight style={styles.button} underlayColor="#B5B5B5" onPress={this.props.onPress}> <Text style={styles.buttonText}>{this.props.text}</Text> </TouchableHighlight> ); } } class BreadcrumbNavSample extends React.Component { componentWillMount() { this._navBarRouteMapper = { rightContentForRoute: function(route, navigator) { return null; }, titleContentForRoute: function(route, navigator) { return ( <TouchableOpacity onPress={() => navigator.push(_getRandomRoute())}> <Text style={styles.titleText}>{route.title}</Text> </TouchableOpacity> ); }, iconForRoute: function(route, navigator) { return ( <TouchableOpacity onPress={() => { navigator.popToRoute(route); }} style={styles.crumbIconPlaceholder} /> ); }, separatorForRoute: function(route, navigator) { return ( <TouchableOpacity onPress={navigator.pop} style={styles.crumbSeparatorPlaceholder} /> ); } }; } _renderScene = (route, navigator) => { return ( <ScrollView style={styles.scene}> <NavButton onPress={() => { navigator.push(_getRandomRoute()); }} text="Push" /> <NavButton onPress={() => { navigator.immediatelyResetRouteStack([_getRandomRoute(), _getRandomRoute()]); }} text="Reset w/ 2 scenes" /> <NavButton onPress={() => { navigator.popToTop(); }} text="Pop to top" /> <NavButton onPress={() => { navigator.replace(_getRandomRoute()); }} text="Replace" /> <NavButton onPress={() => { this.props.navigator.pop(); }} text="Close breadcrumb example" /> </ScrollView> ); }; render() { return ( <Navigator style={styles.container} initialRoute={_getRandomRoute()} renderScene={this._renderScene} navigationBar={ <Navigator.BreadcrumbNavigationBar routeMapper={this._navBarRouteMapper} /> } /> ); } } var styles = StyleSheet.create({ scene: { paddingTop: 50, flex: 1, }, button: { backgroundColor: 'white', padding: 15, borderBottomWidth: StyleSheet.hairlineWidth, borderBottomColor: '#CDCDCD', }, buttonText: { fontSize: 17, fontWeight: '500', }, container: { overflow: 'hidden', backgroundColor: '#dddddd', flex: 1, }, titleText: { fontSize: 18, color: '#666666', textAlign: 'center', fontWeight: 'bold', lineHeight: 32, }, crumbIconPlaceholder: { flex: 1, backgroundColor: '#666666', }, crumbSeparatorPlaceholder: { flex: 1, backgroundColor: '#aaaaaa', }, }); module.exports = BreadcrumbNavSample;
src/routes/Counter/components/Counter.js
rwenor/react-ci-app
import React from 'react' import PropTypes from 'prop-types' export const Counter = ({ counter, increment, doubleAsync }) => ( <div style={{ margin: '0 auto' }} > <h2>Counter: {counter}</h2> <button className='btn btn-primary' onClick={increment}> Increment </button> {' '} <button className='btn btn-secondary' onClick={doubleAsync}> Double (Async) </button> </div> ) Counter.propTypes = { counter: PropTypes.number.isRequired, increment: PropTypes.func.isRequired, doubleAsync: PropTypes.func.isRequired, } export default Counter
src/App.js
tomgowans/365beers
import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import React, { Component } from 'react'; import { Link } from 'react-router'; import * as actionCreators from './actions/actionCreators'; class Main extends Component { constructor(props) { super(props); this.props.siteWideMessage('', ''); } messageFormatting(message, messageClassName) { if (message) { return ( <p className={`alert ${messageClassName}`}>{message}</p> ); } } render() { var messageItem = { containerClass: '', message: '' }; // TODO: Hide message after a couple of seconds if (this.props.message.length) { messageItem = this.props.message[0] } return ( <div> <header className="navbar navbar-inverse"> <h1 className="navbar-brand">365 Beers</h1> <nav id="navbar" className="navbar-collapse"> <ul className="nav navbar-nav"> <li><Link to={`/list`}>Your list</Link></li> <li><Link to={`/new`}>Add new beer</Link></li> </ul> </nav> </header> { this.messageFormatting(messageItem.message, messageItem.containerClass) } <main> {React.cloneElement({...this.props}.children, {...this.props})} </main> </div> ); } } function mapStateToProps(state) { return { items: state.items, message: state.messages } } function mapDispatchToProps(dispatch) { return bindActionCreators(actionCreators, dispatch); } const App = connect(mapStateToProps, mapDispatchToProps)(Main); export default App;
public/dev.bfi.local/www/sites/all/modules/civicrm/packages/PHP/CodeCoverage/Report/HTML/Renderer/Template/jquery.min.js
BuckyFullerInst/BFI-old
/*! jQuery v1.6.3 http://jquery.com/ | http://jquery.org/license */ (function(a,b){function cu(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cr(a){if(!cg[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ch||(ch=c.createElement("iframe"),ch.frameBorder=ch.width=ch.height=0),b.appendChild(ch);if(!ci||!ch.createElement)ci=(ch.contentWindow||ch.contentDocument).document,ci.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),ci.close();d=ci.createElement(a),ci.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ch)}cg[a]=e}return cg[a]}function cq(a,b){var c={};f.each(cm.concat.apply([],cm.slice(0,b)),function(){c[this]=a});return c}function cp(){cn=b}function co(){setTimeout(cp,0);return cn=f.now()}function cf(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ce(){try{return new a.XMLHttpRequest}catch(b){}}function b$(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 bZ(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 bY(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bA.test(a)?d(a,e):bY(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)bY(a+"["+e+"]",b[e],c,d);else d(a,b)}function bX(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 bW(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===bP,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=bW(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bW(a,c,d,e,"*",g));return l}function bV(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bL),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 by(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bt:bu;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bv(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function bl(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bd,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bk(a){f.nodeName(a,"input")?bj(a):"getElementsByTagName"in a&&f.grep(a.getElementsByTagName("input"),bj)}function bj(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bi(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bh(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 bg(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 bf(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function V(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(Q.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 U(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function M(a,b){return(a&&a!=="*"?a+".":"")+b.replace(y,"`").replace(z,"&")}function L(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(w,"")===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 J(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 D(){return!0}function C(){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 K(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(K,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=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};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.3",length:0,size:function(){return this.length},toArray:function(){return G.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)?F.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(),B.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(G.apply(this,arguments),"slice",G.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:F,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;B.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e._Deferred();if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},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):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},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(c){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(x,"ms-").replace(w,y)},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:H?function(a){return a==null?"":H.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)?F.call(c,a):e.merge(c,a)}return c},inArray:function(a,b){if(!b)return-1;if(I)return I.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=G.call(arguments,2),g=function(){return a.apply(c,f.concat(G.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){J["[object "+b+"]"]=b.toLowerCase()}),A=e.uaMatch(z),A.browser&&(e.browser[A.browser]=!0,e.browser.version=A.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?C=function(){c.removeEventListener("DOMContentLoaded",C,!1),e.ready()}:c.attachEvent&&(C=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",C),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+"With"](this===b?d:this,[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,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;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{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={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:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.firstChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-1000px",top:"-1000px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0),o.innerHTML="",n.removeChild(o);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;o=l=g=h=m=j=a=i=null;return k}(),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,h,i=f.expando,j=typeof c=="string",k=a.nodeType,l=k?f.cache:a,m=k?a[f.expando]:a[f.expando]&&f.expando;if((!m||e&&m&&l[m]&&!l[m][i])&&j&&d===b)return;m||(k?a[f.expando]=m=++f.uuid:m=f.expando),l[m]||(l[m]={},k||(l[m].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?l[m][i]=f.extend(l[m][i],c):l[m]=f.extend(l[m],c);g=l[m],e&&(g[i]||(g[i]={}),g=g[i]),d!==b&&(g[f.camelCase(c)]=d);if(c==="events"&&!g[c])return g[i]&&g[i].events;j?(h=g[c],h==null&&(h=g[f.camelCase(c)])):h=g;return h}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e=f.expando,g=a.nodeType,h=g?f.cache:a,i=g?a[f.expando]:f.expando;if(!h[i])return;if(b){d=c?h[i][e]:h[i];if(d){d[b]||(b=f.camelCase(b)),delete d[b];if(!l(d))return}}if(c){delete h[i][e];if(!l(h[i]))return}var j=h[i][e];f.support.deleteExpando||!h.setInterval?delete h[i]:h[i]=null,j?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=j):g&&(f.support.deleteExpando?delete a[f.expando]:a.removeAttribute?a.removeAttribute(f.expando):a[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;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){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(o);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(o);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(n," ");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(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].nodeType===1&&(" "+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;d=e.value;return typeof d=="string"?d.replace(p,""):d==null?"":d}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);j&&(c=f.attrFix[c]||c,i=f.attrHooks[c],i||(t.test(c)?i=v:u&&(i=u)));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&&(h=i.get(a,c))!==null)return h;h=a.getAttribute(c);return h===null?b:h},removeAttr:function(a,b){var c;a.nodeType===1&&(b=f.attrFix[b]||b,f.attr(a,b,""),a.removeAttribute(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}}},value:{get:function(a,b){if(u&&f.nodeName(a,"button"))return u.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(u&&f.nodeName(a,"button"))return u.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=a.nodeType;if(!a||e===3||e===8||e===2)return b;var g,h,i=e!==1||!f.isXMLDoc(a);i&&(c=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))!==null?g: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}}}}),f.attrHooks.tabIndex=f.propHooks.tabIndex,v={get:function(a,c){var d;return f.prop(a,c)===!0||(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}},f.support.getSetAttribute||(u=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?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.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);return null}})),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 w=/\.(.*)$/,x=/^(?:textarea|input|select)$/i,y=/\./g,z=/ /g,A=/[^\w\s.|`]/g,B=function(a){return a.replace(A,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=C;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=C);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(),B).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!=null?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,M(a.origType,a.selector),f.extend({},a,{handler:L,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,M(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()?D:C):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=D;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=D;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=D,this.stopPropagation()},isDefaultPrevented:C,isPropagationStopped:C,isImmediatePropagationStopped:C};var E=function(a){var b=a.relatedTarget,c=!1,d=a.type;a.type=a.data,b!==this&&(b&&(c=f.contains(this,b)),c||(f.event.handle.apply(this,arguments),a.type=d))},F=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?F:E,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?F:E)}}}),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=f.nodeName(b,"input")?b.type:"";(c==="submit"||c==="image")&&f(b).closest("form").length&&J("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&J("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var G,H=function(a){var b=f.nodeName(a,"input")?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},I=function(c){var d=c.target,e,g;if(!!x.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=H(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:I,beforedeactivate:I,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&I.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")&&I.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",H(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in G)f.event.add(this,c+".specialChange",G[c]);return x.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return x.test(this.nodeName)}},G=f.event.special.change.filters,G.focus=G.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 K={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||C,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=w.exec(h),k="",j&&(k=j[0],h=h.replace(w,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,K[h]?(a.push(K[h]+k),h=h+k):h=(K[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+M(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+M(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 N=/Until$/,O=/^(?:parents|prevUntil|prevAll)/,P=/,/,Q=/^.[^:#\[\.,]*$/,R=Array.prototype.slice,S=f.expr.match.POS,T={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(V(this,a,!1),"not",a)},filter:function(a){return this.pushStack(V(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]=S.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=S.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)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(U(c[0])||U(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=R.call(arguments);N.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!T[a]?f.unique(e):e,(this.length>1||P.test(d))&&O.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 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|object|embed|option|style)/i,bb=/checked\s*(?:[^=]|=\s*.checked.)/i,bc=/\/(java|ecma)script/i,bd=/^\s*<!(?:\[CDATA\[|\-\-)/,be={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,"",""]};be.optgroup=be.option,be.tbody=be.tfoot=be.colgroup=be.caption=be.thead,be.th=be.td,f.support.htmlSerialize||(be._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(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!be[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$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"&&bb.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?bf(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bl)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i;b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!ba.test(a[0])&&(f.support.checkClone||!bb.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)){bh(a,d),e=bi(a),g=bi(d);for(h=0;e[h];++h)g[h]&&bh(e[h],g[h])}if(b){bg(a,d);if(c){e=bi(a),g=bi(d);for(h=0;e[h];++h)bg(e[h],g[h])}}e=g=null;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(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=be[l]||be._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=$.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&&X.test(k)&&o.insertBefore(b.createTextNode(X.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++)bk(k[i]);else bk(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bc.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 bm=/alpha\([^)]*\)/i,bn=/opacity=([^)]*)/,bo=/([A-Z]|^ms)/g,bp=/^-?\d+(?:px)?$/i,bq=/^-?\d/,br=/^([\-+])=([\-+.\de]+)/,bs={position:"absolute",visibility:"hidden",display:"block"},bt=["Left","Right"],bu=["Top","Bottom"],bv,bw,bx;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=bv(a,"opacity","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=br.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(bv)return bv(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]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return by(a,b,d);f.swap(a,bs,function(){e=by(a,b,d)});return e}},set:function(a,b){if(!bp.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bn.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.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bm,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bm.test(g)?g.replace(bm,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=bv(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bw=function(a,c){var d,e,g;c=c.replace(bo,"-$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&&(bx=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bp.test(d)&&bq.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}),bv=bw||bx,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 bz=/%20/g,bA=/\[\]$/,bB=/\r?\n/g,bC=/#.*$/,bD=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bE=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bF=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bG=/^(?:GET|HEAD)$/,bH=/^\/\//,bI=/\?/,bJ=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bK=/^(?:select|textarea)/i,bL=/\s+/,bM=/([?&])_=[^&]*/,bN=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bO=f.fn.load,bP={},bQ={},bR,bS,bT=["*/"]+["*"];try{bR=e.href}catch(bU){bR=c.createElement("a"),bR.href="",bR=bR.href}bS=bN.exec(bR.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bO)return bO.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(bJ,"")).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||bK.test(this.nodeName)||bE.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(bB,"\r\n")}}):{name:b.name,value:c.replace(bB,"\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?bX(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),bX(a,b);return a},ajaxSettings:{url:bR,isLocal:bF.test(bS[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","*":bT},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:bV(bP),ajaxTransport:bV(bQ),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?bZ(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=b$(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.resolveWith(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._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=bD.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(bC,"").replace(bH,bS[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bL),d.crossDomain==null&&(r=bN.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bS[1]&&r[2]==bS[2]&&(r[3]||(r[1]==="http:"?80:443))==(bS[3]||(bS[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bW(bP,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bG.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bI.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bM,"$1_="+x);d.url=y+(y===d.url?(bI.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]!=="*"?", "+bT+"; 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=bW(bQ,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){s<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)bY(g,a[g],c,e);return d.join("&").replace(bz,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var b_=f.now(),ca=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+b_++}}),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&&(ca.test(b.url)||e&&ca.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(ca,l),b.url===j&&(e&&(k=k.replace(ca,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 cb=a.ActiveXObject?function(){for(var a in cd)cd[a](0,1)}:!1,cc=0,cd;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ce()||cf()}:ce,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,cb&&delete cd[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=++cc,cb&&(cd||(cd={},f(a).unload(cb)),cd[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cg={},ch,ci,cj=/^(?:toggle|show|hide)$/,ck=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cl,cm=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cn;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cq("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",cr(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(cq("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(cq("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=cr(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],cj.test(h)?k[h==="toggle"?d?"show":"hide":h]():(l=ck.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:cq("show",1),slideUp:cq("hide",1),slideToggle:cq("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){f.isFunction(d.old)&&d.old.call(this),d.queue!==!1?f.dequeue(this):a!==!1&&f._unmark(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 g(a){return d.step(a)}var d=this,e=f.fx;this.startTime=cn||co(),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,g.elem=this.elem,g()&&f.timers.push(g)&&!cl&&(cl=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=cn||co(),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(cl),cl=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 cs=/^t(?:able|d|h)$/i,ct=/^(?: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=cu(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||!cs.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=ct.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&&!ct.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=cu(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=cu(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(){var a=this[0];return a&&a.style?parseFloat(f.css(a,d,"padding")):null},f.fn["outer"+c]=function(a){var b=this[0];return b&&b.style?parseFloat(f.css(b,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],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["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 i=f.css(e,d),j=parseFloat(i);return f.isNaN(j)?i:j}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
src/components/Core/Core.js
dm-istomin/hexamer
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { Route, Switch } from 'react-router-dom'; import { ConnectedRouter } from 'connected-react-router'; import { components, history, store } from '../components.js'; import styles from './component.less'; const Core = () => { return ( <Provider store={store}> <ConnectedRouter history={history}> <div className="window"> <div className="window-content"> <div className="pane-group"> <div className="pane-sm sidebar"><components.Menu /></div> <div className="pane padded"><AppRouter /></div> </div> </div> <components.Footer /> </div> </ConnectedRouter> </Provider> ); } const AppRouter = () => { return ( <Switch> <Route exact path="/" component={Home} /> <Route path="/example" component={components.Example} /> <Route path="/web" component={components.Webview} /> </Switch> ); } const Home = () => { return ( <div> <h1>Hello, Electron!</h1> <p>I hope you enjoy using enhanced-electron-react-boilerplate to start your dev off right!</p> <div className='padded'> <div className={`box padded ${styles.box}`}> This has a different background color, but uses the same 'box' className. However, thanks to CSS modules the names dont collide. Here we are setting a background color, and overriding the shadow. </div> </div> </div> ); } export default Core;
01-cadastro-contatos/node_modules/core-js/client/shim.js
btd1337/angular2-dev
/** * core-js 2.4.1 * https://github.com/zloirock/core-js * License: http://rock.mit-license.org * © 2016 Denis Pushkarev */ !function(__e, __g, undefined){ 'use strict'; /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(1); __webpack_require__(50); __webpack_require__(51); __webpack_require__(52); __webpack_require__(54); __webpack_require__(55); __webpack_require__(58); __webpack_require__(59); __webpack_require__(60); __webpack_require__(61); __webpack_require__(62); __webpack_require__(63); __webpack_require__(64); __webpack_require__(65); __webpack_require__(66); __webpack_require__(68); __webpack_require__(70); __webpack_require__(72); __webpack_require__(74); __webpack_require__(77); __webpack_require__(78); __webpack_require__(79); __webpack_require__(83); __webpack_require__(86); __webpack_require__(87); __webpack_require__(88); __webpack_require__(89); __webpack_require__(91); __webpack_require__(92); __webpack_require__(93); __webpack_require__(94); __webpack_require__(95); __webpack_require__(97); __webpack_require__(99); __webpack_require__(100); __webpack_require__(101); __webpack_require__(103); __webpack_require__(104); __webpack_require__(105); __webpack_require__(107); __webpack_require__(108); __webpack_require__(109); __webpack_require__(111); __webpack_require__(112); __webpack_require__(113); __webpack_require__(114); __webpack_require__(115); __webpack_require__(116); __webpack_require__(117); __webpack_require__(118); __webpack_require__(119); __webpack_require__(120); __webpack_require__(121); __webpack_require__(122); __webpack_require__(123); __webpack_require__(124); __webpack_require__(126); __webpack_require__(130); __webpack_require__(131); __webpack_require__(132); __webpack_require__(133); __webpack_require__(137); __webpack_require__(139); __webpack_require__(140); __webpack_require__(141); __webpack_require__(142); __webpack_require__(143); __webpack_require__(144); __webpack_require__(145); __webpack_require__(146); __webpack_require__(147); __webpack_require__(148); __webpack_require__(149); __webpack_require__(150); __webpack_require__(151); __webpack_require__(152); __webpack_require__(158); __webpack_require__(159); __webpack_require__(161); __webpack_require__(162); __webpack_require__(163); __webpack_require__(167); __webpack_require__(168); __webpack_require__(169); __webpack_require__(170); __webpack_require__(171); __webpack_require__(173); __webpack_require__(174); __webpack_require__(175); __webpack_require__(176); __webpack_require__(179); __webpack_require__(181); __webpack_require__(182); __webpack_require__(183); __webpack_require__(185); __webpack_require__(187); __webpack_require__(189); __webpack_require__(190); __webpack_require__(191); __webpack_require__(193); __webpack_require__(194); __webpack_require__(195); __webpack_require__(196); __webpack_require__(203); __webpack_require__(206); __webpack_require__(207); __webpack_require__(209); __webpack_require__(210); __webpack_require__(211); __webpack_require__(212); __webpack_require__(213); __webpack_require__(214); __webpack_require__(215); __webpack_require__(216); __webpack_require__(217); __webpack_require__(218); __webpack_require__(219); __webpack_require__(220); __webpack_require__(222); __webpack_require__(223); __webpack_require__(224); __webpack_require__(225); __webpack_require__(226); __webpack_require__(227); __webpack_require__(228); __webpack_require__(229); __webpack_require__(231); __webpack_require__(234); __webpack_require__(235); __webpack_require__(237); __webpack_require__(238); __webpack_require__(239); __webpack_require__(240); __webpack_require__(241); __webpack_require__(242); __webpack_require__(243); __webpack_require__(244); __webpack_require__(245); __webpack_require__(246); __webpack_require__(247); __webpack_require__(249); __webpack_require__(250); __webpack_require__(251); __webpack_require__(252); __webpack_require__(253); __webpack_require__(254); __webpack_require__(255); __webpack_require__(256); __webpack_require__(258); __webpack_require__(259); __webpack_require__(261); __webpack_require__(262); __webpack_require__(263); __webpack_require__(264); __webpack_require__(267); __webpack_require__(268); __webpack_require__(269); __webpack_require__(270); __webpack_require__(271); __webpack_require__(272); __webpack_require__(273); __webpack_require__(274); __webpack_require__(276); __webpack_require__(277); __webpack_require__(278); __webpack_require__(279); __webpack_require__(280); __webpack_require__(281); __webpack_require__(282); __webpack_require__(283); __webpack_require__(284); __webpack_require__(285); __webpack_require__(286); __webpack_require__(287); module.exports = __webpack_require__(288); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // ECMAScript 6 symbols shim var global = __webpack_require__(2) , has = __webpack_require__(3) , DESCRIPTORS = __webpack_require__(4) , $export = __webpack_require__(6) , redefine = __webpack_require__(16) , META = __webpack_require__(20).KEY , $fails = __webpack_require__(5) , shared = __webpack_require__(21) , setToStringTag = __webpack_require__(22) , uid = __webpack_require__(17) , wks = __webpack_require__(23) , wksExt = __webpack_require__(24) , wksDefine = __webpack_require__(25) , keyOf = __webpack_require__(27) , enumKeys = __webpack_require__(40) , isArray = __webpack_require__(43) , anObject = __webpack_require__(10) , toIObject = __webpack_require__(30) , toPrimitive = __webpack_require__(14) , createDesc = __webpack_require__(15) , _create = __webpack_require__(44) , gOPNExt = __webpack_require__(47) , $GOPD = __webpack_require__(49) , $DP = __webpack_require__(9) , $keys = __webpack_require__(28) , gOPD = $GOPD.f , dP = $DP.f , gOPN = gOPNExt.f , $Symbol = global.Symbol , $JSON = global.JSON , _stringify = $JSON && $JSON.stringify , PROTOTYPE = 'prototype' , HIDDEN = wks('_hidden') , TO_PRIMITIVE = wks('toPrimitive') , isEnum = {}.propertyIsEnumerable , SymbolRegistry = shared('symbol-registry') , AllSymbols = shared('symbols') , OPSymbols = shared('op-symbols') , ObjectProto = Object[PROTOTYPE] , USE_NATIVE = typeof $Symbol == 'function' , QObject = global.QObject; // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173 var setter = !QObject || !QObject[PROTOTYPE] || !QObject[PROTOTYPE].findChild; // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687 var setSymbolDesc = DESCRIPTORS && $fails(function(){ return _create(dP({}, 'a', { get: function(){ return dP(this, 'a', {value: 7}).a; } })).a != 7; }) ? function(it, key, D){ var protoDesc = gOPD(ObjectProto, key); if(protoDesc)delete ObjectProto[key]; dP(it, key, D); if(protoDesc && it !== ObjectProto)dP(ObjectProto, key, protoDesc); } : dP; var wrap = function(tag){ var sym = AllSymbols[tag] = _create($Symbol[PROTOTYPE]); sym._k = tag; return sym; }; var isSymbol = USE_NATIVE && typeof $Symbol.iterator == 'symbol' ? function(it){ return typeof it == 'symbol'; } : function(it){ return it instanceof $Symbol; }; var $defineProperty = function defineProperty(it, key, D){ if(it === ObjectProto)$defineProperty(OPSymbols, key, D); anObject(it); key = toPrimitive(key, true); anObject(D); if(has(AllSymbols, key)){ if(!D.enumerable){ if(!has(it, HIDDEN))dP(it, HIDDEN, createDesc(1, {})); it[HIDDEN][key] = true; } else { if(has(it, HIDDEN) && it[HIDDEN][key])it[HIDDEN][key] = false; D = _create(D, {enumerable: createDesc(0, false)}); } return setSymbolDesc(it, key, D); } return dP(it, key, D); }; var $defineProperties = function defineProperties(it, P){ anObject(it); var keys = enumKeys(P = toIObject(P)) , i = 0 , l = keys.length , key; while(l > i)$defineProperty(it, key = keys[i++], P[key]); return it; }; var $create = function create(it, P){ return P === undefined ? _create(it) : $defineProperties(_create(it), P); }; var $propertyIsEnumerable = function propertyIsEnumerable(key){ var E = isEnum.call(this, key = toPrimitive(key, true)); if(this === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return false; return E || !has(this, key) || !has(AllSymbols, key) || has(this, HIDDEN) && this[HIDDEN][key] ? E : true; }; var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(it, key){ it = toIObject(it); key = toPrimitive(key, true); if(it === ObjectProto && has(AllSymbols, key) && !has(OPSymbols, key))return; var D = gOPD(it, key); if(D && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key]))D.enumerable = true; return D; }; var $getOwnPropertyNames = function getOwnPropertyNames(it){ var names = gOPN(toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(!has(AllSymbols, key = names[i++]) && key != HIDDEN && key != META)result.push(key); } return result; }; var $getOwnPropertySymbols = function getOwnPropertySymbols(it){ var IS_OP = it === ObjectProto , names = gOPN(IS_OP ? OPSymbols : toIObject(it)) , result = [] , i = 0 , key; while(names.length > i){ if(has(AllSymbols, key = names[i++]) && (IS_OP ? has(ObjectProto, key) : true))result.push(AllSymbols[key]); } return result; }; // 19.4.1.1 Symbol([description]) if(!USE_NATIVE){ $Symbol = function Symbol(){ if(this instanceof $Symbol)throw TypeError('Symbol is not a constructor!'); var tag = uid(arguments.length > 0 ? arguments[0] : undefined); var $set = function(value){ if(this === ObjectProto)$set.call(OPSymbols, value); if(has(this, HIDDEN) && has(this[HIDDEN], tag))this[HIDDEN][tag] = false; setSymbolDesc(this, tag, createDesc(1, value)); }; if(DESCRIPTORS && setter)setSymbolDesc(ObjectProto, tag, {configurable: true, set: $set}); return wrap(tag); }; redefine($Symbol[PROTOTYPE], 'toString', function toString(){ return this._k; }); $GOPD.f = $getOwnPropertyDescriptor; $DP.f = $defineProperty; __webpack_require__(48).f = gOPNExt.f = $getOwnPropertyNames; __webpack_require__(42).f = $propertyIsEnumerable; __webpack_require__(41).f = $getOwnPropertySymbols; if(DESCRIPTORS && !__webpack_require__(26)){ redefine(ObjectProto, 'propertyIsEnumerable', $propertyIsEnumerable, true); } wksExt.f = function(name){ return wrap(wks(name)); } } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Symbol: $Symbol}); for(var symbols = ( // 19.4.2.2, 19.4.2.3, 19.4.2.4, 19.4.2.6, 19.4.2.8, 19.4.2.9, 19.4.2.10, 19.4.2.11, 19.4.2.12, 19.4.2.13, 19.4.2.14 'hasInstance,isConcatSpreadable,iterator,match,replace,search,species,split,toPrimitive,toStringTag,unscopables' ).split(','), i = 0; symbols.length > i; )wks(symbols[i++]); for(var symbols = $keys(wks.store), i = 0; symbols.length > i; )wksDefine(symbols[i++]); $export($export.S + $export.F * !USE_NATIVE, 'Symbol', { // 19.4.2.1 Symbol.for(key) 'for': function(key){ return has(SymbolRegistry, key += '') ? SymbolRegistry[key] : SymbolRegistry[key] = $Symbol(key); }, // 19.4.2.5 Symbol.keyFor(sym) keyFor: function keyFor(key){ if(isSymbol(key))return keyOf(SymbolRegistry, key); throw TypeError(key + ' is not a symbol!'); }, useSetter: function(){ setter = true; }, useSimple: function(){ setter = false; } }); $export($export.S + $export.F * !USE_NATIVE, 'Object', { // 19.1.2.2 Object.create(O [, Properties]) create: $create, // 19.1.2.4 Object.defineProperty(O, P, Attributes) defineProperty: $defineProperty, // 19.1.2.3 Object.defineProperties(O, Properties) defineProperties: $defineProperties, // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) getOwnPropertyDescriptor: $getOwnPropertyDescriptor, // 19.1.2.7 Object.getOwnPropertyNames(O) getOwnPropertyNames: $getOwnPropertyNames, // 19.1.2.8 Object.getOwnPropertySymbols(O) getOwnPropertySymbols: $getOwnPropertySymbols }); // 24.3.2 JSON.stringify(value [, replacer [, space]]) $JSON && $export($export.S + $export.F * (!USE_NATIVE || $fails(function(){ var S = $Symbol(); // MS Edge converts symbol values to JSON as {} // WebKit converts symbol values to JSON as null // V8 throws on boxed symbols return _stringify([S]) != '[null]' || _stringify({a: S}) != '{}' || _stringify(Object(S)) != '{}'; })), 'JSON', { stringify: function stringify(it){ if(it === undefined || isSymbol(it))return; // IE8 returns string on undefined var args = [it] , i = 1 , replacer, $replacer; while(arguments.length > i)args.push(arguments[i++]); replacer = args[1]; if(typeof replacer == 'function')$replacer = replacer; if($replacer || !isArray(replacer))replacer = function(key, value){ if($replacer)value = $replacer.call(this, key, value); if(!isSymbol(value))return value; }; args[1] = replacer; return _stringify.apply($JSON, args); } }); // 19.4.3.4 Symbol.prototype[@@toPrimitive](hint) $Symbol[PROTOTYPE][TO_PRIMITIVE] || __webpack_require__(8)($Symbol[PROTOTYPE], TO_PRIMITIVE, $Symbol[PROTOTYPE].valueOf); // 19.4.3.5 Symbol.prototype[@@toStringTag] setToStringTag($Symbol, 'Symbol'); // 20.2.1.9 Math[@@toStringTag] setToStringTag(Math, 'Math', true); // 24.3.3 JSON[@@toStringTag] setToStringTag(global.JSON, 'JSON', true); /***/ }, /* 2 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 3 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(5)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 5 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(2) , core = __webpack_require__(7) , hide = __webpack_require__(8) , redefine = __webpack_require__(16) , ctx = __webpack_require__(18) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , target = IS_GLOBAL ? global : IS_STATIC ? global[name] || (global[name] = {}) : (global[name] || {})[PROTOTYPE] , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] || (exports[PROTOTYPE] = {}) , key, own, out, exp; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; // export native or passed out = (own ? target : source)[key]; // bind timers to global for call from export context exp = IS_BIND && own ? ctx(out, global) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // extend global if(target)redefine(target, key, out, type & $export.U); // export if(exports[key] != out)hide(exports, key, exp); if(IS_PROTO && expProto[key] != out)expProto[key] = out; } }; global.core = core; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }, /* 7 */ /***/ function(module, exports) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(9) , createDesc = __webpack_require__(15); module.exports = __webpack_require__(4) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(10) , IE8_DOM_DEFINE = __webpack_require__(12) , toPrimitive = __webpack_require__(14) , dP = Object.defineProperty; exports.f = __webpack_require__(4) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 11 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(4) && !__webpack_require__(5)(function(){ return Object.defineProperty(__webpack_require__(13)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11) , document = __webpack_require__(2).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(11); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }, /* 15 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(2) , hide = __webpack_require__(8) , has = __webpack_require__(3) , SRC = __webpack_require__(17)('src') , TO_STRING = 'toString' , $toString = Function[TO_STRING] , TPL = ('' + $toString).split(TO_STRING); __webpack_require__(7).inspectSource = function(it){ return $toString.call(it); }; (module.exports = function(O, key, val, safe){ var isFunction = typeof val == 'function'; if(isFunction)has(val, 'name') || hide(val, 'name', key); if(O[key] === val)return; if(isFunction)has(val, SRC) || hide(val, SRC, O[key] ? '' + O[key] : TPL.join(String(key))); if(O === global){ O[key] = val; } else { if(!safe){ delete O[key]; hide(O, key, val); } else { if(O[key])O[key] = val; else hide(O, key, val); } } // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative })(Function.prototype, TO_STRING, function toString(){ return typeof this == 'function' && this[SRC] || $toString.call(this); }); /***/ }, /* 17 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(19); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 19 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var META = __webpack_require__(17)('meta') , isObject = __webpack_require__(11) , has = __webpack_require__(3) , setDesc = __webpack_require__(9).f , id = 0; var isExtensible = Object.isExtensible || function(){ return true; }; var FREEZE = !__webpack_require__(5)(function(){ return isExtensible(Object.preventExtensions({})); }); var setMeta = function(it){ setDesc(it, META, {value: { i: 'O' + ++id, // object ID w: {} // weak collections IDs }}); }; var fastKey = function(it, create){ // return primitive with prefix if(!isObject(it))return typeof it == 'symbol' ? it : (typeof it == 'string' ? 'S' : 'P') + it; if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return 'F'; // not necessary to add metadata if(!create)return 'E'; // add missing metadata setMeta(it); // return object ID } return it[META].i; }; var getWeak = function(it, create){ if(!has(it, META)){ // can't set metadata to uncaught frozen object if(!isExtensible(it))return true; // not necessary to add metadata if(!create)return false; // add missing metadata setMeta(it); // return hash weak collections IDs } return it[META].w; }; // add metadata on freeze-family methods calling var onFreeze = function(it){ if(FREEZE && meta.NEED && isExtensible(it) && !has(it, META))setMeta(it); return it; }; var meta = module.exports = { KEY: META, NEED: false, fastKey: fastKey, getWeak: getWeak, onFreeze: onFreeze }; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(2) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var def = __webpack_require__(9).f , has = __webpack_require__(3) , TAG = __webpack_require__(23)('toStringTag'); module.exports = function(it, tag, stat){ if(it && !has(it = stat ? it : it.prototype, TAG))def(it, TAG, {configurable: true, value: tag}); }; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var store = __webpack_require__(21)('wks') , uid = __webpack_require__(17) , Symbol = __webpack_require__(2).Symbol , USE_SYMBOL = typeof Symbol == 'function'; var $exports = module.exports = function(name){ return store[name] || (store[name] = USE_SYMBOL && Symbol[name] || (USE_SYMBOL ? Symbol : uid)('Symbol.' + name)); }; $exports.store = store; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { exports.f = __webpack_require__(23); /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(2) , core = __webpack_require__(7) , LIBRARY = __webpack_require__(26) , wksExt = __webpack_require__(24) , defineProperty = __webpack_require__(9).f; module.exports = function(name){ var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {}); if(name.charAt(0) != '_' && !(name in $Symbol))defineProperty($Symbol, name, {value: wksExt.f(name)}); }; /***/ }, /* 26 */ /***/ function(module, exports) { module.exports = false; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(28) , toIObject = __webpack_require__(30); module.exports = function(object, el){ var O = toIObject(object) , keys = getKeys(O) , length = keys.length , index = 0 , key; while(length > index)if(O[key = keys[index++]] === el)return key; }; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(29) , enumBugKeys = __webpack_require__(39); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var has = __webpack_require__(3) , toIObject = __webpack_require__(30) , arrayIndexOf = __webpack_require__(34)(false) , IE_PROTO = __webpack_require__(38)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(31) , defined = __webpack_require__(33); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(32); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 32 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 33 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(30) , toLength = __webpack_require__(35) , toIndex = __webpack_require__(37); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(36) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 36 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(36) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var shared = __webpack_require__(21)('keys') , uid = __webpack_require__(17); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; /***/ }, /* 39 */ /***/ function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { // all enumerable object keys, includes symbols var getKeys = __webpack_require__(28) , gOPS = __webpack_require__(41) , pIE = __webpack_require__(42); module.exports = function(it){ var result = getKeys(it) , getSymbols = gOPS.f; if(getSymbols){ var symbols = getSymbols(it) , isEnum = pIE.f , i = 0 , key; while(symbols.length > i)if(isEnum.call(it, key = symbols[i++]))result.push(key); } return result; }; /***/ }, /* 41 */ /***/ function(module, exports) { exports.f = Object.getOwnPropertySymbols; /***/ }, /* 42 */ /***/ function(module, exports) { exports.f = {}.propertyIsEnumerable; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { // 7.2.2 IsArray(argument) var cof = __webpack_require__(32); module.exports = Array.isArray || function isArray(arg){ return cof(arg) == 'Array'; }; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) var anObject = __webpack_require__(10) , dPs = __webpack_require__(45) , enumBugKeys = __webpack_require__(39) , IE_PROTO = __webpack_require__(38)('IE_PROTO') , Empty = function(){ /* empty */ } , PROTOTYPE = 'prototype'; // Create object with fake `null` prototype: use iframe Object with cleared prototype var createDict = function(){ // Thrash, waste and sodomy: IE GC bug var iframe = __webpack_require__(13)('iframe') , i = enumBugKeys.length , lt = '<' , gt = '>' , iframeDocument; iframe.style.display = 'none'; __webpack_require__(46).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(lt + 'script' + gt + 'document.F=Object' + lt + '/script' + gt); iframeDocument.close(); createDict = iframeDocument.F; while(i--)delete createDict[PROTOTYPE][enumBugKeys[i]]; return createDict(); }; module.exports = Object.create || function create(O, Properties){ var result; if(O !== null){ Empty[PROTOTYPE] = anObject(O); result = new Empty; Empty[PROTOTYPE] = null; // add "__proto__" for Object.getPrototypeOf polyfill result[IE_PROTO] = O; } else result = createDict(); return Properties === undefined ? result : dPs(result, Properties); }; /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(9) , anObject = __webpack_require__(10) , getKeys = __webpack_require__(28); module.exports = __webpack_require__(4) ? Object.defineProperties : function defineProperties(O, Properties){ anObject(O); var keys = getKeys(Properties) , length = keys.length , i = 0 , P; while(length > i)dP.f(O, P = keys[i++], Properties[P]); return O; }; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(2).document && document.documentElement; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window var toIObject = __webpack_require__(30) , gOPN = __webpack_require__(48).f , toString = {}.toString; var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames ? Object.getOwnPropertyNames(window) : []; var getWindowNames = function(it){ try { return gOPN(it); } catch(e){ return windowNames.slice(); } }; module.exports.f = function getOwnPropertyNames(it){ return windowNames && toString.call(it) == '[object Window]' ? getWindowNames(it) : gOPN(toIObject(it)); }; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.7 / 15.2.3.4 Object.getOwnPropertyNames(O) var $keys = __webpack_require__(29) , hiddenKeys = __webpack_require__(39).concat('length', 'prototype'); exports.f = Object.getOwnPropertyNames || function getOwnPropertyNames(O){ return $keys(O, hiddenKeys); }; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var pIE = __webpack_require__(42) , createDesc = __webpack_require__(15) , toIObject = __webpack_require__(30) , toPrimitive = __webpack_require__(14) , has = __webpack_require__(3) , IE8_DOM_DEFINE = __webpack_require__(12) , gOPD = Object.getOwnPropertyDescriptor; exports.f = __webpack_require__(4) ? gOPD : function getOwnPropertyDescriptor(O, P){ O = toIObject(O); P = toPrimitive(P, true); if(IE8_DOM_DEFINE)try { return gOPD(O, P); } catch(e){ /* empty */ } if(has(O, P))return createDesc(!pIE.f.call(O, P), O[P]); }; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6); // 19.1.2.4 / 15.2.3.6 Object.defineProperty(O, P, Attributes) $export($export.S + $export.F * !__webpack_require__(4), 'Object', {defineProperty: __webpack_require__(9).f}); /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6); // 19.1.2.3 / 15.2.3.7 Object.defineProperties(O, Properties) $export($export.S + $export.F * !__webpack_require__(4), 'Object', {defineProperties: __webpack_require__(45)}); /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.6 Object.getOwnPropertyDescriptor(O, P) var toIObject = __webpack_require__(30) , $getOwnPropertyDescriptor = __webpack_require__(49).f; __webpack_require__(53)('getOwnPropertyDescriptor', function(){ return function getOwnPropertyDescriptor(it, key){ return $getOwnPropertyDescriptor(toIObject(it), key); }; }); /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(6) , core = __webpack_require__(7) , fails = __webpack_require__(5); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) // 19.1.2.2 / 15.2.3.5 Object.create(O [, Properties]) $export($export.S, 'Object', {create: __webpack_require__(44)}); /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 Object.getPrototypeOf(O) var toObject = __webpack_require__(56) , $getPrototypeOf = __webpack_require__(57); __webpack_require__(53)('getPrototypeOf', function(){ return function getPrototypeOf(it){ return $getPrototypeOf(toObject(it)); }; }); /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(33); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.9 / 15.2.3.2 Object.getPrototypeOf(O) var has = __webpack_require__(3) , toObject = __webpack_require__(56) , IE_PROTO = __webpack_require__(38)('IE_PROTO') , ObjectProto = Object.prototype; module.exports = Object.getPrototypeOf || function(O){ O = toObject(O); if(has(O, IE_PROTO))return O[IE_PROTO]; if(typeof O.constructor == 'function' && O instanceof O.constructor){ return O.constructor.prototype; } return O instanceof Object ? ObjectProto : null; }; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(56) , $keys = __webpack_require__(28); __webpack_require__(53)('keys', function(){ return function keys(it){ return $keys(toObject(it)); }; }); /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.7 Object.getOwnPropertyNames(O) __webpack_require__(53)('getOwnPropertyNames', function(){ return __webpack_require__(47).f; }); /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.5 Object.freeze(O) var isObject = __webpack_require__(11) , meta = __webpack_require__(20).onFreeze; __webpack_require__(53)('freeze', function($freeze){ return function freeze(it){ return $freeze && isObject(it) ? $freeze(meta(it)) : it; }; }); /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.17 Object.seal(O) var isObject = __webpack_require__(11) , meta = __webpack_require__(20).onFreeze; __webpack_require__(53)('seal', function($seal){ return function seal(it){ return $seal && isObject(it) ? $seal(meta(it)) : it; }; }); /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.15 Object.preventExtensions(O) var isObject = __webpack_require__(11) , meta = __webpack_require__(20).onFreeze; __webpack_require__(53)('preventExtensions', function($preventExtensions){ return function preventExtensions(it){ return $preventExtensions && isObject(it) ? $preventExtensions(meta(it)) : it; }; }); /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.12 Object.isFrozen(O) var isObject = __webpack_require__(11); __webpack_require__(53)('isFrozen', function($isFrozen){ return function isFrozen(it){ return isObject(it) ? $isFrozen ? $isFrozen(it) : false : true; }; }); /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.13 Object.isSealed(O) var isObject = __webpack_require__(11); __webpack_require__(53)('isSealed', function($isSealed){ return function isSealed(it){ return isObject(it) ? $isSealed ? $isSealed(it) : false : true; }; }); /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.11 Object.isExtensible(O) var isObject = __webpack_require__(11); __webpack_require__(53)('isExtensible', function($isExtensible){ return function isExtensible(it){ return isObject(it) ? $isExtensible ? $isExtensible(it) : true : false; }; }); /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.1 Object.assign(target, source) var $export = __webpack_require__(6); $export($export.S + $export.F, 'Object', {assign: __webpack_require__(67)}); /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 19.1.2.1 Object.assign(target, source, ...) var getKeys = __webpack_require__(28) , gOPS = __webpack_require__(41) , pIE = __webpack_require__(42) , toObject = __webpack_require__(56) , IObject = __webpack_require__(31) , $assign = Object.assign; // should work with symbols and should have deterministic property order (V8 bug) module.exports = !$assign || __webpack_require__(5)(function(){ var A = {} , B = {} , S = Symbol() , K = 'abcdefghijklmnopqrst'; A[S] = 7; K.split('').forEach(function(k){ B[k] = k; }); return $assign({}, A)[S] != 7 || Object.keys($assign({}, B)).join('') != K; }) ? function assign(target, source){ // eslint-disable-line no-unused-vars var T = toObject(target) , aLen = arguments.length , index = 1 , getSymbols = gOPS.f , isEnum = pIE.f; while(aLen > index){ var S = IObject(arguments[index++]) , keys = getSymbols ? getKeys(S).concat(getSymbols(S)) : getKeys(S) , length = keys.length , j = 0 , key; while(length > j)if(isEnum.call(S, key = keys[j++]))T[key] = S[key]; } return T; } : $assign; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.10 Object.is(value1, value2) var $export = __webpack_require__(6); $export($export.S, 'Object', {is: __webpack_require__(69)}); /***/ }, /* 69 */ /***/ function(module, exports) { // 7.2.9 SameValue(x, y) module.exports = Object.is || function is(x, y){ return x === y ? x !== 0 || 1 / x === 1 / y : x != x && y != y; }; /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { // 19.1.3.19 Object.setPrototypeOf(O, proto) var $export = __webpack_require__(6); $export($export.S, 'Object', {setPrototypeOf: __webpack_require__(71).set}); /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { // Works with __proto__ only. Old v8 can't work with null proto objects. /* eslint-disable no-proto */ var isObject = __webpack_require__(11) , anObject = __webpack_require__(10); var check = function(O, proto){ anObject(O); if(!isObject(proto) && proto !== null)throw TypeError(proto + ": can't set as prototype!"); }; module.exports = { set: Object.setPrototypeOf || ('__proto__' in {} ? // eslint-disable-line function(test, buggy, set){ try { set = __webpack_require__(18)(Function.call, __webpack_require__(49).f(Object.prototype, '__proto__').set, 2); set(test, []); buggy = !(test instanceof Array); } catch(e){ buggy = true; } return function setPrototypeOf(O, proto){ check(O, proto); if(buggy)O.__proto__ = proto; else set(O, proto); return O; }; }({}, false) : undefined), check: check }; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 19.1.3.6 Object.prototype.toString() var classof = __webpack_require__(73) , test = {}; test[__webpack_require__(23)('toStringTag')] = 'z'; if(test + '' != '[object z]'){ __webpack_require__(16)(Object.prototype, 'toString', function toString(){ return '[object ' + classof(this) + ']'; }, true); } /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { // getting tag from 19.1.3.6 Object.prototype.toString() var cof = __webpack_require__(32) , TAG = __webpack_require__(23)('toStringTag') // ES3 wrong here , ARG = cof(function(){ return arguments; }()) == 'Arguments'; // fallback for IE11 Script Access Denied error var tryGet = function(it, key){ try { return it[key]; } catch(e){ /* empty */ } }; module.exports = function(it){ var O, T, B; return it === undefined ? 'Undefined' : it === null ? 'Null' // @@toStringTag case : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T // builtinTag case : ARG ? cof(O) // ES3 arguments fallback : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B; }; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { // 19.2.3.2 / 15.3.4.5 Function.prototype.bind(thisArg, args...) var $export = __webpack_require__(6); $export($export.P, 'Function', {bind: __webpack_require__(75)}); /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var aFunction = __webpack_require__(19) , isObject = __webpack_require__(11) , invoke = __webpack_require__(76) , arraySlice = [].slice , factories = {}; var construct = function(F, len, args){ if(!(len in factories)){ for(var n = [], i = 0; i < len; i++)n[i] = 'a[' + i + ']'; factories[len] = Function('F,a', 'return new F(' + n.join(',') + ')'); } return factories[len](F, args); }; module.exports = Function.bind || function bind(that /*, args... */){ var fn = aFunction(this) , partArgs = arraySlice.call(arguments, 1); var bound = function(/* args... */){ var args = partArgs.concat(arraySlice.call(arguments)); return this instanceof bound ? construct(fn, args.length, args) : invoke(fn, args, that); }; if(isObject(fn.prototype))bound.prototype = fn.prototype; return bound; }; /***/ }, /* 76 */ /***/ function(module, exports) { // fast apply, http://jsperf.lnkit.com/fast-apply/5 module.exports = function(fn, args, that){ var un = that === undefined; switch(args.length){ case 0: return un ? fn() : fn.call(that); case 1: return un ? fn(args[0]) : fn.call(that, args[0]); case 2: return un ? fn(args[0], args[1]) : fn.call(that, args[0], args[1]); case 3: return un ? fn(args[0], args[1], args[2]) : fn.call(that, args[0], args[1], args[2]); case 4: return un ? fn(args[0], args[1], args[2], args[3]) : fn.call(that, args[0], args[1], args[2], args[3]); } return fn.apply(that, args); }; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(9).f , createDesc = __webpack_require__(15) , has = __webpack_require__(3) , FProto = Function.prototype , nameRE = /^\s*function ([^ (]*)/ , NAME = 'name'; var isExtensible = Object.isExtensible || function(){ return true; }; // 19.2.4.2 name NAME in FProto || __webpack_require__(4) && dP(FProto, NAME, { configurable: true, get: function(){ try { var that = this , name = ('' + that).match(nameRE)[1]; has(that, NAME) || !isExtensible(that) || dP(that, NAME, createDesc(5, name)); return name; } catch(e){ return ''; } } }); /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var isObject = __webpack_require__(11) , getPrototypeOf = __webpack_require__(57) , HAS_INSTANCE = __webpack_require__(23)('hasInstance') , FunctionProto = Function.prototype; // 19.2.3.6 Function.prototype[@@hasInstance](V) if(!(HAS_INSTANCE in FunctionProto))__webpack_require__(9).f(FunctionProto, HAS_INSTANCE, {value: function(O){ if(typeof this != 'function' || !isObject(O))return false; if(!isObject(this.prototype))return O instanceof this; // for environment w/o native `@@hasInstance` logic enough `instanceof`, but add this: while(O = getPrototypeOf(O))if(this.prototype === O)return true; return false; }}); /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = __webpack_require__(2) , has = __webpack_require__(3) , cof = __webpack_require__(32) , inheritIfRequired = __webpack_require__(80) , toPrimitive = __webpack_require__(14) , fails = __webpack_require__(5) , gOPN = __webpack_require__(48).f , gOPD = __webpack_require__(49).f , dP = __webpack_require__(9).f , $trim = __webpack_require__(81).trim , NUMBER = 'Number' , $Number = global[NUMBER] , Base = $Number , proto = $Number.prototype // Opera ~12 has broken Object#toString , BROKEN_COF = cof(__webpack_require__(44)(proto)) == NUMBER , TRIM = 'trim' in String.prototype; // 7.1.3 ToNumber(argument) var toNumber = function(argument){ var it = toPrimitive(argument, false); if(typeof it == 'string' && it.length > 2){ it = TRIM ? it.trim() : $trim(it, 3); var first = it.charCodeAt(0) , third, radix, maxCode; if(first === 43 || first === 45){ third = it.charCodeAt(2); if(third === 88 || third === 120)return NaN; // Number('+0x1') should be NaN, old V8 fix } else if(first === 48){ switch(it.charCodeAt(1)){ case 66 : case 98 : radix = 2; maxCode = 49; break; // fast equal /^0b[01]+$/i case 79 : case 111 : radix = 8; maxCode = 55; break; // fast equal /^0o[0-7]+$/i default : return +it; } for(var digits = it.slice(2), i = 0, l = digits.length, code; i < l; i++){ code = digits.charCodeAt(i); // parseInt parses a string to a first unavailable symbol // but ToNumber should return NaN if a string contains unavailable symbols if(code < 48 || code > maxCode)return NaN; } return parseInt(digits, radix); } } return +it; }; if(!$Number(' 0o1') || !$Number('0b1') || $Number('+0x1')){ $Number = function Number(value){ var it = arguments.length < 1 ? 0 : value , that = this; return that instanceof $Number // check on 1..constructor(foo) case && (BROKEN_COF ? fails(function(){ proto.valueOf.call(that); }) : cof(that) != NUMBER) ? inheritIfRequired(new Base(toNumber(it)), that, $Number) : toNumber(it); }; for(var keys = __webpack_require__(4) ? gOPN(Base) : ( // ES3: 'MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,' + // ES6 (in case, if modules with ES6 Number statics required before): 'EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,' + 'MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger' ).split(','), j = 0, key; keys.length > j; j++){ if(has(Base, key = keys[j]) && !has($Number, key)){ dP($Number, key, gOPD(Base, key)); } } $Number.prototype = proto; proto.constructor = $Number; __webpack_require__(16)(global, NUMBER, $Number); } /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11) , setPrototypeOf = __webpack_require__(71).set; module.exports = function(that, target, C){ var P, S = target.constructor; if(S !== C && typeof S == 'function' && (P = S.prototype) !== C.prototype && isObject(P) && setPrototypeOf){ setPrototypeOf(that, P); } return that; }; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , defined = __webpack_require__(33) , fails = __webpack_require__(5) , spaces = __webpack_require__(82) , space = '[' + spaces + ']' , non = '\u200b\u0085' , ltrim = RegExp('^' + space + space + '*') , rtrim = RegExp(space + space + '*$'); var exporter = function(KEY, exec, ALIAS){ var exp = {}; var FORCE = fails(function(){ return !!spaces[KEY]() || non[KEY]() != non; }); var fn = exp[KEY] = FORCE ? exec(trim) : spaces[KEY]; if(ALIAS)exp[ALIAS] = fn; $export($export.P + $export.F * FORCE, 'String', exp); }; // 1 -> String#trimLeft // 2 -> String#trimRight // 3 -> String#trim var trim = exporter.trim = function(string, TYPE){ string = String(defined(string)); if(TYPE & 1)string = string.replace(ltrim, ''); if(TYPE & 2)string = string.replace(rtrim, ''); return string; }; module.exports = exporter; /***/ }, /* 82 */ /***/ function(module, exports) { module.exports = '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003' + '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF'; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , toInteger = __webpack_require__(36) , aNumberValue = __webpack_require__(84) , repeat = __webpack_require__(85) , $toFixed = 1..toFixed , floor = Math.floor , data = [0, 0, 0, 0, 0, 0] , ERROR = 'Number.toFixed: incorrect invocation!' , ZERO = '0'; var multiply = function(n, c){ var i = -1 , c2 = c; while(++i < 6){ c2 += n * data[i]; data[i] = c2 % 1e7; c2 = floor(c2 / 1e7); } }; var divide = function(n){ var i = 6 , c = 0; while(--i >= 0){ c += data[i]; data[i] = floor(c / n); c = (c % n) * 1e7; } }; var numToString = function(){ var i = 6 , s = ''; while(--i >= 0){ if(s !== '' || i === 0 || data[i] !== 0){ var t = String(data[i]); s = s === '' ? t : s + repeat.call(ZERO, 7 - t.length) + t; } } return s; }; var pow = function(x, n, acc){ return n === 0 ? acc : n % 2 === 1 ? pow(x, n - 1, acc * x) : pow(x * x, n / 2, acc); }; var log = function(x){ var n = 0 , x2 = x; while(x2 >= 4096){ n += 12; x2 /= 4096; } while(x2 >= 2){ n += 1; x2 /= 2; } return n; }; $export($export.P + $export.F * (!!$toFixed && ( 0.00008.toFixed(3) !== '0.000' || 0.9.toFixed(0) !== '1' || 1.255.toFixed(2) !== '1.25' || 1000000000000000128..toFixed(0) !== '1000000000000000128' ) || !__webpack_require__(5)(function(){ // V8 ~ Android 4.3- $toFixed.call({}); })), 'Number', { toFixed: function toFixed(fractionDigits){ var x = aNumberValue(this, ERROR) , f = toInteger(fractionDigits) , s = '' , m = ZERO , e, z, j, k; if(f < 0 || f > 20)throw RangeError(ERROR); if(x != x)return 'NaN'; if(x <= -1e21 || x >= 1e21)return String(x); if(x < 0){ s = '-'; x = -x; } if(x > 1e-21){ e = log(x * pow(2, 69, 1)) - 69; z = e < 0 ? x * pow(2, -e, 1) : x / pow(2, e, 1); z *= 0x10000000000000; e = 52 - e; if(e > 0){ multiply(0, z); j = f; while(j >= 7){ multiply(1e7, 0); j -= 7; } multiply(pow(10, j, 1), 0); j = e - 1; while(j >= 23){ divide(1 << 23); j -= 23; } divide(1 << j); multiply(1, 1); divide(2); m = numToString(); } else { multiply(0, z); multiply(1 << -e, 0); m = numToString() + repeat.call(ZERO, f); } } if(f > 0){ k = m.length; m = s + (k <= f ? '0.' + repeat.call(ZERO, f - k) + m : m.slice(0, k - f) + '.' + m.slice(k - f)); } else { m = s + m; } return m; } }); /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { var cof = __webpack_require__(32); module.exports = function(it, msg){ if(typeof it != 'number' && cof(it) != 'Number')throw TypeError(msg); return +it; }; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var toInteger = __webpack_require__(36) , defined = __webpack_require__(33); module.exports = function repeat(count){ var str = String(defined(this)) , res = '' , n = toInteger(count); if(n < 0 || n == Infinity)throw RangeError("Count can't be negative"); for(;n > 0; (n >>>= 1) && (str += str))if(n & 1)res += str; return res; }; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $fails = __webpack_require__(5) , aNumberValue = __webpack_require__(84) , $toPrecision = 1..toPrecision; $export($export.P + $export.F * ($fails(function(){ // IE7- return $toPrecision.call(1, undefined) !== '1'; }) || !$fails(function(){ // V8 ~ Android 4.3- $toPrecision.call({}); })), 'Number', { toPrecision: function toPrecision(precision){ var that = aNumberValue(this, 'Number#toPrecision: incorrect invocation!'); return precision === undefined ? $toPrecision.call(that) : $toPrecision.call(that, precision); } }); /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.1 Number.EPSILON var $export = __webpack_require__(6); $export($export.S, 'Number', {EPSILON: Math.pow(2, -52)}); /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.2 Number.isFinite(number) var $export = __webpack_require__(6) , _isFinite = __webpack_require__(2).isFinite; $export($export.S, 'Number', { isFinite: function isFinite(it){ return typeof it == 'number' && _isFinite(it); } }); /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.3 Number.isInteger(number) var $export = __webpack_require__(6); $export($export.S, 'Number', {isInteger: __webpack_require__(90)}); /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.3 Number.isInteger(number) var isObject = __webpack_require__(11) , floor = Math.floor; module.exports = function isInteger(it){ return !isObject(it) && isFinite(it) && floor(it) === it; }; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.4 Number.isNaN(number) var $export = __webpack_require__(6); $export($export.S, 'Number', { isNaN: function isNaN(number){ return number != number; } }); /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.5 Number.isSafeInteger(number) var $export = __webpack_require__(6) , isInteger = __webpack_require__(90) , abs = Math.abs; $export($export.S, 'Number', { isSafeInteger: function isSafeInteger(number){ return isInteger(number) && abs(number) <= 0x1fffffffffffff; } }); /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.6 Number.MAX_SAFE_INTEGER var $export = __webpack_require__(6); $export($export.S, 'Number', {MAX_SAFE_INTEGER: 0x1fffffffffffff}); /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { // 20.1.2.10 Number.MIN_SAFE_INTEGER var $export = __webpack_require__(6); $export($export.S, 'Number', {MIN_SAFE_INTEGER: -0x1fffffffffffff}); /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , $parseFloat = __webpack_require__(96); // 20.1.2.12 Number.parseFloat(string) $export($export.S + $export.F * (Number.parseFloat != $parseFloat), 'Number', {parseFloat: $parseFloat}); /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { var $parseFloat = __webpack_require__(2).parseFloat , $trim = __webpack_require__(81).trim; module.exports = 1 / $parseFloat(__webpack_require__(82) + '-0') !== -Infinity ? function parseFloat(str){ var string = $trim(String(str), 3) , result = $parseFloat(string); return result === 0 && string.charAt(0) == '-' ? -0 : result; } : $parseFloat; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , $parseInt = __webpack_require__(98); // 20.1.2.13 Number.parseInt(string, radix) $export($export.S + $export.F * (Number.parseInt != $parseInt), 'Number', {parseInt: $parseInt}); /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { var $parseInt = __webpack_require__(2).parseInt , $trim = __webpack_require__(81).trim , ws = __webpack_require__(82) , hex = /^[\-+]?0[xX]/; module.exports = $parseInt(ws + '08') !== 8 || $parseInt(ws + '0x16') !== 22 ? function parseInt(str, radix){ var string = $trim(String(str), 3); return $parseInt(string, (radix >>> 0) || (hex.test(string) ? 16 : 10)); } : $parseInt; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , $parseInt = __webpack_require__(98); // 18.2.5 parseInt(string, radix) $export($export.G + $export.F * (parseInt != $parseInt), {parseInt: $parseInt}); /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , $parseFloat = __webpack_require__(96); // 18.2.4 parseFloat(string) $export($export.G + $export.F * (parseFloat != $parseFloat), {parseFloat: $parseFloat}); /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.3 Math.acosh(x) var $export = __webpack_require__(6) , log1p = __webpack_require__(102) , sqrt = Math.sqrt , $acosh = Math.acosh; $export($export.S + $export.F * !($acosh // V8 bug: https://code.google.com/p/v8/issues/detail?id=3509 && Math.floor($acosh(Number.MAX_VALUE)) == 710 // Tor Browser bug: Math.acosh(Infinity) -> NaN && $acosh(Infinity) == Infinity ), 'Math', { acosh: function acosh(x){ return (x = +x) < 1 ? NaN : x > 94906265.62425156 ? Math.log(x) + Math.LN2 : log1p(x - 1 + sqrt(x - 1) * sqrt(x + 1)); } }); /***/ }, /* 102 */ /***/ function(module, exports) { // 20.2.2.20 Math.log1p(x) module.exports = Math.log1p || function log1p(x){ return (x = +x) > -1e-8 && x < 1e-8 ? x - x * x / 2 : Math.log(1 + x); }; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.5 Math.asinh(x) var $export = __webpack_require__(6) , $asinh = Math.asinh; function asinh(x){ return !isFinite(x = +x) || x == 0 ? x : x < 0 ? -asinh(-x) : Math.log(x + Math.sqrt(x * x + 1)); } // Tor Browser bug: Math.asinh(0) -> -0 $export($export.S + $export.F * !($asinh && 1 / $asinh(0) > 0), 'Math', {asinh: asinh}); /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.7 Math.atanh(x) var $export = __webpack_require__(6) , $atanh = Math.atanh; // Tor Browser bug: Math.atanh(-0) -> 0 $export($export.S + $export.F * !($atanh && 1 / $atanh(-0) < 0), 'Math', { atanh: function atanh(x){ return (x = +x) == 0 ? x : Math.log((1 + x) / (1 - x)) / 2; } }); /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.9 Math.cbrt(x) var $export = __webpack_require__(6) , sign = __webpack_require__(106); $export($export.S, 'Math', { cbrt: function cbrt(x){ return sign(x = +x) * Math.pow(Math.abs(x), 1 / 3); } }); /***/ }, /* 106 */ /***/ function(module, exports) { // 20.2.2.28 Math.sign(x) module.exports = Math.sign || function sign(x){ return (x = +x) == 0 || x != x ? x : x < 0 ? -1 : 1; }; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.11 Math.clz32(x) var $export = __webpack_require__(6); $export($export.S, 'Math', { clz32: function clz32(x){ return (x >>>= 0) ? 31 - Math.floor(Math.log(x + 0.5) * Math.LOG2E) : 32; } }); /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.12 Math.cosh(x) var $export = __webpack_require__(6) , exp = Math.exp; $export($export.S, 'Math', { cosh: function cosh(x){ return (exp(x = +x) + exp(-x)) / 2; } }); /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.14 Math.expm1(x) var $export = __webpack_require__(6) , $expm1 = __webpack_require__(110); $export($export.S + $export.F * ($expm1 != Math.expm1), 'Math', {expm1: $expm1}); /***/ }, /* 110 */ /***/ function(module, exports) { // 20.2.2.14 Math.expm1(x) var $expm1 = Math.expm1; module.exports = (!$expm1 // Old FF bug || $expm1(10) > 22025.465794806719 || $expm1(10) < 22025.4657948067165168 // Tor Browser bug || $expm1(-2e-17) != -2e-17 ) ? function expm1(x){ return (x = +x) == 0 ? x : x > -1e-6 && x < 1e-6 ? x + x * x / 2 : Math.exp(x) - 1; } : $expm1; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.16 Math.fround(x) var $export = __webpack_require__(6) , sign = __webpack_require__(106) , pow = Math.pow , EPSILON = pow(2, -52) , EPSILON32 = pow(2, -23) , MAX32 = pow(2, 127) * (2 - EPSILON32) , MIN32 = pow(2, -126); var roundTiesToEven = function(n){ return n + 1 / EPSILON - 1 / EPSILON; }; $export($export.S, 'Math', { fround: function fround(x){ var $abs = Math.abs(x) , $sign = sign(x) , a, result; if($abs < MIN32)return $sign * roundTiesToEven($abs / MIN32 / EPSILON32) * MIN32 * EPSILON32; a = (1 + EPSILON32 / EPSILON) * $abs; result = a - (a - $abs); if(result > MAX32 || result != result)return $sign * Infinity; return $sign * result; } }); /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.17 Math.hypot([value1[, value2[, … ]]]) var $export = __webpack_require__(6) , abs = Math.abs; $export($export.S, 'Math', { hypot: function hypot(value1, value2){ // eslint-disable-line no-unused-vars var sum = 0 , i = 0 , aLen = arguments.length , larg = 0 , arg, div; while(i < aLen){ arg = abs(arguments[i++]); if(larg < arg){ div = larg / arg; sum = sum * div * div + 1; larg = arg; } else if(arg > 0){ div = arg / larg; sum += div * div; } else sum += arg; } return larg === Infinity ? Infinity : larg * Math.sqrt(sum); } }); /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.18 Math.imul(x, y) var $export = __webpack_require__(6) , $imul = Math.imul; // some WebKit versions fails with big numbers, some has wrong arity $export($export.S + $export.F * __webpack_require__(5)(function(){ return $imul(0xffffffff, 5) != -5 || $imul.length != 2; }), 'Math', { imul: function imul(x, y){ var UINT16 = 0xffff , xn = +x , yn = +y , xl = UINT16 & xn , yl = UINT16 & yn; return 0 | xl * yl + ((UINT16 & xn >>> 16) * yl + xl * (UINT16 & yn >>> 16) << 16 >>> 0); } }); /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.21 Math.log10(x) var $export = __webpack_require__(6); $export($export.S, 'Math', { log10: function log10(x){ return Math.log(x) / Math.LN10; } }); /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.20 Math.log1p(x) var $export = __webpack_require__(6); $export($export.S, 'Math', {log1p: __webpack_require__(102)}); /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.22 Math.log2(x) var $export = __webpack_require__(6); $export($export.S, 'Math', { log2: function log2(x){ return Math.log(x) / Math.LN2; } }); /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.28 Math.sign(x) var $export = __webpack_require__(6); $export($export.S, 'Math', {sign: __webpack_require__(106)}); /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.30 Math.sinh(x) var $export = __webpack_require__(6) , expm1 = __webpack_require__(110) , exp = Math.exp; // V8 near Chromium 38 has a problem with very small numbers $export($export.S + $export.F * __webpack_require__(5)(function(){ return !Math.sinh(-2e-17) != -2e-17; }), 'Math', { sinh: function sinh(x){ return Math.abs(x = +x) < 1 ? (expm1(x) - expm1(-x)) / 2 : (exp(x - 1) - exp(-x - 1)) * (Math.E / 2); } }); /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.33 Math.tanh(x) var $export = __webpack_require__(6) , expm1 = __webpack_require__(110) , exp = Math.exp; $export($export.S, 'Math', { tanh: function tanh(x){ var a = expm1(x = +x) , b = expm1(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (exp(x) + exp(-x)); } }); /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { // 20.2.2.34 Math.trunc(x) var $export = __webpack_require__(6); $export($export.S, 'Math', { trunc: function trunc(it){ return (it > 0 ? Math.floor : Math.ceil)(it); } }); /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , toIndex = __webpack_require__(37) , fromCharCode = String.fromCharCode , $fromCodePoint = String.fromCodePoint; // length should be 1, old FF problem $export($export.S + $export.F * (!!$fromCodePoint && $fromCodePoint.length != 1), 'String', { // 21.1.2.2 String.fromCodePoint(...codePoints) fromCodePoint: function fromCodePoint(x){ // eslint-disable-line no-unused-vars var res = [] , aLen = arguments.length , i = 0 , code; while(aLen > i){ code = +arguments[i++]; if(toIndex(code, 0x10ffff) !== code)throw RangeError(code + ' is not a valid code point'); res.push(code < 0x10000 ? fromCharCode(code) : fromCharCode(((code -= 0x10000) >> 10) + 0xd800, code % 0x400 + 0xdc00) ); } return res.join(''); } }); /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , toIObject = __webpack_require__(30) , toLength = __webpack_require__(35); $export($export.S, 'String', { // 21.1.2.4 String.raw(callSite, ...substitutions) raw: function raw(callSite){ var tpl = toIObject(callSite.raw) , len = toLength(tpl.length) , aLen = arguments.length , res = [] , i = 0; while(len > i){ res.push(String(tpl[i++])); if(i < aLen)res.push(String(arguments[i])); } return res.join(''); } }); /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 21.1.3.25 String.prototype.trim() __webpack_require__(81)('trim', function($trim){ return function trim(){ return $trim(this, 3); }; }); /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $at = __webpack_require__(125)(false); $export($export.P, 'String', { // 21.1.3.3 String.prototype.codePointAt(pos) codePointAt: function codePointAt(pos){ return $at(this, pos); } }); /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(36) , defined = __webpack_require__(33); // true -> String#at // false -> String#codePointAt module.exports = function(TO_STRING){ return function(that, pos){ var s = String(defined(that)) , i = toInteger(pos) , l = s.length , a, b; if(i < 0 || i >= l)return TO_STRING ? '' : undefined; a = s.charCodeAt(i); return a < 0xd800 || a > 0xdbff || i + 1 === l || (b = s.charCodeAt(i + 1)) < 0xdc00 || b > 0xdfff ? TO_STRING ? s.charAt(i) : a : TO_STRING ? s.slice(i, i + 2) : (a - 0xd800 << 10) + (b - 0xdc00) + 0x10000; }; }; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.6 String.prototype.endsWith(searchString [, endPosition]) 'use strict'; var $export = __webpack_require__(6) , toLength = __webpack_require__(35) , context = __webpack_require__(127) , ENDS_WITH = 'endsWith' , $endsWith = ''[ENDS_WITH]; $export($export.P + $export.F * __webpack_require__(129)(ENDS_WITH), 'String', { endsWith: function endsWith(searchString /*, endPosition = @length */){ var that = context(this, searchString, ENDS_WITH) , endPosition = arguments.length > 1 ? arguments[1] : undefined , len = toLength(that.length) , end = endPosition === undefined ? len : Math.min(toLength(endPosition), len) , search = String(searchString); return $endsWith ? $endsWith.call(that, search, end) : that.slice(end - search.length, end) === search; } }); /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { // helper for String#{startsWith, endsWith, includes} var isRegExp = __webpack_require__(128) , defined = __webpack_require__(33); module.exports = function(that, searchString, NAME){ if(isRegExp(searchString))throw TypeError('String#' + NAME + " doesn't accept regex!"); return String(defined(that)); }; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { // 7.2.8 IsRegExp(argument) var isObject = __webpack_require__(11) , cof = __webpack_require__(32) , MATCH = __webpack_require__(23)('match'); module.exports = function(it){ var isRegExp; return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : cof(it) == 'RegExp'); }; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var MATCH = __webpack_require__(23)('match'); module.exports = function(KEY){ var re = /./; try { '/./'[KEY](re); } catch(e){ try { re[MATCH] = false; return !'/./'[KEY](re); } catch(f){ /* empty */ } } return true; }; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.7 String.prototype.includes(searchString, position = 0) 'use strict'; var $export = __webpack_require__(6) , context = __webpack_require__(127) , INCLUDES = 'includes'; $export($export.P + $export.F * __webpack_require__(129)(INCLUDES), 'String', { includes: function includes(searchString /*, position = 0 */){ return !!~context(this, searchString, INCLUDES) .indexOf(searchString, arguments.length > 1 ? arguments[1] : undefined); } }); /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6); $export($export.P, 'String', { // 21.1.3.13 String.prototype.repeat(count) repeat: __webpack_require__(85) }); /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { // 21.1.3.18 String.prototype.startsWith(searchString [, position ]) 'use strict'; var $export = __webpack_require__(6) , toLength = __webpack_require__(35) , context = __webpack_require__(127) , STARTS_WITH = 'startsWith' , $startsWith = ''[STARTS_WITH]; $export($export.P + $export.F * __webpack_require__(129)(STARTS_WITH), 'String', { startsWith: function startsWith(searchString /*, position = 0 */){ var that = context(this, searchString, STARTS_WITH) , index = toLength(Math.min(arguments.length > 1 ? arguments[1] : undefined, that.length)) , search = String(searchString); return $startsWith ? $startsWith.call(that, search, index) : that.slice(index, index + search.length) === search; } }); /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $at = __webpack_require__(125)(true); // 21.1.3.27 String.prototype[@@iterator]() __webpack_require__(134)(String, 'String', function(iterated){ this._t = String(iterated); // target this._i = 0; // next index // 21.1.5.2.1 %StringIteratorPrototype%.next() }, function(){ var O = this._t , index = this._i , point; if(index >= O.length)return {value: undefined, done: true}; point = $at(O, index); this._i += point.length; return {value: point, done: false}; }); /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(26) , $export = __webpack_require__(6) , redefine = __webpack_require__(16) , hide = __webpack_require__(8) , has = __webpack_require__(3) , Iterators = __webpack_require__(135) , $iterCreate = __webpack_require__(136) , setToStringTag = __webpack_require__(22) , getPrototypeOf = __webpack_require__(57) , ITERATOR = __webpack_require__(23)('iterator') , BUGGY = !([].keys && 'next' in [].keys()) // Safari has buggy iterators w/o `next` , FF_ITERATOR = '@@iterator' , KEYS = 'keys' , VALUES = 'values'; var returnThis = function(){ return this; }; module.exports = function(Base, NAME, Constructor, next, DEFAULT, IS_SET, FORCED){ $iterCreate(Constructor, NAME, next); var getMethod = function(kind){ if(!BUGGY && kind in proto)return proto[kind]; switch(kind){ case KEYS: return function keys(){ return new Constructor(this, kind); }; case VALUES: return function values(){ return new Constructor(this, kind); }; } return function entries(){ return new Constructor(this, kind); }; }; var TAG = NAME + ' Iterator' , DEF_VALUES = DEFAULT == VALUES , VALUES_BUG = false , proto = Base.prototype , $native = proto[ITERATOR] || proto[FF_ITERATOR] || DEFAULT && proto[DEFAULT] , $default = $native || getMethod(DEFAULT) , $entries = DEFAULT ? !DEF_VALUES ? $default : getMethod('entries') : undefined , $anyNative = NAME == 'Array' ? proto.entries || $native : $native , methods, key, IteratorPrototype; // Fix native if($anyNative){ IteratorPrototype = getPrototypeOf($anyNative.call(new Base)); if(IteratorPrototype !== Object.prototype){ // Set @@toStringTag to native iterators setToStringTag(IteratorPrototype, TAG, true); // fix for some old engines if(!LIBRARY && !has(IteratorPrototype, ITERATOR))hide(IteratorPrototype, ITERATOR, returnThis); } } // fix Array#{values, @@iterator}.name in V8 / FF if(DEF_VALUES && $native && $native.name !== VALUES){ VALUES_BUG = true; $default = function values(){ return $native.call(this); }; } // Define iterator if((!LIBRARY || FORCED) && (BUGGY || VALUES_BUG || !proto[ITERATOR])){ hide(proto, ITERATOR, $default); } // Plug for library Iterators[NAME] = $default; Iterators[TAG] = returnThis; if(DEFAULT){ methods = { values: DEF_VALUES ? $default : getMethod(VALUES), keys: IS_SET ? $default : getMethod(KEYS), entries: $entries }; if(FORCED)for(key in methods){ if(!(key in proto))redefine(proto, key, methods[key]); } else $export($export.P + $export.F * (BUGGY || VALUES_BUG), NAME, methods); } return methods; }; /***/ }, /* 135 */ /***/ function(module, exports) { module.exports = {}; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var create = __webpack_require__(44) , descriptor = __webpack_require__(15) , setToStringTag = __webpack_require__(22) , IteratorPrototype = {}; // 25.1.2.1.1 %IteratorPrototype%[@@iterator]() __webpack_require__(8)(IteratorPrototype, __webpack_require__(23)('iterator'), function(){ return this; }); module.exports = function(Constructor, NAME, next){ Constructor.prototype = create(IteratorPrototype, {next: descriptor(1, next)}); setToStringTag(Constructor, NAME + ' Iterator'); }; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.2 String.prototype.anchor(name) __webpack_require__(138)('anchor', function(createHTML){ return function anchor(name){ return createHTML(this, 'a', 'name', name); } }); /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , fails = __webpack_require__(5) , defined = __webpack_require__(33) , quot = /"/g; // B.2.3.2.1 CreateHTML(string, tag, attribute, value) var createHTML = function(string, tag, attribute, value) { var S = String(defined(string)) , p1 = '<' + tag; if(attribute !== '')p1 += ' ' + attribute + '="' + String(value).replace(quot, '&quot;') + '"'; return p1 + '>' + S + '</' + tag + '>'; }; module.exports = function(NAME, exec){ var O = {}; O[NAME] = exec(createHTML); $export($export.P + $export.F * fails(function(){ var test = ''[NAME]('"'); return test !== test.toLowerCase() || test.split('"').length > 3; }), 'String', O); }; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.3 String.prototype.big() __webpack_require__(138)('big', function(createHTML){ return function big(){ return createHTML(this, 'big', '', ''); } }); /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.4 String.prototype.blink() __webpack_require__(138)('blink', function(createHTML){ return function blink(){ return createHTML(this, 'blink', '', ''); } }); /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.5 String.prototype.bold() __webpack_require__(138)('bold', function(createHTML){ return function bold(){ return createHTML(this, 'b', '', ''); } }); /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.6 String.prototype.fixed() __webpack_require__(138)('fixed', function(createHTML){ return function fixed(){ return createHTML(this, 'tt', '', ''); } }); /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.7 String.prototype.fontcolor(color) __webpack_require__(138)('fontcolor', function(createHTML){ return function fontcolor(color){ return createHTML(this, 'font', 'color', color); } }); /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.8 String.prototype.fontsize(size) __webpack_require__(138)('fontsize', function(createHTML){ return function fontsize(size){ return createHTML(this, 'font', 'size', size); } }); /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.9 String.prototype.italics() __webpack_require__(138)('italics', function(createHTML){ return function italics(){ return createHTML(this, 'i', '', ''); } }); /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.10 String.prototype.link(url) __webpack_require__(138)('link', function(createHTML){ return function link(url){ return createHTML(this, 'a', 'href', url); } }); /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.11 String.prototype.small() __webpack_require__(138)('small', function(createHTML){ return function small(){ return createHTML(this, 'small', '', ''); } }); /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.12 String.prototype.strike() __webpack_require__(138)('strike', function(createHTML){ return function strike(){ return createHTML(this, 'strike', '', ''); } }); /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.13 String.prototype.sub() __webpack_require__(138)('sub', function(createHTML){ return function sub(){ return createHTML(this, 'sub', '', ''); } }); /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // B.2.3.14 String.prototype.sup() __webpack_require__(138)('sup', function(createHTML){ return function sup(){ return createHTML(this, 'sup', '', ''); } }); /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { // 22.1.2.2 / 15.4.3.2 Array.isArray(arg) var $export = __webpack_require__(6); $export($export.S, 'Array', {isArray: __webpack_require__(43)}); /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ctx = __webpack_require__(18) , $export = __webpack_require__(6) , toObject = __webpack_require__(56) , call = __webpack_require__(153) , isArrayIter = __webpack_require__(154) , toLength = __webpack_require__(35) , createProperty = __webpack_require__(155) , getIterFn = __webpack_require__(156); $export($export.S + $export.F * !__webpack_require__(157)(function(iter){ Array.from(iter); }), 'Array', { // 22.1.2.1 Array.from(arrayLike, mapfn = undefined, thisArg = undefined) from: function from(arrayLike/*, mapfn = undefined, thisArg = undefined*/){ var O = toObject(arrayLike) , C = typeof this == 'function' ? this : Array , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , index = 0 , iterFn = getIterFn(O) , length, result, step, iterator; if(mapping)mapfn = ctx(mapfn, aLen > 2 ? arguments[2] : undefined, 2); // if object isn't iterable or it's array with default iterator - use simple case if(iterFn != undefined && !(C == Array && isArrayIter(iterFn))){ for(iterator = iterFn.call(O), result = new C; !(step = iterator.next()).done; index++){ createProperty(result, index, mapping ? call(iterator, mapfn, [step.value, index], true) : step.value); } } else { length = toLength(O.length); for(result = new C(length); length > index; index++){ createProperty(result, index, mapping ? mapfn(O[index], index) : O[index]); } } result.length = index; return result; } }); /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { // call something on iterator step with safe closing on error var anObject = __webpack_require__(10); module.exports = function(iterator, fn, value, entries){ try { return entries ? fn(anObject(value)[0], value[1]) : fn(value); // 7.4.6 IteratorClose(iterator, completion) } catch(e){ var ret = iterator['return']; if(ret !== undefined)anObject(ret.call(iterator)); throw e; } }; /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { // check on default Array iterator var Iterators = __webpack_require__(135) , ITERATOR = __webpack_require__(23)('iterator') , ArrayProto = Array.prototype; module.exports = function(it){ return it !== undefined && (Iterators.Array === it || ArrayProto[ITERATOR] === it); }; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $defineProperty = __webpack_require__(9) , createDesc = __webpack_require__(15); module.exports = function(object, index, value){ if(index in object)$defineProperty.f(object, index, createDesc(0, value)); else object[index] = value; }; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { var classof = __webpack_require__(73) , ITERATOR = __webpack_require__(23)('iterator') , Iterators = __webpack_require__(135); module.exports = __webpack_require__(7).getIteratorMethod = function(it){ if(it != undefined)return it[ITERATOR] || it['@@iterator'] || Iterators[classof(it)]; }; /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { var ITERATOR = __webpack_require__(23)('iterator') , SAFE_CLOSING = false; try { var riter = [7][ITERATOR](); riter['return'] = function(){ SAFE_CLOSING = true; }; Array.from(riter, function(){ throw 2; }); } catch(e){ /* empty */ } module.exports = function(exec, skipClosing){ if(!skipClosing && !SAFE_CLOSING)return false; var safe = false; try { var arr = [7] , iter = arr[ITERATOR](); iter.next = function(){ return {done: safe = true}; }; arr[ITERATOR] = function(){ return iter; }; exec(arr); } catch(e){ /* empty */ } return safe; }; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , createProperty = __webpack_require__(155); // WebKit Array.of isn't generic $export($export.S + $export.F * __webpack_require__(5)(function(){ function F(){} return !(Array.of.call(F) instanceof F); }), 'Array', { // 22.1.2.3 Array.of( ...items) of: function of(/* ...args */){ var index = 0 , aLen = arguments.length , result = new (typeof this == 'function' ? this : Array)(aLen); while(aLen > index)createProperty(result, index, arguments[index++]); result.length = aLen; return result; } }); /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.13 Array.prototype.join(separator) var $export = __webpack_require__(6) , toIObject = __webpack_require__(30) , arrayJoin = [].join; // fallback for not array-like strings $export($export.P + $export.F * (__webpack_require__(31) != Object || !__webpack_require__(160)(arrayJoin)), 'Array', { join: function join(separator){ return arrayJoin.call(toIObject(this), separator === undefined ? ',' : separator); } }); /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { var fails = __webpack_require__(5); module.exports = function(method, arg){ return !!method && fails(function(){ arg ? method.call(null, function(){}, 1) : method.call(null); }); }; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , html = __webpack_require__(46) , cof = __webpack_require__(32) , toIndex = __webpack_require__(37) , toLength = __webpack_require__(35) , arraySlice = [].slice; // fallback for not array-like ES3 strings and DOM objects $export($export.P + $export.F * __webpack_require__(5)(function(){ if(html)arraySlice.call(html); }), 'Array', { slice: function slice(begin, end){ var len = toLength(this.length) , klass = cof(this); end = end === undefined ? len : end; if(klass == 'Array')return arraySlice.call(this, begin, end); var start = toIndex(begin, len) , upTo = toIndex(end, len) , size = toLength(upTo - start) , cloned = Array(size) , i = 0; for(; i < size; i++)cloned[i] = klass == 'String' ? this.charAt(start + i) : this[start + i]; return cloned; } }); /***/ }, /* 162 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , aFunction = __webpack_require__(19) , toObject = __webpack_require__(56) , fails = __webpack_require__(5) , $sort = [].sort , test = [1, 2, 3]; $export($export.P + $export.F * (fails(function(){ // IE8- test.sort(undefined); }) || !fails(function(){ // V8 bug test.sort(null); // Old WebKit }) || !__webpack_require__(160)($sort)), 'Array', { // 22.1.3.25 Array.prototype.sort(comparefn) sort: function sort(comparefn){ return comparefn === undefined ? $sort.call(toObject(this)) : $sort.call(toObject(this), aFunction(comparefn)); } }); /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $forEach = __webpack_require__(164)(0) , STRICT = __webpack_require__(160)([].forEach, true); $export($export.P + $export.F * !STRICT, 'Array', { // 22.1.3.10 / 15.4.4.18 Array.prototype.forEach(callbackfn [, thisArg]) forEach: function forEach(callbackfn /* , thisArg */){ return $forEach(this, callbackfn, arguments[1]); } }); /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { // 0 -> Array#forEach // 1 -> Array#map // 2 -> Array#filter // 3 -> Array#some // 4 -> Array#every // 5 -> Array#find // 6 -> Array#findIndex var ctx = __webpack_require__(18) , IObject = __webpack_require__(31) , toObject = __webpack_require__(56) , toLength = __webpack_require__(35) , asc = __webpack_require__(165); module.exports = function(TYPE, $create){ var IS_MAP = TYPE == 1 , IS_FILTER = TYPE == 2 , IS_SOME = TYPE == 3 , IS_EVERY = TYPE == 4 , IS_FIND_INDEX = TYPE == 6 , NO_HOLES = TYPE == 5 || IS_FIND_INDEX , create = $create || asc; return function($this, callbackfn, that){ var O = toObject($this) , self = IObject(O) , f = ctx(callbackfn, that, 3) , length = toLength(self.length) , index = 0 , result = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined , val, res; for(;length > index; index++)if(NO_HOLES || index in self){ val = self[index]; res = f(val, index, O); if(TYPE){ if(IS_MAP)result[index] = res; // map else if(res)switch(TYPE){ case 3: return true; // some case 5: return val; // find case 6: return index; // findIndex case 2: result.push(val); // filter } else if(IS_EVERY)return false; // every } } return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : result; }; }; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { // 9.4.2.3 ArraySpeciesCreate(originalArray, length) var speciesConstructor = __webpack_require__(166); module.exports = function(original, length){ return new (speciesConstructor(original))(length); }; /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(11) , isArray = __webpack_require__(43) , SPECIES = __webpack_require__(23)('species'); module.exports = function(original){ var C; if(isArray(original)){ C = original.constructor; // cross-realm fallback if(typeof C == 'function' && (C === Array || isArray(C.prototype)))C = undefined; if(isObject(C)){ C = C[SPECIES]; if(C === null)C = undefined; } } return C === undefined ? Array : C; }; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $map = __webpack_require__(164)(1); $export($export.P + $export.F * !__webpack_require__(160)([].map, true), 'Array', { // 22.1.3.15 / 15.4.4.19 Array.prototype.map(callbackfn [, thisArg]) map: function map(callbackfn /* , thisArg */){ return $map(this, callbackfn, arguments[1]); } }); /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $filter = __webpack_require__(164)(2); $export($export.P + $export.F * !__webpack_require__(160)([].filter, true), 'Array', { // 22.1.3.7 / 15.4.4.20 Array.prototype.filter(callbackfn [, thisArg]) filter: function filter(callbackfn /* , thisArg */){ return $filter(this, callbackfn, arguments[1]); } }); /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $some = __webpack_require__(164)(3); $export($export.P + $export.F * !__webpack_require__(160)([].some, true), 'Array', { // 22.1.3.23 / 15.4.4.17 Array.prototype.some(callbackfn [, thisArg]) some: function some(callbackfn /* , thisArg */){ return $some(this, callbackfn, arguments[1]); } }); /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $every = __webpack_require__(164)(4); $export($export.P + $export.F * !__webpack_require__(160)([].every, true), 'Array', { // 22.1.3.5 / 15.4.4.16 Array.prototype.every(callbackfn [, thisArg]) every: function every(callbackfn /* , thisArg */){ return $every(this, callbackfn, arguments[1]); } }); /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $reduce = __webpack_require__(172); $export($export.P + $export.F * !__webpack_require__(160)([].reduce, true), 'Array', { // 22.1.3.18 / 15.4.4.21 Array.prototype.reduce(callbackfn [, initialValue]) reduce: function reduce(callbackfn /* , initialValue */){ return $reduce(this, callbackfn, arguments.length, arguments[1], false); } }); /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { var aFunction = __webpack_require__(19) , toObject = __webpack_require__(56) , IObject = __webpack_require__(31) , toLength = __webpack_require__(35); module.exports = function(that, callbackfn, aLen, memo, isRight){ aFunction(callbackfn); var O = toObject(that) , self = IObject(O) , length = toLength(O.length) , index = isRight ? length - 1 : 0 , i = isRight ? -1 : 1; if(aLen < 2)for(;;){ if(index in self){ memo = self[index]; index += i; break; } index += i; if(isRight ? index < 0 : length <= index){ throw TypeError('Reduce of empty array with no initial value'); } } for(;isRight ? index >= 0 : length > index; index += i)if(index in self){ memo = callbackfn(memo, self[index], index, O); } return memo; }; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $reduce = __webpack_require__(172); $export($export.P + $export.F * !__webpack_require__(160)([].reduceRight, true), 'Array', { // 22.1.3.19 / 15.4.4.22 Array.prototype.reduceRight(callbackfn [, initialValue]) reduceRight: function reduceRight(callbackfn /* , initialValue */){ return $reduce(this, callbackfn, arguments.length, arguments[1], true); } }); /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $indexOf = __webpack_require__(34)(false) , $native = [].indexOf , NEGATIVE_ZERO = !!$native && 1 / [1].indexOf(1, -0) < 0; $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(160)($native)), 'Array', { // 22.1.3.11 / 15.4.4.14 Array.prototype.indexOf(searchElement [, fromIndex]) indexOf: function indexOf(searchElement /*, fromIndex = 0 */){ return NEGATIVE_ZERO // convert -0 to +0 ? $native.apply(this, arguments) || 0 : $indexOf(this, searchElement, arguments[1]); } }); /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , toIObject = __webpack_require__(30) , toInteger = __webpack_require__(36) , toLength = __webpack_require__(35) , $native = [].lastIndexOf , NEGATIVE_ZERO = !!$native && 1 / [1].lastIndexOf(1, -0) < 0; $export($export.P + $export.F * (NEGATIVE_ZERO || !__webpack_require__(160)($native)), 'Array', { // 22.1.3.14 / 15.4.4.15 Array.prototype.lastIndexOf(searchElement [, fromIndex]) lastIndexOf: function lastIndexOf(searchElement /*, fromIndex = @[*-1] */){ // convert -0 to +0 if(NEGATIVE_ZERO)return $native.apply(this, arguments) || 0; var O = toIObject(this) , length = toLength(O.length) , index = length - 1; if(arguments.length > 1)index = Math.min(index, toInteger(arguments[1])); if(index < 0)index = length + index; for(;index >= 0; index--)if(index in O)if(O[index] === searchElement)return index || 0; return -1; } }); /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) var $export = __webpack_require__(6); $export($export.P, 'Array', {copyWithin: __webpack_require__(177)}); __webpack_require__(178)('copyWithin'); /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.3 Array.prototype.copyWithin(target, start, end = this.length) 'use strict'; var toObject = __webpack_require__(56) , toIndex = __webpack_require__(37) , toLength = __webpack_require__(35); module.exports = [].copyWithin || function copyWithin(target/*= 0*/, start/*= 0, end = @length*/){ var O = toObject(this) , len = toLength(O.length) , to = toIndex(target, len) , from = toIndex(start, len) , end = arguments.length > 2 ? arguments[2] : undefined , count = Math.min((end === undefined ? len : toIndex(end, len)) - from, len - to) , inc = 1; if(from < to && to < from + count){ inc = -1; from += count - 1; to += count - 1; } while(count-- > 0){ if(from in O)O[to] = O[from]; else delete O[to]; to += inc; from += inc; } return O; }; /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.31 Array.prototype[@@unscopables] var UNSCOPABLES = __webpack_require__(23)('unscopables') , ArrayProto = Array.prototype; if(ArrayProto[UNSCOPABLES] == undefined)__webpack_require__(8)(ArrayProto, UNSCOPABLES, {}); module.exports = function(key){ ArrayProto[UNSCOPABLES][key] = true; }; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) var $export = __webpack_require__(6); $export($export.P, 'Array', {fill: __webpack_require__(180)}); __webpack_require__(178)('fill'); /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { // 22.1.3.6 Array.prototype.fill(value, start = 0, end = this.length) 'use strict'; var toObject = __webpack_require__(56) , toIndex = __webpack_require__(37) , toLength = __webpack_require__(35); module.exports = function fill(value /*, start = 0, end = @length */){ var O = toObject(this) , length = toLength(O.length) , aLen = arguments.length , index = toIndex(aLen > 1 ? arguments[1] : undefined, length) , end = aLen > 2 ? arguments[2] : undefined , endPos = end === undefined ? length : toIndex(end, length); while(endPos > index)O[index++] = value; return O; }; /***/ }, /* 181 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.8 Array.prototype.find(predicate, thisArg = undefined) var $export = __webpack_require__(6) , $find = __webpack_require__(164)(5) , KEY = 'find' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { find: function find(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(178)(KEY); /***/ }, /* 182 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 22.1.3.9 Array.prototype.findIndex(predicate, thisArg = undefined) var $export = __webpack_require__(6) , $find = __webpack_require__(164)(6) , KEY = 'findIndex' , forced = true; // Shouldn't skip holes if(KEY in [])Array(1)[KEY](function(){ forced = false; }); $export($export.P + $export.F * forced, 'Array', { findIndex: function findIndex(callbackfn/*, that = undefined */){ return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(178)(KEY); /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var addToUnscopables = __webpack_require__(178) , step = __webpack_require__(184) , Iterators = __webpack_require__(135) , toIObject = __webpack_require__(30); // 22.1.3.4 Array.prototype.entries() // 22.1.3.13 Array.prototype.keys() // 22.1.3.29 Array.prototype.values() // 22.1.3.30 Array.prototype[@@iterator]() module.exports = __webpack_require__(134)(Array, 'Array', function(iterated, kind){ this._t = toIObject(iterated); // target this._i = 0; // next index this._k = kind; // kind // 22.1.5.2.1 %ArrayIteratorPrototype%.next() }, function(){ var O = this._t , kind = this._k , index = this._i++; if(!O || index >= O.length){ this._t = undefined; return step(1); } if(kind == 'keys' )return step(0, index); if(kind == 'values')return step(0, O[index]); return step(0, [index, O[index]]); }, 'values'); // argumentsList[@@iterator] is %ArrayProto_values% (9.4.4.6, 9.4.4.7) Iterators.Arguments = Iterators.Array; addToUnscopables('keys'); addToUnscopables('values'); addToUnscopables('entries'); /***/ }, /* 184 */ /***/ function(module, exports) { module.exports = function(done, value){ return {value: value, done: !!done}; }; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(186)('Array'); /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = __webpack_require__(2) , dP = __webpack_require__(9) , DESCRIPTORS = __webpack_require__(4) , SPECIES = __webpack_require__(23)('species'); module.exports = function(KEY){ var C = global[KEY]; if(DESCRIPTORS && C && !C[SPECIES])dP.f(C, SPECIES, { configurable: true, get: function(){ return this; } }); }; /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(2) , inheritIfRequired = __webpack_require__(80) , dP = __webpack_require__(9).f , gOPN = __webpack_require__(48).f , isRegExp = __webpack_require__(128) , $flags = __webpack_require__(188) , $RegExp = global.RegExp , Base = $RegExp , proto = $RegExp.prototype , re1 = /a/g , re2 = /a/g // "new" creates a new object, old webkit buggy here , CORRECT_NEW = new $RegExp(re1) !== re1; if(__webpack_require__(4) && (!CORRECT_NEW || __webpack_require__(5)(function(){ re2[__webpack_require__(23)('match')] = false; // RegExp constructor can alter flags and IsRegExp works correct with @@match return $RegExp(re1) != re1 || $RegExp(re2) == re2 || $RegExp(re1, 'i') != '/a/i'; }))){ $RegExp = function RegExp(p, f){ var tiRE = this instanceof $RegExp , piRE = isRegExp(p) , fiU = f === undefined; return !tiRE && piRE && p.constructor === $RegExp && fiU ? p : inheritIfRequired(CORRECT_NEW ? new Base(piRE && !fiU ? p.source : p, f) : Base((piRE = p instanceof $RegExp) ? p.source : p, piRE && fiU ? $flags.call(p) : f) , tiRE ? this : proto, $RegExp); }; var proxy = function(key){ key in $RegExp || dP($RegExp, key, { configurable: true, get: function(){ return Base[key]; }, set: function(it){ Base[key] = it; } }); }; for(var keys = gOPN(Base), i = 0; keys.length > i; )proxy(keys[i++]); proto.constructor = $RegExp; $RegExp.prototype = proto; __webpack_require__(16)(global, 'RegExp', $RegExp); } __webpack_require__(186)('RegExp'); /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 21.2.5.3 get RegExp.prototype.flags var anObject = __webpack_require__(10); module.exports = function(){ var that = anObject(this) , result = ''; if(that.global) result += 'g'; if(that.ignoreCase) result += 'i'; if(that.multiline) result += 'm'; if(that.unicode) result += 'u'; if(that.sticky) result += 'y'; return result; }; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; __webpack_require__(190); var anObject = __webpack_require__(10) , $flags = __webpack_require__(188) , DESCRIPTORS = __webpack_require__(4) , TO_STRING = 'toString' , $toString = /./[TO_STRING]; var define = function(fn){ __webpack_require__(16)(RegExp.prototype, TO_STRING, fn, true); }; // 21.2.5.14 RegExp.prototype.toString() if(__webpack_require__(5)(function(){ return $toString.call({source: 'a', flags: 'b'}) != '/a/b'; })){ define(function toString(){ var R = anObject(this); return '/'.concat(R.source, '/', 'flags' in R ? R.flags : !DESCRIPTORS && R instanceof RegExp ? $flags.call(R) : undefined); }); // FF44- RegExp#toString has a wrong name } else if($toString.name != TO_STRING){ define(function toString(){ return $toString.call(this); }); } /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { // 21.2.5.3 get RegExp.prototype.flags() if(__webpack_require__(4) && /./g.flags != 'g')__webpack_require__(9).f(RegExp.prototype, 'flags', { configurable: true, get: __webpack_require__(188) }); /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { // @@match logic __webpack_require__(192)('match', 1, function(defined, MATCH, $match){ // 21.1.3.11 String.prototype.match(regexp) return [function match(regexp){ 'use strict'; var O = defined(this) , fn = regexp == undefined ? undefined : regexp[MATCH]; return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[MATCH](String(O)); }, $match]; }); /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var hide = __webpack_require__(8) , redefine = __webpack_require__(16) , fails = __webpack_require__(5) , defined = __webpack_require__(33) , wks = __webpack_require__(23); module.exports = function(KEY, length, exec){ var SYMBOL = wks(KEY) , fns = exec(defined, SYMBOL, ''[KEY]) , strfn = fns[0] , rxfn = fns[1]; if(fails(function(){ var O = {}; O[SYMBOL] = function(){ return 7; }; return ''[KEY](O) != 7; })){ redefine(String.prototype, KEY, strfn); hide(RegExp.prototype, SYMBOL, length == 2 // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue) // 21.2.5.11 RegExp.prototype[@@split](string, limit) ? function(string, arg){ return rxfn.call(string, this, arg); } // 21.2.5.6 RegExp.prototype[@@match](string) // 21.2.5.9 RegExp.prototype[@@search](string) : function(string){ return rxfn.call(string, this); } ); } }; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { // @@replace logic __webpack_require__(192)('replace', 2, function(defined, REPLACE, $replace){ // 21.1.3.14 String.prototype.replace(searchValue, replaceValue) return [function replace(searchValue, replaceValue){ 'use strict'; var O = defined(this) , fn = searchValue == undefined ? undefined : searchValue[REPLACE]; return fn !== undefined ? fn.call(searchValue, O, replaceValue) : $replace.call(String(O), searchValue, replaceValue); }, $replace]; }); /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { // @@search logic __webpack_require__(192)('search', 1, function(defined, SEARCH, $search){ // 21.1.3.15 String.prototype.search(regexp) return [function search(regexp){ 'use strict'; var O = defined(this) , fn = regexp == undefined ? undefined : regexp[SEARCH]; return fn !== undefined ? fn.call(regexp, O) : new RegExp(regexp)[SEARCH](String(O)); }, $search]; }); /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { // @@split logic __webpack_require__(192)('split', 2, function(defined, SPLIT, $split){ 'use strict'; var isRegExp = __webpack_require__(128) , _split = $split , $push = [].push , $SPLIT = 'split' , LENGTH = 'length' , LAST_INDEX = 'lastIndex'; if( 'abbc'[$SPLIT](/(b)*/)[1] == 'c' || 'test'[$SPLIT](/(?:)/, -1)[LENGTH] != 4 || 'ab'[$SPLIT](/(?:ab)*/)[LENGTH] != 2 || '.'[$SPLIT](/(.?)(.?)/)[LENGTH] != 4 || '.'[$SPLIT](/()()/)[LENGTH] > 1 || ''[$SPLIT](/.?/)[LENGTH] ){ var NPCG = /()??/.exec('')[1] === undefined; // nonparticipating capturing group // based on es5-shim implementation, need to rework it $split = function(separator, limit){ var string = String(this); if(separator === undefined && limit === 0)return []; // If `separator` is not a regex, use native split if(!isRegExp(separator))return _split.call(string, separator, limit); var output = []; var flags = (separator.ignoreCase ? 'i' : '') + (separator.multiline ? 'm' : '') + (separator.unicode ? 'u' : '') + (separator.sticky ? 'y' : ''); var lastLastIndex = 0; var splitLimit = limit === undefined ? 4294967295 : limit >>> 0; // Make `global` and avoid `lastIndex` issues by working with a copy var separatorCopy = new RegExp(separator.source, flags + 'g'); var separator2, match, lastIndex, lastLength, i; // Doesn't need flags gy, but they don't hurt if(!NPCG)separator2 = new RegExp('^' + separatorCopy.source + '$(?!\\s)', flags); while(match = separatorCopy.exec(string)){ // `separatorCopy.lastIndex` is not reliable cross-browser lastIndex = match.index + match[0][LENGTH]; if(lastIndex > lastLastIndex){ output.push(string.slice(lastLastIndex, match.index)); // Fix browsers whose `exec` methods don't consistently return `undefined` for NPCG if(!NPCG && match[LENGTH] > 1)match[0].replace(separator2, function(){ for(i = 1; i < arguments[LENGTH] - 2; i++)if(arguments[i] === undefined)match[i] = undefined; }); if(match[LENGTH] > 1 && match.index < string[LENGTH])$push.apply(output, match.slice(1)); lastLength = match[0][LENGTH]; lastLastIndex = lastIndex; if(output[LENGTH] >= splitLimit)break; } if(separatorCopy[LAST_INDEX] === match.index)separatorCopy[LAST_INDEX]++; // Avoid an infinite loop } if(lastLastIndex === string[LENGTH]){ if(lastLength || !separatorCopy.test(''))output.push(''); } else output.push(string.slice(lastLastIndex)); return output[LENGTH] > splitLimit ? output.slice(0, splitLimit) : output; }; // Chakra, V8 } else if('0'[$SPLIT](undefined, 0)[LENGTH]){ $split = function(separator, limit){ return separator === undefined && limit === 0 ? [] : _split.call(this, separator, limit); }; } // 21.1.3.17 String.prototype.split(separator, limit) return [function split(separator, limit){ var O = defined(this) , fn = separator == undefined ? undefined : separator[SPLIT]; return fn !== undefined ? fn.call(separator, O, limit) : $split.call(String(O), separator, limit); }, $split]; }); /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var LIBRARY = __webpack_require__(26) , global = __webpack_require__(2) , ctx = __webpack_require__(18) , classof = __webpack_require__(73) , $export = __webpack_require__(6) , isObject = __webpack_require__(11) , aFunction = __webpack_require__(19) , anInstance = __webpack_require__(197) , forOf = __webpack_require__(198) , speciesConstructor = __webpack_require__(199) , task = __webpack_require__(200).set , microtask = __webpack_require__(201)() , PROMISE = 'Promise' , TypeError = global.TypeError , process = global.process , $Promise = global[PROMISE] , process = global.process , isNode = classof(process) == 'process' , empty = function(){ /* empty */ } , Internal, GenericPromiseCapability, Wrapper; var USE_NATIVE = !!function(){ try { // correct subclassing with @@species support var promise = $Promise.resolve(1) , FakePromise = (promise.constructor = {})[__webpack_require__(23)('species')] = function(exec){ exec(empty, empty); }; // unhandled rejections tracking support, NodeJS Promise without it fails @@species test return (isNode || typeof PromiseRejectionEvent == 'function') && promise.then(empty) instanceof FakePromise; } catch(e){ /* empty */ } }(); // helpers var sameConstructor = function(a, b){ // with library wrapper special case return a === b || a === $Promise && b === Wrapper; }; var isThenable = function(it){ var then; return isObject(it) && typeof (then = it.then) == 'function' ? then : false; }; var newPromiseCapability = function(C){ return sameConstructor($Promise, C) ? new PromiseCapability(C) : new GenericPromiseCapability(C); }; var PromiseCapability = GenericPromiseCapability = function(C){ var resolve, reject; this.promise = new C(function($$resolve, $$reject){ if(resolve !== undefined || reject !== undefined)throw TypeError('Bad Promise constructor'); resolve = $$resolve; reject = $$reject; }); this.resolve = aFunction(resolve); this.reject = aFunction(reject); }; var perform = function(exec){ try { exec(); } catch(e){ return {error: e}; } }; var notify = function(promise, isReject){ if(promise._n)return; promise._n = true; var chain = promise._c; microtask(function(){ var value = promise._v , ok = promise._s == 1 , i = 0; var run = function(reaction){ var handler = ok ? reaction.ok : reaction.fail , resolve = reaction.resolve , reject = reaction.reject , domain = reaction.domain , result, then; try { if(handler){ if(!ok){ if(promise._h == 2)onHandleUnhandled(promise); promise._h = 1; } if(handler === true)result = value; else { if(domain)domain.enter(); result = handler(value); if(domain)domain.exit(); } if(result === reaction.promise){ reject(TypeError('Promise-chain cycle')); } else if(then = isThenable(result)){ then.call(result, resolve, reject); } else resolve(result); } else reject(value); } catch(e){ reject(e); } }; while(chain.length > i)run(chain[i++]); // variable length - can't use forEach promise._c = []; promise._n = false; if(isReject && !promise._h)onUnhandled(promise); }); }; var onUnhandled = function(promise){ task.call(global, function(){ var value = promise._v , abrupt, handler, console; if(isUnhandled(promise)){ abrupt = perform(function(){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(handler = global.onunhandledrejection){ handler({promise: promise, reason: value}); } else if((console = global.console) && console.error){ console.error('Unhandled promise rejection', value); } }); // Browsers should not trigger `rejectionHandled` event if it was handled here, NodeJS - should promise._h = isNode || isUnhandled(promise) ? 2 : 1; } promise._a = undefined; if(abrupt)throw abrupt.error; }); }; var isUnhandled = function(promise){ if(promise._h == 1)return false; var chain = promise._a || promise._c , i = 0 , reaction; while(chain.length > i){ reaction = chain[i++]; if(reaction.fail || !isUnhandled(reaction.promise))return false; } return true; }; var onHandleUnhandled = function(promise){ task.call(global, function(){ var handler; if(isNode){ process.emit('rejectionHandled', promise); } else if(handler = global.onrejectionhandled){ handler({promise: promise, reason: promise._v}); } }); }; var $reject = function(value){ var promise = this; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap promise._v = value; promise._s = 2; if(!promise._a)promise._a = promise._c.slice(); notify(promise, true); }; var $resolve = function(value){ var promise = this , then; if(promise._d)return; promise._d = true; promise = promise._w || promise; // unwrap try { if(promise === value)throw TypeError("Promise can't be resolved itself"); if(then = isThenable(value)){ microtask(function(){ var wrapper = {_w: promise, _d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { promise._v = value; promise._s = 1; notify(promise, false); } } catch(e){ $reject.call({_w: promise, _d: false}, e); // wrap } }; // constructor polyfill if(!USE_NATIVE){ // 25.4.3.1 Promise(executor) $Promise = function Promise(executor){ anInstance(this, $Promise, PROMISE, '_h'); aFunction(executor); Internal.call(this); try { executor(ctx($resolve, this, 1), ctx($reject, this, 1)); } catch(err){ $reject.call(this, err); } }; Internal = function Promise(executor){ this._c = []; // <- awaiting reactions this._a = undefined; // <- checked in isUnhandled reactions this._s = 0; // <- state this._d = false; // <- done this._v = undefined; // <- value this._h = 0; // <- rejection state, 0 - default, 1 - handled, 2 - unhandled this._n = false; // <- notify }; Internal.prototype = __webpack_require__(202)($Promise.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var reaction = newPromiseCapability(speciesConstructor(this, $Promise)); reaction.ok = typeof onFulfilled == 'function' ? onFulfilled : true; reaction.fail = typeof onRejected == 'function' && onRejected; reaction.domain = isNode ? process.domain : undefined; this._c.push(reaction); if(this._a)this._a.push(reaction); if(this._s)notify(this, false); return reaction.promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); PromiseCapability = function(){ var promise = new Internal; this.promise = promise; this.resolve = ctx($resolve, promise, 1); this.reject = ctx($reject, promise, 1); }; } $export($export.G + $export.W + $export.F * !USE_NATIVE, {Promise: $Promise}); __webpack_require__(22)($Promise, PROMISE); __webpack_require__(186)(PROMISE); Wrapper = __webpack_require__(7)[PROMISE]; // statics $export($export.S + $export.F * !USE_NATIVE, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ var capability = newPromiseCapability(this) , $$reject = capability.reject; $$reject(r); return capability.promise; } }); $export($export.S + $export.F * (LIBRARY || !USE_NATIVE), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ // instanceof instead of internal slot check because we should fix it without replacement native Promise core if(x instanceof $Promise && sameConstructor(x.constructor, this))return x; var capability = newPromiseCapability(this) , $$resolve = capability.resolve; $$resolve(x); return capability.promise; } }); $export($export.S + $export.F * !(USE_NATIVE && __webpack_require__(157)(function(iter){ $Promise.all(iter)['catch'](empty); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = this , capability = newPromiseCapability(C) , resolve = capability.resolve , reject = capability.reject; var abrupt = perform(function(){ var values = [] , index = 0 , remaining = 1; forOf(iterable, false, function(promise){ var $index = index++ , alreadyCalled = false; values.push(undefined); remaining++; C.resolve(promise).then(function(value){ if(alreadyCalled)return; alreadyCalled = true; values[$index] = value; --remaining || resolve(values); }, reject); }); --remaining || resolve(values); }); if(abrupt)reject(abrupt.error); return capability.promise; }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = this , capability = newPromiseCapability(C) , reject = capability.reject; var abrupt = perform(function(){ forOf(iterable, false, function(promise){ C.resolve(promise).then(capability.resolve, reject); }); }); if(abrupt)reject(abrupt.error); return capability.promise; } }); /***/ }, /* 197 */ /***/ function(module, exports) { module.exports = function(it, Constructor, name, forbiddenField){ if(!(it instanceof Constructor) || (forbiddenField !== undefined && forbiddenField in it)){ throw TypeError(name + ': incorrect invocation!'); } return it; }; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(18) , call = __webpack_require__(153) , isArrayIter = __webpack_require__(154) , anObject = __webpack_require__(10) , toLength = __webpack_require__(35) , getIterFn = __webpack_require__(156) , BREAK = {} , RETURN = {}; var exports = module.exports = function(iterable, entries, fn, that, ITERATOR){ var iterFn = ITERATOR ? function(){ return iterable; } : getIterFn(iterable) , f = ctx(fn, that, entries ? 2 : 1) , index = 0 , length, step, iterator, result; if(typeof iterFn != 'function')throw TypeError(iterable + ' is not iterable!'); // fast case for arrays with default iterator if(isArrayIter(iterFn))for(length = toLength(iterable.length); length > index; index++){ result = entries ? f(anObject(step = iterable[index])[0], step[1]) : f(iterable[index]); if(result === BREAK || result === RETURN)return result; } else for(iterator = iterFn.call(iterable); !(step = iterator.next()).done; ){ result = call(iterator, f, step.value, entries); if(result === BREAK || result === RETURN)return result; } }; exports.BREAK = BREAK; exports.RETURN = RETURN; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { // 7.3.20 SpeciesConstructor(O, defaultConstructor) var anObject = __webpack_require__(10) , aFunction = __webpack_require__(19) , SPECIES = __webpack_require__(23)('species'); module.exports = function(O, D){ var C = anObject(O).constructor, S; return C === undefined || (S = anObject(C)[SPECIES]) == undefined ? D : aFunction(S); }; /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { var ctx = __webpack_require__(18) , invoke = __webpack_require__(76) , html = __webpack_require__(46) , cel = __webpack_require__(13) , global = __webpack_require__(2) , process = global.process , setTask = global.setImmediate , clearTask = global.clearImmediate , MessageChannel = global.MessageChannel , counter = 0 , queue = {} , ONREADYSTATECHANGE = 'onreadystatechange' , defer, channel, port; var run = function(){ var id = +this; if(queue.hasOwnProperty(id)){ var fn = queue[id]; delete queue[id]; fn(); } }; var listener = function(event){ run.call(event.data); }; // Node.js 0.9+ & IE10+ has setImmediate, otherwise: if(!setTask || !clearTask){ setTask = function setImmediate(fn){ var args = [], i = 1; while(arguments.length > i)args.push(arguments[i++]); queue[++counter] = function(){ invoke(typeof fn == 'function' ? fn : Function(fn), args); }; defer(counter); return counter; }; clearTask = function clearImmediate(id){ delete queue[id]; }; // Node.js 0.8- if(__webpack_require__(32)(process) == 'process'){ defer = function(id){ process.nextTick(ctx(run, id, 1)); }; // Browsers with MessageChannel, includes WebWorkers } else if(MessageChannel){ channel = new MessageChannel; port = channel.port2; channel.port1.onmessage = listener; defer = ctx(port.postMessage, port, 1); // Browsers with postMessage, skip WebWorkers // IE8 has postMessage, but it's sync & typeof its postMessage is 'object' } else if(global.addEventListener && typeof postMessage == 'function' && !global.importScripts){ defer = function(id){ global.postMessage(id + '', '*'); }; global.addEventListener('message', listener, false); // IE8- } else if(ONREADYSTATECHANGE in cel('script')){ defer = function(id){ html.appendChild(cel('script'))[ONREADYSTATECHANGE] = function(){ html.removeChild(this); run.call(id); }; }; // Rest old browsers } else { defer = function(id){ setTimeout(ctx(run, id, 1), 0); }; } } module.exports = { set: setTask, clear: clearTask }; /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(2) , macrotask = __webpack_require__(200).set , Observer = global.MutationObserver || global.WebKitMutationObserver , process = global.process , Promise = global.Promise , isNode = __webpack_require__(32)(process) == 'process'; module.exports = function(){ var head, last, notify; var flush = function(){ var parent, fn; if(isNode && (parent = process.domain))parent.exit(); while(head){ fn = head.fn; head = head.next; try { fn(); } catch(e){ if(head)notify(); else last = undefined; throw e; } } last = undefined; if(parent)parent.enter(); }; // Node.js if(isNode){ notify = function(){ process.nextTick(flush); }; // browsers with MutationObserver } else if(Observer){ var toggle = true , node = document.createTextNode(''); new Observer(flush).observe(node, {characterData: true}); // eslint-disable-line no-new notify = function(){ node.data = toggle = !toggle; }; // environments with maybe non-completely correct, but existent Promise } else if(Promise && Promise.resolve){ var promise = Promise.resolve(); notify = function(){ promise.then(flush); }; // for other environments - macrotask based on: // - setImmediate // - MessageChannel // - window.postMessag // - onreadystatechange // - setTimeout } else { notify = function(){ // strange IE + webpack dev server bug - use .call(global) macrotask.call(global, flush); }; } return function(fn){ var task = {fn: fn, next: undefined}; if(last)last.next = task; if(!head){ head = task; notify(); } last = task; }; }; /***/ }, /* 202 */ /***/ function(module, exports, __webpack_require__) { var redefine = __webpack_require__(16); module.exports = function(target, src, safe){ for(var key in src)redefine(target, key, src[key], safe); return target; }; /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(204); // 23.1 Map Objects module.exports = __webpack_require__(205)('Map', function(get){ return function Map(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.1.3.6 Map.prototype.get(key) get: function get(key){ var entry = strong.getEntry(this, key); return entry && entry.v; }, // 23.1.3.9 Map.prototype.set(key, value) set: function set(key, value){ return strong.def(this, key === 0 ? 0 : key, value); } }, strong, true); /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var dP = __webpack_require__(9).f , create = __webpack_require__(44) , redefineAll = __webpack_require__(202) , ctx = __webpack_require__(18) , anInstance = __webpack_require__(197) , defined = __webpack_require__(33) , forOf = __webpack_require__(198) , $iterDefine = __webpack_require__(134) , step = __webpack_require__(184) , setSpecies = __webpack_require__(186) , DESCRIPTORS = __webpack_require__(4) , fastKey = __webpack_require__(20).fastKey , SIZE = DESCRIPTORS ? '_s' : 'size'; var getEntry = function(that, key){ // fast case var index = fastKey(key), entry; if(index !== 'F')return that._i[index]; // frozen object case for(entry = that._f; entry; entry = entry.n){ if(entry.k == key)return entry; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ anInstance(that, C, NAME, '_i'); that._i = create(null); // index that._f = undefined; // first entry that._l = undefined; // last entry that[SIZE] = 0; // size if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.1.3.1 Map.prototype.clear() // 23.2.3.2 Set.prototype.clear() clear: function clear(){ for(var that = this, data = that._i, entry = that._f; entry; entry = entry.n){ entry.r = true; if(entry.p)entry.p = entry.p.n = undefined; delete data[entry.i]; } that._f = that._l = undefined; that[SIZE] = 0; }, // 23.1.3.3 Map.prototype.delete(key) // 23.2.3.4 Set.prototype.delete(value) 'delete': function(key){ var that = this , entry = getEntry(that, key); if(entry){ var next = entry.n , prev = entry.p; delete that._i[entry.i]; entry.r = true; if(prev)prev.n = next; if(next)next.p = prev; if(that._f == entry)that._f = next; if(that._l == entry)that._l = prev; that[SIZE]--; } return !!entry; }, // 23.2.3.6 Set.prototype.forEach(callbackfn, thisArg = undefined) // 23.1.3.5 Map.prototype.forEach(callbackfn, thisArg = undefined) forEach: function forEach(callbackfn /*, that = undefined */){ anInstance(this, C, 'forEach'); var f = ctx(callbackfn, arguments.length > 1 ? arguments[1] : undefined, 3) , entry; while(entry = entry ? entry.n : this._f){ f(entry.v, entry.k, this); // revert to the last existing entry while(entry && entry.r)entry = entry.p; } }, // 23.1.3.7 Map.prototype.has(key) // 23.2.3.7 Set.prototype.has(value) has: function has(key){ return !!getEntry(this, key); } }); if(DESCRIPTORS)dP(C.prototype, 'size', { get: function(){ return defined(this[SIZE]); } }); return C; }, def: function(that, key, value){ var entry = getEntry(that, key) , prev, index; // change existing entry if(entry){ entry.v = value; // create new entry } else { that._l = entry = { i: index = fastKey(key, true), // <- index k: key, // <- key v: value, // <- value p: prev = that._l, // <- previous entry n: undefined, // <- next entry r: false // <- removed }; if(!that._f)that._f = entry; if(prev)prev.n = entry; that[SIZE]++; // add to index if(index !== 'F')that._i[index] = entry; } return that; }, getEntry: getEntry, setStrong: function(C, NAME, IS_MAP){ // add .keys, .values, .entries, [@@iterator] // 23.1.3.4, 23.1.3.8, 23.1.3.11, 23.1.3.12, 23.2.3.5, 23.2.3.8, 23.2.3.10, 23.2.3.11 $iterDefine(C, NAME, function(iterated, kind){ this._t = iterated; // target this._k = kind; // kind this._l = undefined; // previous }, function(){ var that = this , kind = that._k , entry = that._l; // revert to the last existing entry while(entry && entry.r)entry = entry.p; // get next entry if(!that._t || !(that._l = entry = entry ? entry.n : that._t._f)){ // or finish the iteration that._t = undefined; return step(1); } // return step by kind if(kind == 'keys' )return step(0, entry.k); if(kind == 'values')return step(0, entry.v); return step(0, [entry.k, entry.v]); }, IS_MAP ? 'entries' : 'values' , !IS_MAP, true); // add [@@species], 23.1.2.2, 23.2.2.2 setSpecies(NAME); } }; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = __webpack_require__(2) , $export = __webpack_require__(6) , redefine = __webpack_require__(16) , redefineAll = __webpack_require__(202) , meta = __webpack_require__(20) , forOf = __webpack_require__(198) , anInstance = __webpack_require__(197) , isObject = __webpack_require__(11) , fails = __webpack_require__(5) , $iterDetect = __webpack_require__(157) , setToStringTag = __webpack_require__(22) , inheritIfRequired = __webpack_require__(80); module.exports = function(NAME, wrapper, methods, common, IS_MAP, IS_WEAK){ var Base = global[NAME] , C = Base , ADDER = IS_MAP ? 'set' : 'add' , proto = C && C.prototype , O = {}; var fixMethod = function(KEY){ var fn = proto[KEY]; redefine(proto, KEY, KEY == 'delete' ? function(a){ return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); } : KEY == 'has' ? function has(a){ return IS_WEAK && !isObject(a) ? false : fn.call(this, a === 0 ? 0 : a); } : KEY == 'get' ? function get(a){ return IS_WEAK && !isObject(a) ? undefined : fn.call(this, a === 0 ? 0 : a); } : KEY == 'add' ? function add(a){ fn.call(this, a === 0 ? 0 : a); return this; } : function set(a, b){ fn.call(this, a === 0 ? 0 : a, b); return this; } ); }; if(typeof C != 'function' || !(IS_WEAK || proto.forEach && !fails(function(){ new C().entries().next(); }))){ // create collection constructor C = common.getConstructor(wrapper, NAME, IS_MAP, ADDER); redefineAll(C.prototype, methods); meta.NEED = true; } else { var instance = new C // early implementations not supports chaining , HASNT_CHAINING = instance[ADDER](IS_WEAK ? {} : -0, 1) != instance // V8 ~ Chromium 40- weak-collections throws on primitives, but should return false , THROWS_ON_PRIMITIVES = fails(function(){ instance.has(1); }) // most early implementations doesn't supports iterables, most modern - not close it correctly , ACCEPT_ITERABLES = $iterDetect(function(iter){ new C(iter); }) // eslint-disable-line no-new // for early implementations -0 and +0 not the same , BUGGY_ZERO = !IS_WEAK && fails(function(){ // V8 ~ Chromium 42- fails only with 5+ elements var $instance = new C() , index = 5; while(index--)$instance[ADDER](index, index); return !$instance.has(-0); }); if(!ACCEPT_ITERABLES){ C = wrapper(function(target, iterable){ anInstance(target, C, NAME); var that = inheritIfRequired(new Base, target, C); if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); return that; }); C.prototype = proto; proto.constructor = C; } if(THROWS_ON_PRIMITIVES || BUGGY_ZERO){ fixMethod('delete'); fixMethod('has'); IS_MAP && fixMethod('get'); } if(BUGGY_ZERO || HASNT_CHAINING)fixMethod(ADDER); // weak collections should not contains .clear method if(IS_WEAK && proto.clear)delete proto.clear; } setToStringTag(C, NAME); O[NAME] = C; $export($export.G + $export.W + $export.F * (C != Base), O); if(!IS_WEAK)common.setStrong(C, NAME, IS_MAP); return C; }; /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var strong = __webpack_require__(204); // 23.2 Set Objects module.exports = __webpack_require__(205)('Set', function(get){ return function Set(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.2.3.1 Set.prototype.add(value) add: function add(value){ return strong.def(this, value = value === 0 ? 0 : value, value); } }, strong); /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var each = __webpack_require__(164)(0) , redefine = __webpack_require__(16) , meta = __webpack_require__(20) , assign = __webpack_require__(67) , weak = __webpack_require__(208) , isObject = __webpack_require__(11) , getWeak = meta.getWeak , isExtensible = Object.isExtensible , uncaughtFrozenStore = weak.ufstore , tmp = {} , InternalMap; var wrapper = function(get){ return function WeakMap(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }; var methods = { // 23.3.3.3 WeakMap.prototype.get(key) get: function get(key){ if(isObject(key)){ var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).get(key); return data ? data[this._i] : undefined; } }, // 23.3.3.5 WeakMap.prototype.set(key, value) set: function set(key, value){ return weak.def(this, key, value); } }; // 23.3 WeakMap Objects var $WeakMap = module.exports = __webpack_require__(205)('WeakMap', wrapper, methods, weak, true, true); // IE11 WeakMap frozen keys fix if(new $WeakMap().set((Object.freeze || Object)(tmp), 7).get(tmp) != 7){ InternalMap = weak.getConstructor(wrapper); assign(InternalMap.prototype, methods); meta.NEED = true; each(['delete', 'has', 'get', 'set'], function(key){ var proto = $WeakMap.prototype , method = proto[key]; redefine(proto, key, function(a, b){ // store frozen objects on internal weakmap shim if(isObject(a) && !isExtensible(a)){ if(!this._f)this._f = new InternalMap; var result = this._f[key](a, b); return key == 'set' ? this : result; // store all the rest on native weakmap } return method.call(this, a, b); }); }); } /***/ }, /* 208 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var redefineAll = __webpack_require__(202) , getWeak = __webpack_require__(20).getWeak , anObject = __webpack_require__(10) , isObject = __webpack_require__(11) , anInstance = __webpack_require__(197) , forOf = __webpack_require__(198) , createArrayMethod = __webpack_require__(164) , $has = __webpack_require__(3) , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , id = 0; // fallback for uncaught frozen keys var uncaughtFrozenStore = function(that){ return that._l || (that._l = new UncaughtFrozenStore); }; var UncaughtFrozenStore = function(){ this.a = []; }; var findUncaughtFrozen = function(store, key){ return arrayFind(store.a, function(it){ return it[0] === key; }); }; UncaughtFrozenStore.prototype = { get: function(key){ var entry = findUncaughtFrozen(this, key); if(entry)return entry[1]; }, has: function(key){ return !!findUncaughtFrozen(this, key); }, set: function(key, value){ var entry = findUncaughtFrozen(this, key); if(entry)entry[1] = value; else this.a.push([key, value]); }, 'delete': function(key){ var index = arrayFindIndex(this.a, function(it){ return it[0] === key; }); if(~index)this.a.splice(index, 1); return !!~index; } }; module.exports = { getConstructor: function(wrapper, NAME, IS_MAP, ADDER){ var C = wrapper(function(that, iterable){ anInstance(that, C, NAME, '_i'); that._i = id++; // collection id that._l = undefined; // leak store for uncaught frozen objects if(iterable != undefined)forOf(iterable, IS_MAP, that[ADDER], that); }); redefineAll(C.prototype, { // 23.3.3.2 WeakMap.prototype.delete(key) // 23.4.3.3 WeakSet.prototype.delete(value) 'delete': function(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this)['delete'](key); return data && $has(data, this._i) && delete data[this._i]; }, // 23.3.3.4 WeakMap.prototype.has(key) // 23.4.3.4 WeakSet.prototype.has(value) has: function has(key){ if(!isObject(key))return false; var data = getWeak(key); if(data === true)return uncaughtFrozenStore(this).has(key); return data && $has(data, this._i); } }); return C; }, def: function(that, key, value){ var data = getWeak(anObject(key), true); if(data === true)uncaughtFrozenStore(that).set(key, value); else data[that._i] = value; return that; }, ufstore: uncaughtFrozenStore }; /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var weak = __webpack_require__(208); // 23.4 WeakSet Objects __webpack_require__(205)('WeakSet', function(get){ return function WeakSet(){ return get(this, arguments.length > 0 ? arguments[0] : undefined); }; }, { // 23.4.3.1 WeakSet.prototype.add(value) add: function add(value){ return weak.def(this, value, true); } }, weak, false, true); /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { // 26.1.1 Reflect.apply(target, thisArgument, argumentsList) var $export = __webpack_require__(6) , aFunction = __webpack_require__(19) , anObject = __webpack_require__(10) , rApply = (__webpack_require__(2).Reflect || {}).apply , fApply = Function.apply; // MS Edge argumentsList argument is optional $export($export.S + $export.F * !__webpack_require__(5)(function(){ rApply(function(){}); }), 'Reflect', { apply: function apply(target, thisArgument, argumentsList){ var T = aFunction(target) , L = anObject(argumentsList); return rApply ? rApply(T, thisArgument, L) : fApply.call(T, thisArgument, L); } }); /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { // 26.1.2 Reflect.construct(target, argumentsList [, newTarget]) var $export = __webpack_require__(6) , create = __webpack_require__(44) , aFunction = __webpack_require__(19) , anObject = __webpack_require__(10) , isObject = __webpack_require__(11) , fails = __webpack_require__(5) , bind = __webpack_require__(75) , rConstruct = (__webpack_require__(2).Reflect || {}).construct; // MS Edge supports only 2 arguments and argumentsList argument is optional // FF Nightly sets third argument as `new.target`, but does not create `this` from it var NEW_TARGET_BUG = fails(function(){ function F(){} return !(rConstruct(function(){}, [], F) instanceof F); }); var ARGS_BUG = !fails(function(){ rConstruct(function(){}); }); $export($export.S + $export.F * (NEW_TARGET_BUG || ARGS_BUG), 'Reflect', { construct: function construct(Target, args /*, newTarget*/){ aFunction(Target); anObject(args); var newTarget = arguments.length < 3 ? Target : aFunction(arguments[2]); if(ARGS_BUG && !NEW_TARGET_BUG)return rConstruct(Target, args, newTarget); if(Target == newTarget){ // w/o altered newTarget, optimization for 0-4 arguments switch(args.length){ case 0: return new Target; case 1: return new Target(args[0]); case 2: return new Target(args[0], args[1]); case 3: return new Target(args[0], args[1], args[2]); case 4: return new Target(args[0], args[1], args[2], args[3]); } // w/o altered newTarget, lot of arguments case var $args = [null]; $args.push.apply($args, args); return new (bind.apply(Target, $args)); } // with altered newTarget, not support built-in constructors var proto = newTarget.prototype , instance = create(isObject(proto) ? proto : Object.prototype) , result = Function.apply.call(Target, instance, args); return isObject(result) ? result : instance; } }); /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { // 26.1.3 Reflect.defineProperty(target, propertyKey, attributes) var dP = __webpack_require__(9) , $export = __webpack_require__(6) , anObject = __webpack_require__(10) , toPrimitive = __webpack_require__(14); // MS Edge has broken Reflect.defineProperty - throwing instead of returning false $export($export.S + $export.F * __webpack_require__(5)(function(){ Reflect.defineProperty(dP.f({}, 1, {value: 1}), 1, {value: 2}); }), 'Reflect', { defineProperty: function defineProperty(target, propertyKey, attributes){ anObject(target); propertyKey = toPrimitive(propertyKey, true); anObject(attributes); try { dP.f(target, propertyKey, attributes); return true; } catch(e){ return false; } } }); /***/ }, /* 213 */ /***/ function(module, exports, __webpack_require__) { // 26.1.4 Reflect.deleteProperty(target, propertyKey) var $export = __webpack_require__(6) , gOPD = __webpack_require__(49).f , anObject = __webpack_require__(10); $export($export.S, 'Reflect', { deleteProperty: function deleteProperty(target, propertyKey){ var desc = gOPD(anObject(target), propertyKey); return desc && !desc.configurable ? false : delete target[propertyKey]; } }); /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 26.1.5 Reflect.enumerate(target) var $export = __webpack_require__(6) , anObject = __webpack_require__(10); var Enumerate = function(iterated){ this._t = anObject(iterated); // target this._i = 0; // next index var keys = this._k = [] // keys , key; for(key in iterated)keys.push(key); }; __webpack_require__(136)(Enumerate, 'Object', function(){ var that = this , keys = that._k , key; do { if(that._i >= keys.length)return {value: undefined, done: true}; } while(!((key = keys[that._i++]) in that._t)); return {value: key, done: false}; }); $export($export.S, 'Reflect', { enumerate: function enumerate(target){ return new Enumerate(target); } }); /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { // 26.1.6 Reflect.get(target, propertyKey [, receiver]) var gOPD = __webpack_require__(49) , getPrototypeOf = __webpack_require__(57) , has = __webpack_require__(3) , $export = __webpack_require__(6) , isObject = __webpack_require__(11) , anObject = __webpack_require__(10); function get(target, propertyKey/*, receiver*/){ var receiver = arguments.length < 3 ? target : arguments[2] , desc, proto; if(anObject(target) === receiver)return target[propertyKey]; if(desc = gOPD.f(target, propertyKey))return has(desc, 'value') ? desc.value : desc.get !== undefined ? desc.get.call(receiver) : undefined; if(isObject(proto = getPrototypeOf(target)))return get(proto, propertyKey, receiver); } $export($export.S, 'Reflect', {get: get}); /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { // 26.1.7 Reflect.getOwnPropertyDescriptor(target, propertyKey) var gOPD = __webpack_require__(49) , $export = __webpack_require__(6) , anObject = __webpack_require__(10); $export($export.S, 'Reflect', { getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey){ return gOPD.f(anObject(target), propertyKey); } }); /***/ }, /* 217 */ /***/ function(module, exports, __webpack_require__) { // 26.1.8 Reflect.getPrototypeOf(target) var $export = __webpack_require__(6) , getProto = __webpack_require__(57) , anObject = __webpack_require__(10); $export($export.S, 'Reflect', { getPrototypeOf: function getPrototypeOf(target){ return getProto(anObject(target)); } }); /***/ }, /* 218 */ /***/ function(module, exports, __webpack_require__) { // 26.1.9 Reflect.has(target, propertyKey) var $export = __webpack_require__(6); $export($export.S, 'Reflect', { has: function has(target, propertyKey){ return propertyKey in target; } }); /***/ }, /* 219 */ /***/ function(module, exports, __webpack_require__) { // 26.1.10 Reflect.isExtensible(target) var $export = __webpack_require__(6) , anObject = __webpack_require__(10) , $isExtensible = Object.isExtensible; $export($export.S, 'Reflect', { isExtensible: function isExtensible(target){ anObject(target); return $isExtensible ? $isExtensible(target) : true; } }); /***/ }, /* 220 */ /***/ function(module, exports, __webpack_require__) { // 26.1.11 Reflect.ownKeys(target) var $export = __webpack_require__(6); $export($export.S, 'Reflect', {ownKeys: __webpack_require__(221)}); /***/ }, /* 221 */ /***/ function(module, exports, __webpack_require__) { // all object keys, includes non-enumerable and symbols var gOPN = __webpack_require__(48) , gOPS = __webpack_require__(41) , anObject = __webpack_require__(10) , Reflect = __webpack_require__(2).Reflect; module.exports = Reflect && Reflect.ownKeys || function ownKeys(it){ var keys = gOPN.f(anObject(it)) , getSymbols = gOPS.f; return getSymbols ? keys.concat(getSymbols(it)) : keys; }; /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { // 26.1.12 Reflect.preventExtensions(target) var $export = __webpack_require__(6) , anObject = __webpack_require__(10) , $preventExtensions = Object.preventExtensions; $export($export.S, 'Reflect', { preventExtensions: function preventExtensions(target){ anObject(target); try { if($preventExtensions)$preventExtensions(target); return true; } catch(e){ return false; } } }); /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { // 26.1.13 Reflect.set(target, propertyKey, V [, receiver]) var dP = __webpack_require__(9) , gOPD = __webpack_require__(49) , getPrototypeOf = __webpack_require__(57) , has = __webpack_require__(3) , $export = __webpack_require__(6) , createDesc = __webpack_require__(15) , anObject = __webpack_require__(10) , isObject = __webpack_require__(11); function set(target, propertyKey, V/*, receiver*/){ var receiver = arguments.length < 4 ? target : arguments[3] , ownDesc = gOPD.f(anObject(target), propertyKey) , existingDescriptor, proto; if(!ownDesc){ if(isObject(proto = getPrototypeOf(target))){ return set(proto, propertyKey, V, receiver); } ownDesc = createDesc(0); } if(has(ownDesc, 'value')){ if(ownDesc.writable === false || !isObject(receiver))return false; existingDescriptor = gOPD.f(receiver, propertyKey) || createDesc(0); existingDescriptor.value = V; dP.f(receiver, propertyKey, existingDescriptor); return true; } return ownDesc.set === undefined ? false : (ownDesc.set.call(receiver, V), true); } $export($export.S, 'Reflect', {set: set}); /***/ }, /* 224 */ /***/ function(module, exports, __webpack_require__) { // 26.1.14 Reflect.setPrototypeOf(target, proto) var $export = __webpack_require__(6) , setProto = __webpack_require__(71); if(setProto)$export($export.S, 'Reflect', { setPrototypeOf: function setPrototypeOf(target, proto){ setProto.check(target, proto); try { setProto.set(target, proto); return true; } catch(e){ return false; } } }); /***/ }, /* 225 */ /***/ function(module, exports, __webpack_require__) { // 20.3.3.1 / 15.9.4.4 Date.now() var $export = __webpack_require__(6); $export($export.S, 'Date', {now: function(){ return new Date().getTime(); }}); /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , toObject = __webpack_require__(56) , toPrimitive = __webpack_require__(14); $export($export.P + $export.F * __webpack_require__(5)(function(){ return new Date(NaN).toJSON() !== null || Date.prototype.toJSON.call({toISOString: function(){ return 1; }}) !== 1; }), 'Date', { toJSON: function toJSON(key){ var O = toObject(this) , pv = toPrimitive(O); return typeof pv == 'number' && !isFinite(pv) ? null : O.toISOString(); } }); /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // 20.3.4.36 / 15.9.5.43 Date.prototype.toISOString() var $export = __webpack_require__(6) , fails = __webpack_require__(5) , getTime = Date.prototype.getTime; var lz = function(num){ return num > 9 ? num : '0' + num; }; // PhantomJS / old WebKit has a broken implementations $export($export.P + $export.F * (fails(function(){ return new Date(-5e13 - 1).toISOString() != '0385-07-25T07:06:39.999Z'; }) || !fails(function(){ new Date(NaN).toISOString(); })), 'Date', { toISOString: function toISOString(){ if(!isFinite(getTime.call(this)))throw RangeError('Invalid time value'); var d = this , y = d.getUTCFullYear() , m = d.getUTCMilliseconds() , s = y < 0 ? '-' : y > 9999 ? '+' : ''; return s + ('00000' + Math.abs(y)).slice(s ? -6 : -4) + '-' + lz(d.getUTCMonth() + 1) + '-' + lz(d.getUTCDate()) + 'T' + lz(d.getUTCHours()) + ':' + lz(d.getUTCMinutes()) + ':' + lz(d.getUTCSeconds()) + '.' + (m > 99 ? m : '0' + lz(m)) + 'Z'; } }); /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { var DateProto = Date.prototype , INVALID_DATE = 'Invalid Date' , TO_STRING = 'toString' , $toString = DateProto[TO_STRING] , getTime = DateProto.getTime; if(new Date(NaN) + '' != INVALID_DATE){ __webpack_require__(16)(DateProto, TO_STRING, function toString(){ var value = getTime.call(this); return value === value ? $toString.call(this) : INVALID_DATE; }); } /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { var TO_PRIMITIVE = __webpack_require__(23)('toPrimitive') , proto = Date.prototype; if(!(TO_PRIMITIVE in proto))__webpack_require__(8)(proto, TO_PRIMITIVE, __webpack_require__(230)); /***/ }, /* 230 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var anObject = __webpack_require__(10) , toPrimitive = __webpack_require__(14) , NUMBER = 'number'; module.exports = function(hint){ if(hint !== 'string' && hint !== NUMBER && hint !== 'default')throw TypeError('Incorrect hint'); return toPrimitive(anObject(this), hint != NUMBER); }; /***/ }, /* 231 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , $typed = __webpack_require__(232) , buffer = __webpack_require__(233) , anObject = __webpack_require__(10) , toIndex = __webpack_require__(37) , toLength = __webpack_require__(35) , isObject = __webpack_require__(11) , ArrayBuffer = __webpack_require__(2).ArrayBuffer , speciesConstructor = __webpack_require__(199) , $ArrayBuffer = buffer.ArrayBuffer , $DataView = buffer.DataView , $isView = $typed.ABV && ArrayBuffer.isView , $slice = $ArrayBuffer.prototype.slice , VIEW = $typed.VIEW , ARRAY_BUFFER = 'ArrayBuffer'; $export($export.G + $export.W + $export.F * (ArrayBuffer !== $ArrayBuffer), {ArrayBuffer: $ArrayBuffer}); $export($export.S + $export.F * !$typed.CONSTR, ARRAY_BUFFER, { // 24.1.3.1 ArrayBuffer.isView(arg) isView: function isView(it){ return $isView && $isView(it) || isObject(it) && VIEW in it; } }); $export($export.P + $export.U + $export.F * __webpack_require__(5)(function(){ return !new $ArrayBuffer(2).slice(1, undefined).byteLength; }), ARRAY_BUFFER, { // 24.1.4.3 ArrayBuffer.prototype.slice(start, end) slice: function slice(start, end){ if($slice !== undefined && end === undefined)return $slice.call(anObject(this), start); // FF fix var len = anObject(this).byteLength , first = toIndex(start, len) , final = toIndex(end === undefined ? len : end, len) , result = new (speciesConstructor(this, $ArrayBuffer))(toLength(final - first)) , viewS = new $DataView(this) , viewT = new $DataView(result) , index = 0; while(first < final){ viewT.setUint8(index++, viewS.getUint8(first++)); } return result; } }); __webpack_require__(186)(ARRAY_BUFFER); /***/ }, /* 232 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(2) , hide = __webpack_require__(8) , uid = __webpack_require__(17) , TYPED = uid('typed_array') , VIEW = uid('view') , ABV = !!(global.ArrayBuffer && global.DataView) , CONSTR = ABV , i = 0, l = 9, Typed; var TypedArrayConstructors = ( 'Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array' ).split(','); while(i < l){ if(Typed = global[TypedArrayConstructors[i++]]){ hide(Typed.prototype, TYPED, true); hide(Typed.prototype, VIEW, true); } else CONSTR = false; } module.exports = { ABV: ABV, CONSTR: CONSTR, TYPED: TYPED, VIEW: VIEW }; /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var global = __webpack_require__(2) , DESCRIPTORS = __webpack_require__(4) , LIBRARY = __webpack_require__(26) , $typed = __webpack_require__(232) , hide = __webpack_require__(8) , redefineAll = __webpack_require__(202) , fails = __webpack_require__(5) , anInstance = __webpack_require__(197) , toInteger = __webpack_require__(36) , toLength = __webpack_require__(35) , gOPN = __webpack_require__(48).f , dP = __webpack_require__(9).f , arrayFill = __webpack_require__(180) , setToStringTag = __webpack_require__(22) , ARRAY_BUFFER = 'ArrayBuffer' , DATA_VIEW = 'DataView' , PROTOTYPE = 'prototype' , WRONG_LENGTH = 'Wrong length!' , WRONG_INDEX = 'Wrong index!' , $ArrayBuffer = global[ARRAY_BUFFER] , $DataView = global[DATA_VIEW] , Math = global.Math , RangeError = global.RangeError , Infinity = global.Infinity , BaseBuffer = $ArrayBuffer , abs = Math.abs , pow = Math.pow , floor = Math.floor , log = Math.log , LN2 = Math.LN2 , BUFFER = 'buffer' , BYTE_LENGTH = 'byteLength' , BYTE_OFFSET = 'byteOffset' , $BUFFER = DESCRIPTORS ? '_b' : BUFFER , $LENGTH = DESCRIPTORS ? '_l' : BYTE_LENGTH , $OFFSET = DESCRIPTORS ? '_o' : BYTE_OFFSET; // IEEE754 conversions based on https://github.com/feross/ieee754 var packIEEE754 = function(value, mLen, nBytes){ var buffer = Array(nBytes) , eLen = nBytes * 8 - mLen - 1 , eMax = (1 << eLen) - 1 , eBias = eMax >> 1 , rt = mLen === 23 ? pow(2, -24) - pow(2, -77) : 0 , i = 0 , s = value < 0 || value === 0 && 1 / value < 0 ? 1 : 0 , e, m, c; value = abs(value) if(value != value || value === Infinity){ m = value != value ? 1 : 0; e = eMax; } else { e = floor(log(value) / LN2); if(value * (c = pow(2, -e)) < 1){ e--; c *= 2; } if(e + eBias >= 1){ value += rt / c; } else { value += rt * pow(2, 1 - eBias); } if(value * c >= 2){ e++; c /= 2; } if(e + eBias >= eMax){ m = 0; e = eMax; } else if(e + eBias >= 1){ m = (value * c - 1) * pow(2, mLen); e = e + eBias; } else { m = value * pow(2, eBias - 1) * pow(2, mLen); e = 0; } } for(; mLen >= 8; buffer[i++] = m & 255, m /= 256, mLen -= 8); e = e << mLen | m; eLen += mLen; for(; eLen > 0; buffer[i++] = e & 255, e /= 256, eLen -= 8); buffer[--i] |= s * 128; return buffer; }; var unpackIEEE754 = function(buffer, mLen, nBytes){ var eLen = nBytes * 8 - mLen - 1 , eMax = (1 << eLen) - 1 , eBias = eMax >> 1 , nBits = eLen - 7 , i = nBytes - 1 , s = buffer[i--] , e = s & 127 , m; s >>= 7; for(; nBits > 0; e = e * 256 + buffer[i], i--, nBits -= 8); m = e & (1 << -nBits) - 1; e >>= -nBits; nBits += mLen; for(; nBits > 0; m = m * 256 + buffer[i], i--, nBits -= 8); if(e === 0){ e = 1 - eBias; } else if(e === eMax){ return m ? NaN : s ? -Infinity : Infinity; } else { m = m + pow(2, mLen); e = e - eBias; } return (s ? -1 : 1) * m * pow(2, e - mLen); }; var unpackI32 = function(bytes){ return bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0]; }; var packI8 = function(it){ return [it & 0xff]; }; var packI16 = function(it){ return [it & 0xff, it >> 8 & 0xff]; }; var packI32 = function(it){ return [it & 0xff, it >> 8 & 0xff, it >> 16 & 0xff, it >> 24 & 0xff]; }; var packF64 = function(it){ return packIEEE754(it, 52, 8); }; var packF32 = function(it){ return packIEEE754(it, 23, 4); }; var addGetter = function(C, key, internal){ dP(C[PROTOTYPE], key, {get: function(){ return this[internal]; }}); }; var get = function(view, bytes, index, isLittleEndian){ var numIndex = +index , intIndex = toInteger(numIndex); if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); var store = view[$BUFFER]._b , start = intIndex + view[$OFFSET] , pack = store.slice(start, start + bytes); return isLittleEndian ? pack : pack.reverse(); }; var set = function(view, bytes, index, conversion, value, isLittleEndian){ var numIndex = +index , intIndex = toInteger(numIndex); if(numIndex != intIndex || intIndex < 0 || intIndex + bytes > view[$LENGTH])throw RangeError(WRONG_INDEX); var store = view[$BUFFER]._b , start = intIndex + view[$OFFSET] , pack = conversion(+value); for(var i = 0; i < bytes; i++)store[start + i] = pack[isLittleEndian ? i : bytes - i - 1]; }; var validateArrayBufferArguments = function(that, length){ anInstance(that, $ArrayBuffer, ARRAY_BUFFER); var numberLength = +length , byteLength = toLength(numberLength); if(numberLength != byteLength)throw RangeError(WRONG_LENGTH); return byteLength; }; if(!$typed.ABV){ $ArrayBuffer = function ArrayBuffer(length){ var byteLength = validateArrayBufferArguments(this, length); this._b = arrayFill.call(Array(byteLength), 0); this[$LENGTH] = byteLength; }; $DataView = function DataView(buffer, byteOffset, byteLength){ anInstance(this, $DataView, DATA_VIEW); anInstance(buffer, $ArrayBuffer, DATA_VIEW); var bufferLength = buffer[$LENGTH] , offset = toInteger(byteOffset); if(offset < 0 || offset > bufferLength)throw RangeError('Wrong offset!'); byteLength = byteLength === undefined ? bufferLength - offset : toLength(byteLength); if(offset + byteLength > bufferLength)throw RangeError(WRONG_LENGTH); this[$BUFFER] = buffer; this[$OFFSET] = offset; this[$LENGTH] = byteLength; }; if(DESCRIPTORS){ addGetter($ArrayBuffer, BYTE_LENGTH, '_l'); addGetter($DataView, BUFFER, '_b'); addGetter($DataView, BYTE_LENGTH, '_l'); addGetter($DataView, BYTE_OFFSET, '_o'); } redefineAll($DataView[PROTOTYPE], { getInt8: function getInt8(byteOffset){ return get(this, 1, byteOffset)[0] << 24 >> 24; }, getUint8: function getUint8(byteOffset){ return get(this, 1, byteOffset)[0]; }, getInt16: function getInt16(byteOffset /*, littleEndian */){ var bytes = get(this, 2, byteOffset, arguments[1]); return (bytes[1] << 8 | bytes[0]) << 16 >> 16; }, getUint16: function getUint16(byteOffset /*, littleEndian */){ var bytes = get(this, 2, byteOffset, arguments[1]); return bytes[1] << 8 | bytes[0]; }, getInt32: function getInt32(byteOffset /*, littleEndian */){ return unpackI32(get(this, 4, byteOffset, arguments[1])); }, getUint32: function getUint32(byteOffset /*, littleEndian */){ return unpackI32(get(this, 4, byteOffset, arguments[1])) >>> 0; }, getFloat32: function getFloat32(byteOffset /*, littleEndian */){ return unpackIEEE754(get(this, 4, byteOffset, arguments[1]), 23, 4); }, getFloat64: function getFloat64(byteOffset /*, littleEndian */){ return unpackIEEE754(get(this, 8, byteOffset, arguments[1]), 52, 8); }, setInt8: function setInt8(byteOffset, value){ set(this, 1, byteOffset, packI8, value); }, setUint8: function setUint8(byteOffset, value){ set(this, 1, byteOffset, packI8, value); }, setInt16: function setInt16(byteOffset, value /*, littleEndian */){ set(this, 2, byteOffset, packI16, value, arguments[2]); }, setUint16: function setUint16(byteOffset, value /*, littleEndian */){ set(this, 2, byteOffset, packI16, value, arguments[2]); }, setInt32: function setInt32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packI32, value, arguments[2]); }, setUint32: function setUint32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packI32, value, arguments[2]); }, setFloat32: function setFloat32(byteOffset, value /*, littleEndian */){ set(this, 4, byteOffset, packF32, value, arguments[2]); }, setFloat64: function setFloat64(byteOffset, value /*, littleEndian */){ set(this, 8, byteOffset, packF64, value, arguments[2]); } }); } else { if(!fails(function(){ new $ArrayBuffer; // eslint-disable-line no-new }) || !fails(function(){ new $ArrayBuffer(.5); // eslint-disable-line no-new })){ $ArrayBuffer = function ArrayBuffer(length){ return new BaseBuffer(validateArrayBufferArguments(this, length)); }; var ArrayBufferProto = $ArrayBuffer[PROTOTYPE] = BaseBuffer[PROTOTYPE]; for(var keys = gOPN(BaseBuffer), j = 0, key; keys.length > j; ){ if(!((key = keys[j++]) in $ArrayBuffer))hide($ArrayBuffer, key, BaseBuffer[key]); }; if(!LIBRARY)ArrayBufferProto.constructor = $ArrayBuffer; } // iOS Safari 7.x bug var view = new $DataView(new $ArrayBuffer(2)) , $setInt8 = $DataView[PROTOTYPE].setInt8; view.setInt8(0, 2147483648); view.setInt8(1, 2147483649); if(view.getInt8(0) || !view.getInt8(1))redefineAll($DataView[PROTOTYPE], { setInt8: function setInt8(byteOffset, value){ $setInt8.call(this, byteOffset, value << 24 >> 24); }, setUint8: function setUint8(byteOffset, value){ $setInt8.call(this, byteOffset, value << 24 >> 24); } }, true); } setToStringTag($ArrayBuffer, ARRAY_BUFFER); setToStringTag($DataView, DATA_VIEW); hide($DataView[PROTOTYPE], $typed.VIEW, true); exports[ARRAY_BUFFER] = $ArrayBuffer; exports[DATA_VIEW] = $DataView; /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6); $export($export.G + $export.W + $export.F * !__webpack_require__(232).ABV, { DataView: __webpack_require__(233).DataView }); /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Int8', 1, function(init){ return function Int8Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; if(__webpack_require__(4)){ var LIBRARY = __webpack_require__(26) , global = __webpack_require__(2) , fails = __webpack_require__(5) , $export = __webpack_require__(6) , $typed = __webpack_require__(232) , $buffer = __webpack_require__(233) , ctx = __webpack_require__(18) , anInstance = __webpack_require__(197) , propertyDesc = __webpack_require__(15) , hide = __webpack_require__(8) , redefineAll = __webpack_require__(202) , toInteger = __webpack_require__(36) , toLength = __webpack_require__(35) , toIndex = __webpack_require__(37) , toPrimitive = __webpack_require__(14) , has = __webpack_require__(3) , same = __webpack_require__(69) , classof = __webpack_require__(73) , isObject = __webpack_require__(11) , toObject = __webpack_require__(56) , isArrayIter = __webpack_require__(154) , create = __webpack_require__(44) , getPrototypeOf = __webpack_require__(57) , gOPN = __webpack_require__(48).f , getIterFn = __webpack_require__(156) , uid = __webpack_require__(17) , wks = __webpack_require__(23) , createArrayMethod = __webpack_require__(164) , createArrayIncludes = __webpack_require__(34) , speciesConstructor = __webpack_require__(199) , ArrayIterators = __webpack_require__(183) , Iterators = __webpack_require__(135) , $iterDetect = __webpack_require__(157) , setSpecies = __webpack_require__(186) , arrayFill = __webpack_require__(180) , arrayCopyWithin = __webpack_require__(177) , $DP = __webpack_require__(9) , $GOPD = __webpack_require__(49) , dP = $DP.f , gOPD = $GOPD.f , RangeError = global.RangeError , TypeError = global.TypeError , Uint8Array = global.Uint8Array , ARRAY_BUFFER = 'ArrayBuffer' , SHARED_BUFFER = 'Shared' + ARRAY_BUFFER , BYTES_PER_ELEMENT = 'BYTES_PER_ELEMENT' , PROTOTYPE = 'prototype' , ArrayProto = Array[PROTOTYPE] , $ArrayBuffer = $buffer.ArrayBuffer , $DataView = $buffer.DataView , arrayForEach = createArrayMethod(0) , arrayFilter = createArrayMethod(2) , arraySome = createArrayMethod(3) , arrayEvery = createArrayMethod(4) , arrayFind = createArrayMethod(5) , arrayFindIndex = createArrayMethod(6) , arrayIncludes = createArrayIncludes(true) , arrayIndexOf = createArrayIncludes(false) , arrayValues = ArrayIterators.values , arrayKeys = ArrayIterators.keys , arrayEntries = ArrayIterators.entries , arrayLastIndexOf = ArrayProto.lastIndexOf , arrayReduce = ArrayProto.reduce , arrayReduceRight = ArrayProto.reduceRight , arrayJoin = ArrayProto.join , arraySort = ArrayProto.sort , arraySlice = ArrayProto.slice , arrayToString = ArrayProto.toString , arrayToLocaleString = ArrayProto.toLocaleString , ITERATOR = wks('iterator') , TAG = wks('toStringTag') , TYPED_CONSTRUCTOR = uid('typed_constructor') , DEF_CONSTRUCTOR = uid('def_constructor') , ALL_CONSTRUCTORS = $typed.CONSTR , TYPED_ARRAY = $typed.TYPED , VIEW = $typed.VIEW , WRONG_LENGTH = 'Wrong length!'; var $map = createArrayMethod(1, function(O, length){ return allocate(speciesConstructor(O, O[DEF_CONSTRUCTOR]), length); }); var LITTLE_ENDIAN = fails(function(){ return new Uint8Array(new Uint16Array([1]).buffer)[0] === 1; }); var FORCED_SET = !!Uint8Array && !!Uint8Array[PROTOTYPE].set && fails(function(){ new Uint8Array(1).set({}); }); var strictToLength = function(it, SAME){ if(it === undefined)throw TypeError(WRONG_LENGTH); var number = +it , length = toLength(it); if(SAME && !same(number, length))throw RangeError(WRONG_LENGTH); return length; }; var toOffset = function(it, BYTES){ var offset = toInteger(it); if(offset < 0 || offset % BYTES)throw RangeError('Wrong offset!'); return offset; }; var validate = function(it){ if(isObject(it) && TYPED_ARRAY in it)return it; throw TypeError(it + ' is not a typed array!'); }; var allocate = function(C, length){ if(!(isObject(C) && TYPED_CONSTRUCTOR in C)){ throw TypeError('It is not a typed array constructor!'); } return new C(length); }; var speciesFromList = function(O, list){ return fromList(speciesConstructor(O, O[DEF_CONSTRUCTOR]), list); }; var fromList = function(C, list){ var index = 0 , length = list.length , result = allocate(C, length); while(length > index)result[index] = list[index++]; return result; }; var addGetter = function(it, key, internal){ dP(it, key, {get: function(){ return this._d[internal]; }}); }; var $from = function from(source /*, mapfn, thisArg */){ var O = toObject(source) , aLen = arguments.length , mapfn = aLen > 1 ? arguments[1] : undefined , mapping = mapfn !== undefined , iterFn = getIterFn(O) , i, length, values, result, step, iterator; if(iterFn != undefined && !isArrayIter(iterFn)){ for(iterator = iterFn.call(O), values = [], i = 0; !(step = iterator.next()).done; i++){ values.push(step.value); } O = values; } if(mapping && aLen > 2)mapfn = ctx(mapfn, arguments[2], 2); for(i = 0, length = toLength(O.length), result = allocate(this, length); length > i; i++){ result[i] = mapping ? mapfn(O[i], i) : O[i]; } return result; }; var $of = function of(/*...items*/){ var index = 0 , length = arguments.length , result = allocate(this, length); while(length > index)result[index] = arguments[index++]; return result; }; // iOS Safari 6.x fails here var TO_LOCALE_BUG = !!Uint8Array && fails(function(){ arrayToLocaleString.call(new Uint8Array(1)); }); var $toLocaleString = function toLocaleString(){ return arrayToLocaleString.apply(TO_LOCALE_BUG ? arraySlice.call(validate(this)) : validate(this), arguments); }; var proto = { copyWithin: function copyWithin(target, start /*, end */){ return arrayCopyWithin.call(validate(this), target, start, arguments.length > 2 ? arguments[2] : undefined); }, every: function every(callbackfn /*, thisArg */){ return arrayEvery(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, fill: function fill(value /*, start, end */){ // eslint-disable-line no-unused-vars return arrayFill.apply(validate(this), arguments); }, filter: function filter(callbackfn /*, thisArg */){ return speciesFromList(this, arrayFilter(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined)); }, find: function find(predicate /*, thisArg */){ return arrayFind(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }, findIndex: function findIndex(predicate /*, thisArg */){ return arrayFindIndex(validate(this), predicate, arguments.length > 1 ? arguments[1] : undefined); }, forEach: function forEach(callbackfn /*, thisArg */){ arrayForEach(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, indexOf: function indexOf(searchElement /*, fromIndex */){ return arrayIndexOf(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }, includes: function includes(searchElement /*, fromIndex */){ return arrayIncludes(validate(this), searchElement, arguments.length > 1 ? arguments[1] : undefined); }, join: function join(separator){ // eslint-disable-line no-unused-vars return arrayJoin.apply(validate(this), arguments); }, lastIndexOf: function lastIndexOf(searchElement /*, fromIndex */){ // eslint-disable-line no-unused-vars return arrayLastIndexOf.apply(validate(this), arguments); }, map: function map(mapfn /*, thisArg */){ return $map(validate(this), mapfn, arguments.length > 1 ? arguments[1] : undefined); }, reduce: function reduce(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars return arrayReduce.apply(validate(this), arguments); }, reduceRight: function reduceRight(callbackfn /*, initialValue */){ // eslint-disable-line no-unused-vars return arrayReduceRight.apply(validate(this), arguments); }, reverse: function reverse(){ var that = this , length = validate(that).length , middle = Math.floor(length / 2) , index = 0 , value; while(index < middle){ value = that[index]; that[index++] = that[--length]; that[length] = value; } return that; }, some: function some(callbackfn /*, thisArg */){ return arraySome(validate(this), callbackfn, arguments.length > 1 ? arguments[1] : undefined); }, sort: function sort(comparefn){ return arraySort.call(validate(this), comparefn); }, subarray: function subarray(begin, end){ var O = validate(this) , length = O.length , $begin = toIndex(begin, length); return new (speciesConstructor(O, O[DEF_CONSTRUCTOR]))( O.buffer, O.byteOffset + $begin * O.BYTES_PER_ELEMENT, toLength((end === undefined ? length : toIndex(end, length)) - $begin) ); } }; var $slice = function slice(start, end){ return speciesFromList(this, arraySlice.call(validate(this), start, end)); }; var $set = function set(arrayLike /*, offset */){ validate(this); var offset = toOffset(arguments[1], 1) , length = this.length , src = toObject(arrayLike) , len = toLength(src.length) , index = 0; if(len + offset > length)throw RangeError(WRONG_LENGTH); while(index < len)this[offset + index] = src[index++]; }; var $iterators = { entries: function entries(){ return arrayEntries.call(validate(this)); }, keys: function keys(){ return arrayKeys.call(validate(this)); }, values: function values(){ return arrayValues.call(validate(this)); } }; var isTAIndex = function(target, key){ return isObject(target) && target[TYPED_ARRAY] && typeof key != 'symbol' && key in target && String(+key) == String(key); }; var $getDesc = function getOwnPropertyDescriptor(target, key){ return isTAIndex(target, key = toPrimitive(key, true)) ? propertyDesc(2, target[key]) : gOPD(target, key); }; var $setDesc = function defineProperty(target, key, desc){ if(isTAIndex(target, key = toPrimitive(key, true)) && isObject(desc) && has(desc, 'value') && !has(desc, 'get') && !has(desc, 'set') // TODO: add validation descriptor w/o calling accessors && !desc.configurable && (!has(desc, 'writable') || desc.writable) && (!has(desc, 'enumerable') || desc.enumerable) ){ target[key] = desc.value; return target; } else return dP(target, key, desc); }; if(!ALL_CONSTRUCTORS){ $GOPD.f = $getDesc; $DP.f = $setDesc; } $export($export.S + $export.F * !ALL_CONSTRUCTORS, 'Object', { getOwnPropertyDescriptor: $getDesc, defineProperty: $setDesc }); if(fails(function(){ arrayToString.call({}); })){ arrayToString = arrayToLocaleString = function toString(){ return arrayJoin.call(this); } } var $TypedArrayPrototype$ = redefineAll({}, proto); redefineAll($TypedArrayPrototype$, $iterators); hide($TypedArrayPrototype$, ITERATOR, $iterators.values); redefineAll($TypedArrayPrototype$, { slice: $slice, set: $set, constructor: function(){ /* noop */ }, toString: arrayToString, toLocaleString: $toLocaleString }); addGetter($TypedArrayPrototype$, 'buffer', 'b'); addGetter($TypedArrayPrototype$, 'byteOffset', 'o'); addGetter($TypedArrayPrototype$, 'byteLength', 'l'); addGetter($TypedArrayPrototype$, 'length', 'e'); dP($TypedArrayPrototype$, TAG, { get: function(){ return this[TYPED_ARRAY]; } }); module.exports = function(KEY, BYTES, wrapper, CLAMPED){ CLAMPED = !!CLAMPED; var NAME = KEY + (CLAMPED ? 'Clamped' : '') + 'Array' , ISNT_UINT8 = NAME != 'Uint8Array' , GETTER = 'get' + KEY , SETTER = 'set' + KEY , TypedArray = global[NAME] , Base = TypedArray || {} , TAC = TypedArray && getPrototypeOf(TypedArray) , FORCED = !TypedArray || !$typed.ABV , O = {} , TypedArrayPrototype = TypedArray && TypedArray[PROTOTYPE]; var getter = function(that, index){ var data = that._d; return data.v[GETTER](index * BYTES + data.o, LITTLE_ENDIAN); }; var setter = function(that, index, value){ var data = that._d; if(CLAMPED)value = (value = Math.round(value)) < 0 ? 0 : value > 0xff ? 0xff : value & 0xff; data.v[SETTER](index * BYTES + data.o, value, LITTLE_ENDIAN); }; var addElement = function(that, index){ dP(that, index, { get: function(){ return getter(this, index); }, set: function(value){ return setter(this, index, value); }, enumerable: true }); }; if(FORCED){ TypedArray = wrapper(function(that, data, $offset, $length){ anInstance(that, TypedArray, NAME, '_d'); var index = 0 , offset = 0 , buffer, byteLength, length, klass; if(!isObject(data)){ length = strictToLength(data, true) byteLength = length * BYTES; buffer = new $ArrayBuffer(byteLength); } else if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ buffer = data; offset = toOffset($offset, BYTES); var $len = data.byteLength; if($length === undefined){ if($len % BYTES)throw RangeError(WRONG_LENGTH); byteLength = $len - offset; if(byteLength < 0)throw RangeError(WRONG_LENGTH); } else { byteLength = toLength($length) * BYTES; if(byteLength + offset > $len)throw RangeError(WRONG_LENGTH); } length = byteLength / BYTES; } else if(TYPED_ARRAY in data){ return fromList(TypedArray, data); } else { return $from.call(TypedArray, data); } hide(that, '_d', { b: buffer, o: offset, l: byteLength, e: length, v: new $DataView(buffer) }); while(index < length)addElement(that, index++); }); TypedArrayPrototype = TypedArray[PROTOTYPE] = create($TypedArrayPrototype$); hide(TypedArrayPrototype, 'constructor', TypedArray); } else if(!$iterDetect(function(iter){ // V8 works with iterators, but fails in many other cases // https://code.google.com/p/v8/issues/detail?id=4552 new TypedArray(null); // eslint-disable-line no-new new TypedArray(iter); // eslint-disable-line no-new }, true)){ TypedArray = wrapper(function(that, data, $offset, $length){ anInstance(that, TypedArray, NAME); var klass; // `ws` module bug, temporarily remove validation length for Uint8Array // https://github.com/websockets/ws/pull/645 if(!isObject(data))return new Base(strictToLength(data, ISNT_UINT8)); if(data instanceof $ArrayBuffer || (klass = classof(data)) == ARRAY_BUFFER || klass == SHARED_BUFFER){ return $length !== undefined ? new Base(data, toOffset($offset, BYTES), $length) : $offset !== undefined ? new Base(data, toOffset($offset, BYTES)) : new Base(data); } if(TYPED_ARRAY in data)return fromList(TypedArray, data); return $from.call(TypedArray, data); }); arrayForEach(TAC !== Function.prototype ? gOPN(Base).concat(gOPN(TAC)) : gOPN(Base), function(key){ if(!(key in TypedArray))hide(TypedArray, key, Base[key]); }); TypedArray[PROTOTYPE] = TypedArrayPrototype; if(!LIBRARY)TypedArrayPrototype.constructor = TypedArray; } var $nativeIterator = TypedArrayPrototype[ITERATOR] , CORRECT_ITER_NAME = !!$nativeIterator && ($nativeIterator.name == 'values' || $nativeIterator.name == undefined) , $iterator = $iterators.values; hide(TypedArray, TYPED_CONSTRUCTOR, true); hide(TypedArrayPrototype, TYPED_ARRAY, NAME); hide(TypedArrayPrototype, VIEW, true); hide(TypedArrayPrototype, DEF_CONSTRUCTOR, TypedArray); if(CLAMPED ? new TypedArray(1)[TAG] != NAME : !(TAG in TypedArrayPrototype)){ dP(TypedArrayPrototype, TAG, { get: function(){ return NAME; } }); } O[NAME] = TypedArray; $export($export.G + $export.W + $export.F * (TypedArray != Base), O); $export($export.S, NAME, { BYTES_PER_ELEMENT: BYTES, from: $from, of: $of }); if(!(BYTES_PER_ELEMENT in TypedArrayPrototype))hide(TypedArrayPrototype, BYTES_PER_ELEMENT, BYTES); $export($export.P, NAME, proto); setSpecies(NAME); $export($export.P + $export.F * FORCED_SET, NAME, {set: $set}); $export($export.P + $export.F * !CORRECT_ITER_NAME, NAME, $iterators); $export($export.P + $export.F * (TypedArrayPrototype.toString != arrayToString), NAME, {toString: arrayToString}); $export($export.P + $export.F * fails(function(){ new TypedArray(1).slice(); }), NAME, {slice: $slice}); $export($export.P + $export.F * (fails(function(){ return [1, 2].toLocaleString() != new TypedArray([1, 2]).toLocaleString() }) || !fails(function(){ TypedArrayPrototype.toLocaleString.call([1, 2]); })), NAME, {toLocaleString: $toLocaleString}); Iterators[NAME] = CORRECT_ITER_NAME ? $nativeIterator : $iterator; if(!LIBRARY && !CORRECT_ITER_NAME)hide(TypedArrayPrototype, ITERATOR, $iterator); }; } else module.exports = function(){ /* empty */ }; /***/ }, /* 237 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Uint8', 1, function(init){ return function Uint8Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); /***/ }, /* 238 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Uint8', 1, function(init){ return function Uint8ClampedArray(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }, true); /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Int16', 2, function(init){ return function Int16Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); /***/ }, /* 240 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Uint16', 2, function(init){ return function Uint16Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Int32', 4, function(init){ return function Int32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Uint32', 4, function(init){ return function Uint32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Float32', 4, function(init){ return function Float32Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(236)('Float64', 8, function(init){ return function Float64Array(data, byteOffset, length){ return init(this, data, byteOffset, length); }; }); /***/ }, /* 245 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/tc39/Array.prototype.includes var $export = __webpack_require__(6) , $includes = __webpack_require__(34)(true); $export($export.P, 'Array', { includes: function includes(el /*, fromIndex = 0 */){ return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined); } }); __webpack_require__(178)('includes'); /***/ }, /* 246 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/mathiasbynens/String.prototype.at var $export = __webpack_require__(6) , $at = __webpack_require__(125)(true); $export($export.P, 'String', { at: function at(pos){ return $at(this, pos); } }); /***/ }, /* 247 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = __webpack_require__(6) , $pad = __webpack_require__(248); $export($export.P, 'String', { padStart: function padStart(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, true); } }); /***/ }, /* 248 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-string-pad-start-end var toLength = __webpack_require__(35) , repeat = __webpack_require__(85) , defined = __webpack_require__(33); module.exports = function(that, maxLength, fillString, left){ var S = String(defined(that)) , stringLength = S.length , fillStr = fillString === undefined ? ' ' : String(fillString) , intMaxLength = toLength(maxLength); if(intMaxLength <= stringLength || fillStr == '')return S; var fillLen = intMaxLength - stringLength , stringFiller = repeat.call(fillStr, Math.ceil(fillLen / fillStr.length)); if(stringFiller.length > fillLen)stringFiller = stringFiller.slice(0, fillLen); return left ? stringFiller + S : S + stringFiller; }; /***/ }, /* 249 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/tc39/proposal-string-pad-start-end var $export = __webpack_require__(6) , $pad = __webpack_require__(248); $export($export.P, 'String', { padEnd: function padEnd(maxLength /*, fillString = ' ' */){ return $pad(this, maxLength, arguments.length > 1 ? arguments[1] : undefined, false); } }); /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim __webpack_require__(81)('trimLeft', function($trim){ return function trimLeft(){ return $trim(this, 1); }; }, 'trimStart'); /***/ }, /* 251 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/sebmarkbage/ecmascript-string-left-right-trim __webpack_require__(81)('trimRight', function($trim){ return function trimRight(){ return $trim(this, 2); }; }, 'trimEnd'); /***/ }, /* 252 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://tc39.github.io/String.prototype.matchAll/ var $export = __webpack_require__(6) , defined = __webpack_require__(33) , toLength = __webpack_require__(35) , isRegExp = __webpack_require__(128) , getFlags = __webpack_require__(188) , RegExpProto = RegExp.prototype; var $RegExpStringIterator = function(regexp, string){ this._r = regexp; this._s = string; }; __webpack_require__(136)($RegExpStringIterator, 'RegExp String', function next(){ var match = this._r.exec(this._s); return {value: match, done: match === null}; }); $export($export.P, 'String', { matchAll: function matchAll(regexp){ defined(this); if(!isRegExp(regexp))throw TypeError(regexp + ' is not a regexp!'); var S = String(this) , flags = 'flags' in RegExpProto ? String(regexp.flags) : getFlags.call(regexp) , rx = new RegExp(regexp.source, ~flags.indexOf('g') ? flags : 'g' + flags); rx.lastIndex = toLength(regexp.lastIndex); return new $RegExpStringIterator(rx, S); } }); /***/ }, /* 253 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(25)('asyncIterator'); /***/ }, /* 254 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(25)('observable'); /***/ }, /* 255 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-object-getownpropertydescriptors var $export = __webpack_require__(6) , ownKeys = __webpack_require__(221) , toIObject = __webpack_require__(30) , gOPD = __webpack_require__(49) , createProperty = __webpack_require__(155); $export($export.S, 'Object', { getOwnPropertyDescriptors: function getOwnPropertyDescriptors(object){ var O = toIObject(object) , getDesc = gOPD.f , keys = ownKeys(O) , result = {} , i = 0 , key; while(keys.length > i)createProperty(result, key = keys[i++], getDesc(O, key)); return result; } }); /***/ }, /* 256 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-object-values-entries var $export = __webpack_require__(6) , $values = __webpack_require__(257)(false); $export($export.S, 'Object', { values: function values(it){ return $values(it); } }); /***/ }, /* 257 */ /***/ function(module, exports, __webpack_require__) { var getKeys = __webpack_require__(28) , toIObject = __webpack_require__(30) , isEnum = __webpack_require__(42).f; module.exports = function(isEntries){ return function(it){ var O = toIObject(it) , keys = getKeys(O) , length = keys.length , i = 0 , result = [] , key; while(length > i)if(isEnum.call(O, key = keys[i++])){ result.push(isEntries ? [key, O[key]] : O[key]); } return result; }; }; /***/ }, /* 258 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/tc39/proposal-object-values-entries var $export = __webpack_require__(6) , $entries = __webpack_require__(257)(true); $export($export.S, 'Object', { entries: function entries(it){ return $entries(it); } }); /***/ }, /* 259 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , toObject = __webpack_require__(56) , aFunction = __webpack_require__(19) , $defineProperty = __webpack_require__(9); // B.2.2.2 Object.prototype.__defineGetter__(P, getter) __webpack_require__(4) && $export($export.P + __webpack_require__(260), 'Object', { __defineGetter__: function __defineGetter__(P, getter){ $defineProperty.f(toObject(this), P, {get: aFunction(getter), enumerable: true, configurable: true}); } }); /***/ }, /* 260 */ /***/ function(module, exports, __webpack_require__) { // Forced replacement prototype accessors methods module.exports = __webpack_require__(26)|| !__webpack_require__(5)(function(){ var K = Math.random(); // In FF throws only define methods __defineSetter__.call(null, K, function(){ /* empty */}); delete __webpack_require__(2)[K]; }); /***/ }, /* 261 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , toObject = __webpack_require__(56) , aFunction = __webpack_require__(19) , $defineProperty = __webpack_require__(9); // B.2.2.3 Object.prototype.__defineSetter__(P, setter) __webpack_require__(4) && $export($export.P + __webpack_require__(260), 'Object', { __defineSetter__: function __defineSetter__(P, setter){ $defineProperty.f(toObject(this), P, {set: aFunction(setter), enumerable: true, configurable: true}); } }); /***/ }, /* 262 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , toObject = __webpack_require__(56) , toPrimitive = __webpack_require__(14) , getPrototypeOf = __webpack_require__(57) , getOwnPropertyDescriptor = __webpack_require__(49).f; // B.2.2.4 Object.prototype.__lookupGetter__(P) __webpack_require__(4) && $export($export.P + __webpack_require__(260), 'Object', { __lookupGetter__: function __lookupGetter__(P){ var O = toObject(this) , K = toPrimitive(P, true) , D; do { if(D = getOwnPropertyDescriptor(O, K))return D.get; } while(O = getPrototypeOf(O)); } }); /***/ }, /* 263 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var $export = __webpack_require__(6) , toObject = __webpack_require__(56) , toPrimitive = __webpack_require__(14) , getPrototypeOf = __webpack_require__(57) , getOwnPropertyDescriptor = __webpack_require__(49).f; // B.2.2.5 Object.prototype.__lookupSetter__(P) __webpack_require__(4) && $export($export.P + __webpack_require__(260), 'Object', { __lookupSetter__: function __lookupSetter__(P){ var O = toObject(this) , K = toPrimitive(P, true) , D; do { if(D = getOwnPropertyDescriptor(O, K))return D.set; } while(O = getPrototypeOf(O)); } }); /***/ }, /* 264 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(6); $export($export.P + $export.R, 'Map', {toJSON: __webpack_require__(265)('Map')}); /***/ }, /* 265 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var classof = __webpack_require__(73) , from = __webpack_require__(266); module.exports = function(NAME){ return function toJSON(){ if(classof(this) != NAME)throw TypeError(NAME + "#toJSON isn't generic"); return from(this); }; }; /***/ }, /* 266 */ /***/ function(module, exports, __webpack_require__) { var forOf = __webpack_require__(198); module.exports = function(iter, ITERATOR){ var result = []; forOf(iter, false, result.push, result, ITERATOR); return result; }; /***/ }, /* 267 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/DavidBruant/Map-Set.prototype.toJSON var $export = __webpack_require__(6); $export($export.P + $export.R, 'Set', {toJSON: __webpack_require__(265)('Set')}); /***/ }, /* 268 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/ljharb/proposal-global var $export = __webpack_require__(6); $export($export.S, 'System', {global: __webpack_require__(2)}); /***/ }, /* 269 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/ljharb/proposal-is-error var $export = __webpack_require__(6) , cof = __webpack_require__(32); $export($export.S, 'Error', { isError: function isError(it){ return cof(it) === 'Error'; } }); /***/ }, /* 270 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = __webpack_require__(6); $export($export.S, 'Math', { iaddh: function iaddh(x0, x1, y0, y1){ var $x0 = x0 >>> 0 , $x1 = x1 >>> 0 , $y0 = y0 >>> 0; return $x1 + (y1 >>> 0) + (($x0 & $y0 | ($x0 | $y0) & ~($x0 + $y0 >>> 0)) >>> 31) | 0; } }); /***/ }, /* 271 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = __webpack_require__(6); $export($export.S, 'Math', { isubh: function isubh(x0, x1, y0, y1){ var $x0 = x0 >>> 0 , $x1 = x1 >>> 0 , $y0 = y0 >>> 0; return $x1 - (y1 >>> 0) - ((~$x0 & $y0 | ~($x0 ^ $y0) & $x0 - $y0 >>> 0) >>> 31) | 0; } }); /***/ }, /* 272 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = __webpack_require__(6); $export($export.S, 'Math', { imulh: function imulh(u, v){ var UINT16 = 0xffff , $u = +u , $v = +v , u0 = $u & UINT16 , v0 = $v & UINT16 , u1 = $u >> 16 , v1 = $v >> 16 , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); return u1 * v1 + (t >> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >> 16); } }); /***/ }, /* 273 */ /***/ function(module, exports, __webpack_require__) { // https://gist.github.com/BrendanEich/4294d5c212a6d2254703 var $export = __webpack_require__(6); $export($export.S, 'Math', { umulh: function umulh(u, v){ var UINT16 = 0xffff , $u = +u , $v = +v , u0 = $u & UINT16 , v0 = $v & UINT16 , u1 = $u >>> 16 , v1 = $v >>> 16 , t = (u1 * v0 >>> 0) + (u0 * v0 >>> 16); return u1 * v1 + (t >>> 16) + ((u0 * v1 >>> 0) + (t & UINT16) >>> 16); } }); /***/ }, /* 274 */ /***/ function(module, exports, __webpack_require__) { var metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , toMetaKey = metadata.key , ordinaryDefineOwnMetadata = metadata.set; metadata.exp({defineMetadata: function defineMetadata(metadataKey, metadataValue, target, targetKey){ ordinaryDefineOwnMetadata(metadataKey, metadataValue, anObject(target), toMetaKey(targetKey)); }}); /***/ }, /* 275 */ /***/ function(module, exports, __webpack_require__) { var Map = __webpack_require__(203) , $export = __webpack_require__(6) , shared = __webpack_require__(21)('metadata') , store = shared.store || (shared.store = new (__webpack_require__(207))); var getOrCreateMetadataMap = function(target, targetKey, create){ var targetMetadata = store.get(target); if(!targetMetadata){ if(!create)return undefined; store.set(target, targetMetadata = new Map); } var keyMetadata = targetMetadata.get(targetKey); if(!keyMetadata){ if(!create)return undefined; targetMetadata.set(targetKey, keyMetadata = new Map); } return keyMetadata; }; var ordinaryHasOwnMetadata = function(MetadataKey, O, P){ var metadataMap = getOrCreateMetadataMap(O, P, false); return metadataMap === undefined ? false : metadataMap.has(MetadataKey); }; var ordinaryGetOwnMetadata = function(MetadataKey, O, P){ var metadataMap = getOrCreateMetadataMap(O, P, false); return metadataMap === undefined ? undefined : metadataMap.get(MetadataKey); }; var ordinaryDefineOwnMetadata = function(MetadataKey, MetadataValue, O, P){ getOrCreateMetadataMap(O, P, true).set(MetadataKey, MetadataValue); }; var ordinaryOwnMetadataKeys = function(target, targetKey){ var metadataMap = getOrCreateMetadataMap(target, targetKey, false) , keys = []; if(metadataMap)metadataMap.forEach(function(_, key){ keys.push(key); }); return keys; }; var toMetaKey = function(it){ return it === undefined || typeof it == 'symbol' ? it : String(it); }; var exp = function(O){ $export($export.S, 'Reflect', O); }; module.exports = { store: store, map: getOrCreateMetadataMap, has: ordinaryHasOwnMetadata, get: ordinaryGetOwnMetadata, set: ordinaryDefineOwnMetadata, keys: ordinaryOwnMetadataKeys, key: toMetaKey, exp: exp }; /***/ }, /* 276 */ /***/ function(module, exports, __webpack_require__) { var metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , toMetaKey = metadata.key , getOrCreateMetadataMap = metadata.map , store = metadata.store; metadata.exp({deleteMetadata: function deleteMetadata(metadataKey, target /*, targetKey */){ var targetKey = arguments.length < 3 ? undefined : toMetaKey(arguments[2]) , metadataMap = getOrCreateMetadataMap(anObject(target), targetKey, false); if(metadataMap === undefined || !metadataMap['delete'](metadataKey))return false; if(metadataMap.size)return true; var targetMetadata = store.get(target); targetMetadata['delete'](targetKey); return !!targetMetadata.size || store['delete'](target); }}); /***/ }, /* 277 */ /***/ function(module, exports, __webpack_require__) { var metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , getPrototypeOf = __webpack_require__(57) , ordinaryHasOwnMetadata = metadata.has , ordinaryGetOwnMetadata = metadata.get , toMetaKey = metadata.key; var ordinaryGetMetadata = function(MetadataKey, O, P){ var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); if(hasOwn)return ordinaryGetOwnMetadata(MetadataKey, O, P); var parent = getPrototypeOf(O); return parent !== null ? ordinaryGetMetadata(MetadataKey, parent, P) : undefined; }; metadata.exp({getMetadata: function getMetadata(metadataKey, target /*, targetKey */){ return ordinaryGetMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); /***/ }, /* 278 */ /***/ function(module, exports, __webpack_require__) { var Set = __webpack_require__(206) , from = __webpack_require__(266) , metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , getPrototypeOf = __webpack_require__(57) , ordinaryOwnMetadataKeys = metadata.keys , toMetaKey = metadata.key; var ordinaryMetadataKeys = function(O, P){ var oKeys = ordinaryOwnMetadataKeys(O, P) , parent = getPrototypeOf(O); if(parent === null)return oKeys; var pKeys = ordinaryMetadataKeys(parent, P); return pKeys.length ? oKeys.length ? from(new Set(oKeys.concat(pKeys))) : pKeys : oKeys; }; metadata.exp({getMetadataKeys: function getMetadataKeys(target /*, targetKey */){ return ordinaryMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); }}); /***/ }, /* 279 */ /***/ function(module, exports, __webpack_require__) { var metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , ordinaryGetOwnMetadata = metadata.get , toMetaKey = metadata.key; metadata.exp({getOwnMetadata: function getOwnMetadata(metadataKey, target /*, targetKey */){ return ordinaryGetOwnMetadata(metadataKey, anObject(target) , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); /***/ }, /* 280 */ /***/ function(module, exports, __webpack_require__) { var metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , ordinaryOwnMetadataKeys = metadata.keys , toMetaKey = metadata.key; metadata.exp({getOwnMetadataKeys: function getOwnMetadataKeys(target /*, targetKey */){ return ordinaryOwnMetadataKeys(anObject(target), arguments.length < 2 ? undefined : toMetaKey(arguments[1])); }}); /***/ }, /* 281 */ /***/ function(module, exports, __webpack_require__) { var metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , getPrototypeOf = __webpack_require__(57) , ordinaryHasOwnMetadata = metadata.has , toMetaKey = metadata.key; var ordinaryHasMetadata = function(MetadataKey, O, P){ var hasOwn = ordinaryHasOwnMetadata(MetadataKey, O, P); if(hasOwn)return true; var parent = getPrototypeOf(O); return parent !== null ? ordinaryHasMetadata(MetadataKey, parent, P) : false; }; metadata.exp({hasMetadata: function hasMetadata(metadataKey, target /*, targetKey */){ return ordinaryHasMetadata(metadataKey, anObject(target), arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); /***/ }, /* 282 */ /***/ function(module, exports, __webpack_require__) { var metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , ordinaryHasOwnMetadata = metadata.has , toMetaKey = metadata.key; metadata.exp({hasOwnMetadata: function hasOwnMetadata(metadataKey, target /*, targetKey */){ return ordinaryHasOwnMetadata(metadataKey, anObject(target) , arguments.length < 3 ? undefined : toMetaKey(arguments[2])); }}); /***/ }, /* 283 */ /***/ function(module, exports, __webpack_require__) { var metadata = __webpack_require__(275) , anObject = __webpack_require__(10) , aFunction = __webpack_require__(19) , toMetaKey = metadata.key , ordinaryDefineOwnMetadata = metadata.set; metadata.exp({metadata: function metadata(metadataKey, metadataValue){ return function decorator(target, targetKey){ ordinaryDefineOwnMetadata( metadataKey, metadataValue, (targetKey !== undefined ? anObject : aFunction)(target), toMetaKey(targetKey) ); }; }}); /***/ }, /* 284 */ /***/ function(module, exports, __webpack_require__) { // https://github.com/rwaldron/tc39-notes/blob/master/es6/2014-09/sept-25.md#510-globalasap-for-enqueuing-a-microtask var $export = __webpack_require__(6) , microtask = __webpack_require__(201)() , process = __webpack_require__(2).process , isNode = __webpack_require__(32)(process) == 'process'; $export($export.G, { asap: function asap(fn){ var domain = isNode && process.domain; microtask(domain ? domain.bind(fn) : fn); } }); /***/ }, /* 285 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // https://github.com/zenparsing/es-observable var $export = __webpack_require__(6) , global = __webpack_require__(2) , core = __webpack_require__(7) , microtask = __webpack_require__(201)() , OBSERVABLE = __webpack_require__(23)('observable') , aFunction = __webpack_require__(19) , anObject = __webpack_require__(10) , anInstance = __webpack_require__(197) , redefineAll = __webpack_require__(202) , hide = __webpack_require__(8) , forOf = __webpack_require__(198) , RETURN = forOf.RETURN; var getMethod = function(fn){ return fn == null ? undefined : aFunction(fn); }; var cleanupSubscription = function(subscription){ var cleanup = subscription._c; if(cleanup){ subscription._c = undefined; cleanup(); } }; var subscriptionClosed = function(subscription){ return subscription._o === undefined; }; var closeSubscription = function(subscription){ if(!subscriptionClosed(subscription)){ subscription._o = undefined; cleanupSubscription(subscription); } }; var Subscription = function(observer, subscriber){ anObject(observer); this._c = undefined; this._o = observer; observer = new SubscriptionObserver(this); try { var cleanup = subscriber(observer) , subscription = cleanup; if(cleanup != null){ if(typeof cleanup.unsubscribe === 'function')cleanup = function(){ subscription.unsubscribe(); }; else aFunction(cleanup); this._c = cleanup; } } catch(e){ observer.error(e); return; } if(subscriptionClosed(this))cleanupSubscription(this); }; Subscription.prototype = redefineAll({}, { unsubscribe: function unsubscribe(){ closeSubscription(this); } }); var SubscriptionObserver = function(subscription){ this._s = subscription; }; SubscriptionObserver.prototype = redefineAll({}, { next: function next(value){ var subscription = this._s; if(!subscriptionClosed(subscription)){ var observer = subscription._o; try { var m = getMethod(observer.next); if(m)return m.call(observer, value); } catch(e){ try { closeSubscription(subscription); } finally { throw e; } } } }, error: function error(value){ var subscription = this._s; if(subscriptionClosed(subscription))throw value; var observer = subscription._o; subscription._o = undefined; try { var m = getMethod(observer.error); if(!m)throw value; value = m.call(observer, value); } catch(e){ try { cleanupSubscription(subscription); } finally { throw e; } } cleanupSubscription(subscription); return value; }, complete: function complete(value){ var subscription = this._s; if(!subscriptionClosed(subscription)){ var observer = subscription._o; subscription._o = undefined; try { var m = getMethod(observer.complete); value = m ? m.call(observer, value) : undefined; } catch(e){ try { cleanupSubscription(subscription); } finally { throw e; } } cleanupSubscription(subscription); return value; } } }); var $Observable = function Observable(subscriber){ anInstance(this, $Observable, 'Observable', '_f')._f = aFunction(subscriber); }; redefineAll($Observable.prototype, { subscribe: function subscribe(observer){ return new Subscription(observer, this._f); }, forEach: function forEach(fn){ var that = this; return new (core.Promise || global.Promise)(function(resolve, reject){ aFunction(fn); var subscription = that.subscribe({ next : function(value){ try { return fn(value); } catch(e){ reject(e); subscription.unsubscribe(); } }, error: reject, complete: resolve }); }); } }); redefineAll($Observable, { from: function from(x){ var C = typeof this === 'function' ? this : $Observable; var method = getMethod(anObject(x)[OBSERVABLE]); if(method){ var observable = anObject(method.call(x)); return observable.constructor === C ? observable : new C(function(observer){ return observable.subscribe(observer); }); } return new C(function(observer){ var done = false; microtask(function(){ if(!done){ try { if(forOf(x, false, function(it){ observer.next(it); if(done)return RETURN; }) === RETURN)return; } catch(e){ if(done)throw e; observer.error(e); return; } observer.complete(); } }); return function(){ done = true; }; }); }, of: function of(){ for(var i = 0, l = arguments.length, items = Array(l); i < l;)items[i] = arguments[i++]; return new (typeof this === 'function' ? this : $Observable)(function(observer){ var done = false; microtask(function(){ if(!done){ for(var i = 0; i < items.length; ++i){ observer.next(items[i]); if(done)return; } observer.complete(); } }); return function(){ done = true; }; }); } }); hide($Observable.prototype, OBSERVABLE, function(){ return this; }); $export($export.G, {Observable: $Observable}); __webpack_require__(186)('Observable'); /***/ }, /* 286 */ /***/ function(module, exports, __webpack_require__) { var $export = __webpack_require__(6) , $task = __webpack_require__(200); $export($export.G + $export.B, { setImmediate: $task.set, clearImmediate: $task.clear }); /***/ }, /* 287 */ /***/ function(module, exports, __webpack_require__) { var $iterators = __webpack_require__(183) , redefine = __webpack_require__(16) , global = __webpack_require__(2) , hide = __webpack_require__(8) , Iterators = __webpack_require__(135) , wks = __webpack_require__(23) , ITERATOR = wks('iterator') , TO_STRING_TAG = wks('toStringTag') , ArrayValues = Iterators.Array; for(var collections = ['NodeList', 'DOMTokenList', 'MediaList', 'StyleSheetList', 'CSSRuleList'], i = 0; i < 5; i++){ var NAME = collections[i] , Collection = global[NAME] , proto = Collection && Collection.prototype , key; if(proto){ if(!proto[ITERATOR])hide(proto, ITERATOR, ArrayValues); if(!proto[TO_STRING_TAG])hide(proto, TO_STRING_TAG, NAME); Iterators[NAME] = ArrayValues; for(key in $iterators)if(!proto[key])redefine(proto, key, $iterators[key], true); } } /***/ }, /* 288 */ /***/ function(module, exports, __webpack_require__) { // ie9- setTimeout & setInterval additional parameters fix var global = __webpack_require__(2) , $export = __webpack_require__(6) , invoke = __webpack_require__(76) , partial = __webpack_require__(289) , navigator = global.navigator , MSIE = !!navigator && /MSIE .\./.test(navigator.userAgent); // <- dirty ie9- check var wrap = function(set){ return MSIE ? function(fn, time /*, ...args */){ return set(invoke( partial, [].slice.call(arguments, 2), typeof fn == 'function' ? fn : Function(fn) ), time); } : set; }; $export($export.G + $export.B + $export.F * MSIE, { setTimeout: wrap(global.setTimeout), setInterval: wrap(global.setInterval) }); /***/ }, /* 289 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var path = __webpack_require__(290) , invoke = __webpack_require__(76) , aFunction = __webpack_require__(19); module.exports = function(/* ...pargs */){ var fn = aFunction(this) , length = arguments.length , pargs = Array(length) , i = 0 , _ = path._ , holder = false; while(length > i)if((pargs[i] = arguments[i++]) === _)holder = true; return function(/* ...args */){ var that = this , aLen = arguments.length , j = 0, k = 0, args; if(!holder && !aLen)return invoke(fn, pargs, that); args = pargs.slice(); if(holder)for(;length > j; j++)if(args[j] === _)args[j] = arguments[k++]; while(aLen > k)args.push(arguments[k++]); return invoke(fn, args, that); }; }; /***/ }, /* 290 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(2); /***/ } /******/ ]); // CommonJS export if(typeof module != 'undefined' && module.exports)module.exports = __e; // RequireJS export else if(typeof define == 'function' && define.amd)define(function(){return __e}); // Export to global object else __g.core = __e; }(1, 1);
__tests__/index.android.js
nb7123/RNapp
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
packages/material-ui-icons/src/Dock.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Dock = props => <SvgIcon {...props}> <path d="M8 23h8v-2H8v2zm8-21.99L8 1c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM16 15H8V5h8v10z" /> </SvgIcon>; Dock = pure(Dock); Dock.muiName = 'SvgIcon'; export default Dock;
ajax/libs/rxjs/2.3.6/rx.compat.js
stefanocudini/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (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; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // 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; }; } // 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; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); /** * Represents a disposable resource 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 () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var s = state; var id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; }(Scheduler.prototype)); (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); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var 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; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * 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) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * 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(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * 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.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (!onError) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * * @example * var res = source.takeLast(5); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * 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(); }); }); }; /** * 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(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each 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; 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(); }); }).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; 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)); }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each 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(); }); }).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 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 (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the 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)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); 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));
src/components/controls.js
isehrob/synapses-text
// block styles import React from 'react'; import { StyleButton } from './buttons'; import { BLOCK_TYPES, HEADER_TYPES, INLINE_STYLES } from '../utils/types'; export const BlockStyleControls = (props) => { const {editorState} = props; const selection = editorState.getSelection(); const blockType = editorState .getCurrentContent() .getBlockForKey(selection.getStartKey()) .getType(); return ( <div className={"RichEditor-controls " + props.className} style={props.extraStyle}> {BLOCK_TYPES.map((type, i) => <StyleButton key={type.label} active={type.style === blockType} onToggle={props.onToggle} style={type.style} tooltip={type.tooltip} > <type.label key={i} /> </StyleButton> )} <select onChange={props.onToggle} value={blockType} > {HEADER_TYPES.map((elem, i) => <option key={i} value={elem.style} className={elem.style} >{elem.label}</option> )} </select> </div> ); }; export const InlineStyleControls = (props) => { var currentStyle = props.editorState.getCurrentInlineStyle(); return ( <div className={"RichEditor-controls " + props.className} style={props.extraStyle}> {INLINE_STYLES.map((type, i) => <StyleButton key={type.label} active={currentStyle.has(type.style)} onToggle={props.onToggle} style={type.style} tooltip={type.tooltip} > <type.label key={i} /> </StyleButton> )} </div> ); };
src/svg-icons/action/line-style.js
pancho111203/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionLineStyle = (props) => ( <SvgIcon {...props}> <path d="M3 16h5v-2H3v2zm6.5 0h5v-2h-5v2zm6.5 0h5v-2h-5v2zM3 20h2v-2H3v2zm4 0h2v-2H7v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zM3 12h8v-2H3v2zm10 0h8v-2h-8v2zM3 4v4h18V4H3z"/> </SvgIcon> ); ActionLineStyle = pure(ActionLineStyle); ActionLineStyle.displayName = 'ActionLineStyle'; ActionLineStyle.muiName = 'SvgIcon'; export default ActionLineStyle;
ajax/libs/mobx/2.5.1/mobx.min.js
tonytomov/cdnjs
/** MobX - (c) Michel Weststrate 2015, 2016 - MIT Licensed */ "use strict";function e(e,n,r,o){return 1===arguments.length&&"function"==typeof e?D(e.name||"<unnamed action>",e):2===arguments.length&&"function"==typeof n?D(e,n):1===arguments.length&&"string"==typeof e?t(e):t(n).apply(null,arguments)}function t(e){return function(t,n,r){return r&&"function"==typeof r.value?(r.value=D(e,r.value),r.enumerable=!1,r.configurable=!0,r):Tt(e).apply(this,arguments)}}function n(e,t,n){var r="string"==typeof e?e:e.name||"<unnamed action>",o="function"==typeof e?e:t,i="function"==typeof e?t:n;return pt("function"==typeof o,"`runInAction` expects a function"),pt(0===o.length,"`runInAction` expects a function without arguments"),pt("string"==typeof r&&r.length>0,"actions should have valid names, got: '"+r+"'"),P(r,o,i,void 0)}function r(e){return"function"==typeof e&&e.isMobxAction===!0}function o(e,t,n){function r(){i(a)}var o,i,s;"string"==typeof e?(o=e,i=t,s=n):"function"==typeof e&&(o=e.name||"Autorun@"+lt(),i=e,s=t),Ve(i,"autorun methods cannot have modifiers"),pt("function"==typeof i,"autorun expects a function"),s&&(i=i.bind(s));var a=new Nt(o,function(){this.track(r)});return a.schedule(),a.getDisposer()}function i(e,t,n,r){var i,s,a,u;"string"==typeof e?(i=e,s=t,a=n,u=r):"function"==typeof e&&(i="When@"+lt(),s=e,a=t,u=n);var c=o(i,function(e){if(s.call(u)){e.dispose();var t=X();a.call(u),Y(t)}});return c}function s(e,t,n){return ft("`autorunUntil` is deprecated, please use `when`."),i.apply(null,arguments)}function a(e,t,n,r){function o(){s(l)}var i,s,a,u;"string"==typeof e?(i=e,s=t,a=n,u=r):"function"==typeof e&&(i=e.name||"AutorunAsync@"+lt(),s=e,a=t,u=n),void 0===a&&(a=1),u&&(s=s.bind(u));var c=!1,l=new Nt(i,function(){c||(c=!0,setTimeout(function(){c=!1,l.isDisposed||l.track(o)},a))});return l.schedule(),l.getDisposer()}function u(t,n,r,o,i,s){function a(){if(!w.isDisposed){var e=!1;w.track(function(){var t=b(w);e=mt(y,x,t),x=t}),m&&p&&l(x,w),m||e!==!0||l(x,w),m&&(m=!1)}}var u,c,l,p,f,h;"string"==typeof t?(u=t,c=n,l=r,p=o,f=i,h=s):(u=t.name||n.name||"Reaction@"+lt(),c=t,l=n,p=r,f=o,h=i),void 0===p&&(p=!1),void 0===f&&(f=0);var d=Ce(c,Ft.Reference),v=d[0],b=d[1],y=v===Ft.Structure;h&&(b=b.bind(h),l=e(u,l.bind(h)));var m=!0,g=!1,x=void 0,w=new Nt(u,function(){f<1?a():g||(g=!0,setTimeout(function(){g=!1,a()},f))});return w.schedule(),w.getDisposer()}function c(e,t,n,r){return"function"==typeof e&&arguments.length<3?"function"==typeof t?l(e,t,void 0):l(e,void 0,t):It.apply(null,arguments)}function l(e,t,n){var r=Ce(e,Ft.Recursive),o=r[0],i=r[1];return new Dt(i,n,o===Ft.Structure,i.name,t)}function p(e,t){pt("function"==typeof e&&1===e.length,"createTransformer expects a function that accepts one argument");var n={},r=$t.resetId,o=function(r){function o(t,n){r.call(this,function(){return e(n)},null,!1,"Transformer-"+e.name+"-"+t,void 0),this.sourceIdentifier=t,this.sourceObject=n}return kt(o,r),o.prototype.onBecomeUnobserved=function(){var e=this.value;r.prototype.onBecomeUnobserved.call(this),delete n[this.sourceIdentifier],t&&t(e,this.sourceObject)},o}(Dt);return function(e){r!==$t.resetId&&(n={},r=$t.resetId);var t=f(e),i=n[t];return i?i.get():(i=n[t]=new o(t,e),i.get())}}function f(e){if(null===e||"object"!=typeof e)throw new Error("[mobx] transform expected some kind of object, got: "+e);var t=e.$transformId;return void 0===t&&(t=lt(),wt(e,"$transformId",t)),t}function h(e,t){return z()||console.warn("[mobx.expr] 'expr' should only be used inside other reactive functions."),c(e,t).get()}function d(e){for(var t=[],n=1;n<arguments.length;n++)t[n-1]=arguments[n];return pt(arguments.length>=2,"extendObservable expected 2 or more arguments"),pt("object"==typeof e,"extendObservable expects an object as first argument"),pt(!(e instanceof en),"extendObservable should not be used on maps, use map.merge instead"),t.forEach(function(t){pt("object"==typeof t,"all arguments of extendObservable should be objects"),v(e,t,Ft.Recursive,null)}),e}function v(e,t,n,r){var o=Je(e,r,n);for(var i in t)if(gt(t,i)){if(e===t&&!Ot(e,i))continue;var s=Object.getOwnPropertyDescriptor(t,i);We(o,i,s)}return e}function b(e,t){return y(et(e,t))}function y(e){var t={name:e.name};return e.observing&&e.observing.length>0&&(t.dependencies=dt(e.observing).map(y)),t}function m(e,t){return g(et(e,t))}function g(e){var t={name:e.name};return ee(e)&&(t.observers=te(e).map(g)),t}function x(e,t,n){return"function"==typeof n?_(e,t,n):w(e,t)}function w(e,t){return bt(e)&&!Ze(e)?(ft("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),tt(A(e)).intercept(t)):tt(e).intercept(t)}function _(e,t,n){return bt(e)&&!Ze(e)?(ft("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),d(e,{property:e[t]}),_(e,t,n)):tt(e,t).intercept(n)}function O(e,t){if(null===e||void 0===e)return!1;if(void 0!==t){if(e instanceof en||e instanceof qt)throw new Error("[mobx.isObservable] isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead.");if(Ze(e)){var n=e.$mobx;return n.values&&!!n.values[t]}return!1}return!!e.$mobx||e instanceof Lt||e instanceof Nt||e instanceof Dt}function S(e,t,n){return pt(arguments.length>=2&&arguments.length<=3,"Illegal decorator config",t),St(e,t),pt(!n||!n.get,"@observable can not be used on getters, use @computed instead"),Et.apply(null,arguments)}function A(e,t){if(void 0===e&&(e=void 0),"string"==typeof arguments[1])return S.apply(null,arguments);if(pt(arguments.length<3,"observable expects zero, one or two arguments"),O(e))return e;var n=Ce(e,Ft.Recursive),r=n[0],o=n[1],i=r===Ft.Reference?jt.Reference:R(o);switch(i){case jt.Array:case jt.PlainObject:return Pe(o,r);case jt.Reference:case jt.ComplexObject:return new sn(o,r);case jt.ComplexFunction:throw new Error("[mobx.observable] To be able to make a function reactive it should not have arguments. If you need an observable reference to a function, use `observable(asReference(f))`");case jt.ViewFunction:return ft("Use `computed(expr)` instead of `observable(expr)`"),c(e,t)}pt(!1,"Illegal State")}function R(e){return null===e||void 0===e?jt.Reference:"function"==typeof e?e.length?jt.ComplexFunction:jt.ViewFunction:Array.isArray(e)||e instanceof qt?jt.Array:"object"==typeof e?bt(e)?jt.PlainObject:jt.ComplexObject:jt.Reference}function k(e,t,n,r){return"function"==typeof n?I(e,t,n,r):T(e,t,n)}function T(e,t,n){return bt(e)&&!Ze(e)?(ft("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),tt(A(e)).observe(t,n)):tt(e).observe(t,n)}function I(e,t,n,r){return bt(e)&&!Ze(e)?(ft("Passing plain objects to intercept / observe is deprecated and will be removed in 3.0"),d(e,{property:e[t]}),I(e,t,n,r)):tt(e,t).observe(n,r)}function E(e,t,n){function r(r){return t&&n.push([e,r]),r}if(void 0===t&&(t=!0),void 0===n&&(n=null),e instanceof Date||e instanceof RegExp)return e;if(t&&null===n&&(n=[]),t&&null!==e&&"object"==typeof e)for(var o=0,i=n.length;o<i;o++)if(n[o][0]===e)return n[o][1];if(!e)return e;if(Array.isArray(e)||e instanceof qt){var s=r([]),a=e.map(function(e){return E(e,t,n)});s.length=a.length;for(var o=0,i=a.length;o<i;o++)s[o]=a[o];return s}if(e instanceof en){var u=r({});return e.forEach(function(e,r){return u[r]=E(e,t,n)}),u}if(O(e)&&e.$mobx instanceof sn)return E(e(),t,n);if(e instanceof sn)return E(e.get(),t,n);if("object"==typeof e){var s=r({});for(var c in e)s[c]=E(e[c],t,n);return s}return e}function j(e,t,n){return void 0===t&&(t=!0),void 0===n&&(n=null),ft("toJSON is deprecated. Use toJS instead"),E.apply(null,arguments)}function L(e){return console.log(e),e}function C(e,t){switch(arguments.length){case 0:if(e=$t.trackingDerivation,!e)return L("whyRun() can only be used if a derivation is active, or by passing an computed value / reaction explicitly. If you invoked whyRun from inside a computation; the computation is currently suspended but re-evaluating because somebody requested it's value.");break;case 2:e=et(e,t)}return e=et(e),e instanceof Dt?L(e.whyRun()):e instanceof Nt?L(e.whyRun()):void pt(!1,"whyRun can only be used on reactions and computed values")}function D(e,t){pt("function"==typeof t,"`action` can only be invoked on functions"),pt("string"==typeof e&&e.length>0,"actions should have valid names, got: '"+e+"'");var n=function(){return P(e,t,this,arguments)};return n.isMobxAction=!0,n}function P(e,t,n,r){pt(!($t.trackingDerivation instanceof Dt),"Computed values or transformers should not invoke actions or trigger other side effects");var o,i=de();if(i){o=Date.now();var s=r&&r.length||0,a=new Array(s);if(s>0)for(var u=0;u<s;u++)a[u]=r[u];be({type:"action",name:e,fn:t,target:n,arguments:a})}var c=X();we(e,n,!1);var l=N(!0);try{return t.apply(n,r)}finally{U(l),_e(!1),Y(c),i&&ye({time:Date.now()-o})}}function V(e){return 0===arguments.length?(ft("`useStrict` without arguments is deprecated, use `isStrictModeEnabled()` instead"),$t.strictMode):(pt(null===$t.trackingDerivation,"It is not allowed to set `useStrict` when a derivation is running"),$t.strictMode=e,$t.allowStateChanges=!e,void 0)}function M(){return $t.strictMode}function $(e,t){var n=N(e),r=t();return U(n),r}function N(e){var t=$t.allowStateChanges;return $t.allowStateChanges=e,t}function U(e){$t.allowStateChanges=e}function B(e){switch(e.dependenciesState){case Pt.UP_TO_DATE:return!1;case Pt.NOT_TRACKING:case Pt.STALE:return!0;case Pt.POSSIBLY_STALE:var t=!0,n=X();try{for(var r=e.observing,o=r.length,i=0;i<o;i++){var s=r[i];if(s instanceof Dt&&(s.get(),e.dependenciesState===Pt.STALE))return t=!1,Y(n),!0}return t=!1,q(e),Y(n),!1}finally{t&&q(e)}}}function z(){return null!==$t.trackingDerivation}function F(){$t.allowStateChanges||pt(!1,$t.strictMode?"It is not allowed to create or change state outside an `action` when MobX is in strict mode. Wrap the current method in `action` if this state change is intended":"It is not allowed to change the state when a computed value or transformer is being evaluated. Use 'autorun' to create reactive functions with side-effects.")}function G(e,t){q(e),e.newObserving=new Array(e.observing.length+100),e.unboundDepsCount=0,e.runId=++$t.runId;var n=$t.trackingDerivation;$t.trackingDerivation=e;var r,o=!0;try{r=t.call(e),o=!1}finally{o?K(e):($t.trackingDerivation=n,J(e))}return r}function K(e){var t="[mobx] An uncaught exception occurred while calculating your computed value, autorun or transformer. Or inside the render() method of an observer based React component. These functions should never throw exceptions as MobX will not always be able to recover from them. "+("Please fix the error reported after this message or enable 'Pause on (caught) exceptions' in your debugger to find the root cause. In: '"+e.name+"'. ")+"For more details see https://github.com/mobxjs/mobx/issues/462";de()&&ve({type:"error",message:t}),console.warn(t),q(e),e.newObserving=null,e.unboundDepsCount=0,e.recoverFromError(),ae(),Z()}function J(e){var t=e.observing,n=e.observing=e.newObserving;e.newObserving=null;for(var r=0,o=e.unboundDepsCount,i=0;i<o;i++){var s=n[i];0===s.diffValue&&(s.diffValue=1,r!==i&&(n[r]=s),r++)}for(n.length=r,o=t.length;o--;){var s=t[o];0===s.diffValue&&oe(s,e),s.diffValue=0}for(;r--;){var s=n[r];1===s.diffValue&&(s.diffValue=0,re(s,e))}}function W(e){for(var t=e.observing,n=t.length;n--;)oe(t[n],e);e.dependenciesState=Pt.NOT_TRACKING,t.length=0}function H(e){var t=X(),n=e();return Y(t),n}function X(){var e=$t.trackingDerivation;return $t.trackingDerivation=null,e}function Y(e){$t.trackingDerivation=e}function q(e){if(e.dependenciesState!==Pt.UP_TO_DATE){e.dependenciesState=Pt.UP_TO_DATE;for(var t=e.observing,n=t.length;n--;)t[n].lowestObserverState=Pt.UP_TO_DATE}}function Q(){}function Z(){$t.resetId++;var e=new Mt;for(var t in e)Vt.indexOf(t)===-1&&($t[t]=e[t]);$t.allowStateChanges=!$t.strictMode}function ee(e){return e.observers&&e.observers.length>0}function te(e){return e.observers}function ne(e){for(var t=e.observers,n=e.observersIndexes,r=t.length,o=0;o<r;o++){var i=t[o].__mapid;o?pt(n[i]===o,"INTERNAL ERROR maps derivation.__mapid to index in list"):pt(!(i in n),"INTERNAL ERROR observer on index 0 shouldnt be held in map.")}pt(0===t.length||Object.keys(n).length===t.length-1,"INTERNAL ERROR there is no junk in map")}function re(e,t){var n=e.observers.length;n&&(e.observersIndexes[t.__mapid]=n),e.observers[n]=t,e.lowestObserverState>t.dependenciesState&&(e.lowestObserverState=t.dependenciesState)}function oe(e,t){if(1===e.observers.length)e.observers.length=0,ie(e);else{var n=e.observers,r=e.observersIndexes,o=n.pop();if(o!==t){var i=r[t.__mapid]||0;i?r[o.__mapid]=i:delete r[o.__mapid],n[i]=o}delete r[t.__mapid]}}function ie(e){e.isPendingUnobservation||(e.isPendingUnobservation=!0,$t.pendingUnobservations.push(e))}function se(){$t.inBatch++}function ae(){if(1===$t.inBatch){for(var e=$t.pendingUnobservations,t=0;t<e.length;t++){var n=e[t];n.isPendingUnobservation=!1,0===n.observers.length&&n.onBecomeUnobserved()}$t.pendingUnobservations=[]}$t.inBatch--}function ue(e){var t=$t.trackingDerivation;null!==t?t.runId!==e.lastAccessedBy&&(e.lastAccessedBy=t.runId,t.newObserving[t.unboundDepsCount++]=e):0===e.observers.length&&ie(e)}function ce(e,t){var n=te(e).reduce(function(e,t){return Math.min(e,t.dependenciesState)},2);if(!(n>=e.lowestObserverState))throw new Error("lowestObserverState is wrong for "+t+" because "+n+" < "+e.lowestObserverState)}function le(e){if(e.lowestObserverState!==Pt.STALE){e.lowestObserverState=Pt.STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Pt.UP_TO_DATE&&r.onBecomeStale(),r.dependenciesState=Pt.STALE}}}function pe(e){if(e.lowestObserverState!==Pt.STALE){e.lowestObserverState=Pt.STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Pt.POSSIBLY_STALE?r.dependenciesState=Pt.STALE:r.dependenciesState===Pt.UP_TO_DATE&&(e.lowestObserverState=Pt.UP_TO_DATE)}}}function fe(e){if(e.lowestObserverState===Pt.UP_TO_DATE){e.lowestObserverState=Pt.POSSIBLY_STALE;for(var t=e.observers,n=t.length;n--;){var r=t[n];r.dependenciesState===Pt.UP_TO_DATE&&(r.dependenciesState=Pt.POSSIBLY_STALE,r.onBecomeStale())}}}function he(){if(!($t.isRunningReactions===!0||$t.inTransaction>0)){$t.isRunningReactions=!0;for(var e=$t.pendingReactions,t=0;e.length>0;){if(++t===Ut)throw Z(),new Error("Reaction doesn't converge to a stable state after "+Ut+" iterations. Probably there is a cycle in the reactive function: "+e[0]);for(var n=e.splice(0),r=0,o=n.length;r<o;r++)n[r].runReaction()}$t.isRunningReactions=!1}}function de(){return Bt}function ve(e){if(!Bt)return!1;for(var t=$t.spyListeners,n=0,r=t.length;n<r;n++)t[n](e)}function be(e){var t=yt({},e,{spyReportStart:!0});ve(t)}function ye(e){ve(e?yt({},e,zt):zt)}function me(e){return $t.spyListeners.push(e),Bt=$t.spyListeners.length>0,ht(function(){var t=$t.spyListeners.indexOf(e);t!==-1&&$t.spyListeners.splice(t,1),Bt=$t.spyListeners.length>0})}function ge(e){return ft("trackTransitions is deprecated. Use mobx.spy instead"),"boolean"==typeof e&&(ft("trackTransitions only takes a single callback function. If you are using the mobx-react-devtools, please update them first"),e=arguments[1]),e?me(e):(ft("trackTransitions without callback has been deprecated and is a no-op now. If you are using the mobx-react-devtools, please update them first"),function(){})}function xe(e,t,n){void 0===t&&(t=void 0),void 0===n&&(n=!0),we(e.name||"anonymous transaction",t,n);var r=e.call(t);return _e(n),r}function we(e,t,n){void 0===t&&(t=void 0),void 0===n&&(n=!0),se(),$t.inTransaction+=1,n&&de()&&be({type:"transaction",target:t,name:e})}function _e(e){void 0===e&&(e=!0),0===--$t.inTransaction&&he(),e&&de()&&ye(),ae()}function Oe(e){return e.interceptors&&e.interceptors.length>0}function Se(e,t){var n=e.interceptors||(e.interceptors=[]);return n.push(t),ht(function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Ae(e,t){for(var n=X(),r=e.interceptors,o=0,i=r.length;o<i;o++)if(t=r[o](t),pt(!t||t.type,"Intercept handlers should return nothing or a change object"),!t)return null;return Y(n),t}function Re(e){return e.changeListeners&&e.changeListeners.length>0}function ke(e,t){var n=e.changeListeners||(e.changeListeners=[]);return n.push(t),ht(function(){var e=n.indexOf(t);e!==-1&&n.splice(e,1)})}function Te(e,t){var n=X(),r=e.changeListeners;if(r){r=r.slice();for(var o=0,i=r.length;o<i;o++)Array.isArray(t)?r[o].apply(null,t):r[o](t);Y(n)}}function Ie(e){return new Gt(e)}function Ee(e){return new Kt(e)}function je(e){return new Jt(e)}function Le(e,t){return Ge(e,t)}function Ce(e,t){return e instanceof Gt?[Ft.Reference,e.value]:e instanceof Kt?[Ft.Structure,e.value]:e instanceof Jt?[Ft.Flat,e.value]:[t,e]}function De(e){return e===Ie?Ft.Reference:e===Ee?Ft.Structure:e===je?Ft.Flat:(pt(void 0===e,"Cannot determine value mode from function. Please pass in one of these: mobx.asReference, mobx.asStructure or mobx.asFlat, got: "+e),Ft.Recursive)}function Pe(e,t,n){var r;if(O(e))return e;switch(t){case Ft.Reference:return e;case Ft.Flat:Ve(e,"Items inside 'asFlat' cannot have modifiers"),r=Ft.Reference;break;case Ft.Structure:Ve(e,"Items inside 'asStructure' cannot have modifiers"),r=Ft.Structure;break;case Ft.Recursive:o=Ce(e,Ft.Recursive),r=o[0],e=o[1];break;default:pt(!1,"Illegal State")}return Array.isArray(e)?Be(e,r,n):bt(e)&&Object.isExtensible(e)?v(e,e,r,n):e;var o}function Ve(e,t){if(e instanceof Gt||e instanceof Kt||e instanceof Jt)throw new Error("[mobx] asStructure / asReference / asFlat cannot be used here. "+t)}function Me(e){var t=$e(e),n=Ne(e);Object.defineProperty(qt.prototype,""+e,{enumerable:!1,configurable:!0,set:t,get:n})}function $e(e){return function(t){var n=this.$mobx,r=n.values;if(Ve(t,"Modifiers cannot be used on array values. For non-reactive array values use makeReactive(asFlat(array))."),e<r.length){F();var o=r[e];if(Oe(n)){var i=Ae(n,{type:"update",object:n.array,index:e,newValue:t});if(!i)return;t=i.newValue}t=n.makeReactiveArrayItem(t);var s=n.mode===Ft.Structure?!Rt(o,t):o!==t;s&&(r[e]=t,n.notifyArrayChildUpdate(e,t,o))}else{if(e!==r.length)throw new Error("[mobx.array] Index out of bounds, "+e+" is larger than "+r.length);n.spliceWithArray(e,0,[t])}}}function Ne(e){return function(){var t=this.$mobx;return t&&e<t.values.length?(t.atom.reportObserved(),t.values[e]):void 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")}}function Ue(e){for(var t=Ht;t<e;t++)Me(t);Ht=e}function Be(e,t,n){return new qt(e,t,n)}function ze(e){return ft("fastArray is deprecated. Please use `observable(asFlat([]))`"),Be(e,Ft.Flat,null)}function Fe(e){return e instanceof qt}function Ge(e,t){return new en(e,t)}function Ke(e){return e instanceof en}function Je(e,t,n){if(void 0===n&&(n=Ft.Recursive),Ze(e))return e.$mobx;bt(e)||(t=e.constructor.name+"@"+lt()),t||(t="ObservableObject@"+lt());var r=new tn(e,t,n);return _t(e,"$mobx",r),r}function We(e,t,n){e.values[t]?(pt("value"in n,"cannot redefine property "+t),e.target[t]=n.value):"value"in n?He(e,t,n.value,!0,void 0):He(e,t,n.get,!0,n.set)}function He(e,t,n,o,i){o&&St(e.target,t);var s,a=e.name+"."+t,u=!0;if(n instanceof sn)s=n,n.name=a,u=!1;else if(n instanceof Dt)s=n,n.name=a,n.scope||(n.scope=e.target);else if("function"!=typeof n||0!==n.length||r(n))if(n instanceof Kt&&"function"==typeof n.value&&0===n.value.length)s=new Dt(n.value,e.target,(!0),a,i);else{if(u=!1,Oe(e)){var c=Ae(e,{object:e.target,name:t,type:"add",newValue:n});if(!c)return;n=c.newValue}s=new sn(n,e.mode,a,(!1)),n=s.value}else s=new Dt(n,e.target,(!1),a,i);e.values[t]=s,o&&Object.defineProperty(e.target,t,u?Ye(t):Xe(t)),u||Qe(e,e.target,t,n)}function Xe(e){var t=nn[e];return t?t:nn[e]={configurable:!0,enumerable:!0,get:function(){return this.$mobx.values[e].get()},set:function(t){qe(this,e,t)}}}function Ye(e){var t=rn[e];return t?t:rn[e]={configurable:!0,enumerable:!1,get:function(){return this.$mobx.values[e].get()},set:function(t){return this.$mobx.values[e].set(t)}}}function qe(e,t,n){var r=e.$mobx,o=r.values[t];if(Oe(r)){var i=Ae(r,{type:"update",object:e,name:t,newValue:n});if(!i)return;n=i.newValue}if(n=o.prepareNewValue(n),n!==on){var s=Re(r),a=de(),i=Te||Re?{type:"update",object:e,oldValue:o.value,name:t,newValue:n}:null;a&&be(i),o.setNewValue(n),s&&Te(r,i),a&&ye()}}function Qe(e,t,n,r){var o=Re(e),i=de(),s=o||i?{type:"add",object:t,name:n,newValue:r}:null;i&&be(s),o&&Te(e,s),i&&ye()}function Ze(e){return"object"==typeof e&&null!==e&&(it(e),e.$mobx instanceof tn)}function et(e,t){if("object"==typeof e&&null!==e){if(Fe(e))return pt(void 0===t,"It is not possible to get index atoms from arrays"),e.$mobx.atom;if(Ke(e)){if(void 0===t)return et(e._keys);var n=e._data[t]||e._hasMap[t];return pt(!!n,"the entry '"+t+"' does not exist in the observable map '"+nt(e)+"'"),n}if(it(e),Ze(e)){pt(!!t,"please specify a property");var r=e.$mobx.values[t];return pt(!!r,"no observable property '"+t+"' found on the observable object '"+nt(e)+"'"),r}if(e instanceof Lt||e instanceof Dt||e instanceof Nt)return e}else if("function"==typeof e&&e.$mobx instanceof Nt)return e.$mobx;pt(!1,"Cannot obtain atom from "+e)}function tt(e,t){return pt(e,"Expection some object"),void 0!==t?tt(et(e,t)):e instanceof Lt||e instanceof Dt||e instanceof Nt?e:Ke(e)?e:(it(e),e.$mobx?e.$mobx:void pt(!1,"Cannot obtain administration from "+e))}function nt(e,t){var n;return n=void 0!==t?et(e,t):Ze(e)||Ke(e)?tt(e):et(e),n.name}function rt(e,t,n,r,o){function i(i,s,a,u){if(pt(o||st(arguments),"This function is a decorator, but it wasn't invoked like a decorator"),a){gt(i,"__mobxLazyInitializers")||wt(i,"__mobxLazyInitializers",i.__mobxLazyInitializers&&i.__mobxLazyInitializers.slice()||[]);var c=a.value,l=a.initializer;return i.__mobxLazyInitializers.push(function(t){e(t,s,l?l.call(t):c,u,a)}),{enumerable:r,configurable:!0,get:function(){return this.__mobxDidRunLazyInitializers!==!0&&it(this),t.call(this,s)},set:function(e){this.__mobxDidRunLazyInitializers!==!0&&it(this),n.call(this,s,e)}}}var p={enumerable:r,configurable:!0,get:function(){return this.__mobxInitializedProps&&this.__mobxInitializedProps[s]===!0||ot(this,s,void 0,e,u,a),t.call(this,s)},set:function(t){this.__mobxInitializedProps&&this.__mobxInitializedProps[s]===!0?n.call(this,s,t):ot(this,s,t,e,u,a)}};return arguments.length<3&&Object.defineProperty(i,s,p),p}return o?function(){if(st(arguments))return i.apply(null,arguments);var e=arguments;return function(t,n,r){return i(t,n,r,e)}}:i}function ot(e,t,n,r,o,i){gt(e,"__mobxInitializedProps")||wt(e,"__mobxInitializedProps",{}),e.__mobxInitializedProps[t]=!0,r(e,t,n,o,i)}function it(e){e.__mobxDidRunLazyInitializers!==!0&&e.__mobxLazyInitializers&&(wt(e,"__mobxDidRunLazyInitializers",!0),e.__mobxDidRunLazyInitializers&&e.__mobxLazyInitializers.forEach(function(t){return t(e)}))}function st(e){return(2===e.length||3===e.length)&&"string"==typeof e[1]}function at(){return"function"==typeof Symbol&&Symbol.iterator||"@@iterator"}function ut(e){pt(e[an]!==!0,"Illegal state: cannot recycle array as iterator"),_t(e,an,!0);var t=-1;return _t(e,"next",function(){return t++,{done:t>=this.length,value:t<this.length?this[t]:void 0}}),e}function ct(e,t){_t(e,at(),t)}function lt(){return++$t.mobxGuid}function pt(e,t,n){if(!e)throw new Error("[mobx] Invariant failed: "+t+(n?" in '"+n+"'":""))}function ft(e){ln.indexOf(e)===-1&&(ln.push(e),console.error("[mobx] Deprecated: "+e))}function ht(e){var t=!1;return function(){if(!t)return t=!0,e.apply(this,arguments)}}function dt(e){var t=[];return e.forEach(function(e){t.indexOf(e)===-1&&t.push(e)}),t}function vt(e,t,n){if(void 0===t&&(t=100),void 0===n&&(n=" - "),!e)return"";var r=e.slice(0,t);return""+r.join(n)+(e.length>t?" (... and "+(e.length-t)+"more)":"")}function bt(e){if(null===e||"object"!=typeof e)return!1;var t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}function yt(){for(var e=arguments[0],t=1,n=arguments.length;t<n;t++){var r=arguments[t];for(var o in r)gt(r,o)&&(e[o]=r[o])}return e}function mt(e,t,n){return e?!Rt(t,n):t!==n}function gt(e,t){return fn.call(e,t)}function xt(e,t){for(var n=0;n<t.length;n++)wt(e,t[n],e[t[n]])}function wt(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!0,configurable:!0,value:n})}function _t(e,t,n){Object.defineProperty(e,t,{enumerable:!1,writable:!1,configurable:!0,value:n})}function Ot(e,t){var n=Object.getOwnPropertyDescriptor(e,t);return!n||n.configurable!==!1&&n.writable!==!1}function St(e,t){pt(Ot(e,t),"Cannot make property '"+t+"' observable, it is not configurable and writable in the target object")}function At(e){var t=[];for(var n in e)t.push(n);return t}function Rt(e,t){if(null===e&&null===t)return!0;if(void 0===e&&void 0===t)return!0;var n=Array.isArray(e)||Fe(e);if(n!==(Array.isArray(t)||Fe(t)))return!1;if(n){if(e.length!==t.length)return!1;for(var r=e.length-1;r>=0;r--)if(!Rt(e[r],t[r]))return!1;return!0}if("object"==typeof e&&"object"==typeof t){if(null===e||null===t)return!1;if(At(e).length!==At(t).length)return!1;for(var o in e){if(!(o in t))return!1;if(!Rt(e[o],t[o]))return!1}return!0}return e===t}var kt=this&&this.__extends||function(e,t){function n(){this.constructor=e}for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)};Q(),exports.extras={allowStateChanges:$,getAtom:et,getDebugName:nt,getDependencyTree:b,getObserverTree:m,isComputingDerivation:z,isSpyEnabled:de,resetGlobalState:Z,spyReport:ve,spyReportEnd:ye,spyReportStart:be,trackTransitions:ge},exports._={getAdministration:tt,resetGlobalState:Z},"object"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx(module.exports);var Tt=rt(function(t,n,r,o,i){var s=o&&1===o.length?o[0]:r.name||n||"<unnamed action>",a=e(s,r);wt(t,n,a)},function(e){return this[e]},function(){pt(!1,"It is not allowed to assign new values to @action fields")},!1,!0);exports.action=e,exports.runInAction=n,exports.isAction=r,exports.autorun=o,exports.when=i,exports.autorunUntil=s,exports.autorunAsync=a,exports.reaction=u;var It=rt(function(e,t,n,r,o){pt("undefined"!=typeof o,"@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'. It looks like it was used on a property.");var i=o.get,s=o.set;pt("function"==typeof i,"@computed can only be used on getter functions, like: '@computed get myProps() { return ...; }'");var a=!1;r&&1===r.length&&r[0].asStructure===!0&&(a=!0);var u=Je(e,void 0,Ft.Recursive);He(u,t,a?Ee(i):i,!1,s)},function(e){var t=this.$mobx.values[e];if(void 0!==t)return t.get()},function(e,t){this.$mobx.values[e].set(t)},!1,!0);exports.computed=c,exports.createTransformer=p,exports.expr=h,exports.extendObservable=d,exports.intercept=x,exports.isObservable=O;var Et=rt(function(e,t,n){var r=N(!0);"function"==typeof n&&(n=Ie(n));var o=Je(e,void 0,Ft.Recursive);He(o,t,n,!0,void 0),U(r)},function(e){var t=this.$mobx.values[e];if(void 0!==t)return t.get()},function(e,t){qe(this,e,t)},!0,!1);exports.observable=A;var jt;!function(e){e[e.Reference=0]="Reference",e[e.PlainObject=1]="PlainObject",e[e.ComplexObject=2]="ComplexObject",e[e.Array=3]="Array",e[e.ViewFunction=4]="ViewFunction",e[e.ComplexFunction=5]="ComplexFunction"}(jt||(jt={})),exports.observe=k,exports.toJS=E,exports.toJSON=j,exports.whyRun=C,exports.useStrict=V,exports.isStrictModeEnabled=M;var Lt=function(){function e(e){void 0===e&&(e="Atom@"+lt()),this.name=e,this.isPendingUnobservation=!0,this.observers=[],this.observersIndexes={},this.diffValue=0,this.lastAccessedBy=0,this.lowestObserverState=Pt.NOT_TRACKING}return e.prototype.onBecomeUnobserved=function(){},e.prototype.reportObserved=function(){ue(this)},e.prototype.reportChanged=function(){we("propagatingAtomChange",null,!1),le(this),_e(!1)},e.prototype.toString=function(){return this.name},e}();exports.BaseAtom=Lt;var Ct=function(e){function t(t,n,r){void 0===t&&(t="Atom@"+lt()),void 0===n&&(n=pn),void 0===r&&(r=pn),e.call(this,t),this.name=t,this.onBecomeObservedHandler=n,this.onBecomeUnobservedHandler=r,this.isPendingUnobservation=!1,this.isBeingTracked=!1}return kt(t,e),t.prototype.reportObserved=function(){return se(),e.prototype.reportObserved.call(this),this.isBeingTracked||(this.isBeingTracked=!0,this.onBecomeObservedHandler()),ae(),!!$t.trackingDerivation},t.prototype.onBecomeUnobserved=function(){this.isBeingTracked=!1,this.onBecomeUnobservedHandler()},t}(Lt);exports.Atom=Ct;var Dt=function(){function e(e,t,n,r,o){this.derivation=e,this.scope=t,this.compareStructural=n,this.dependenciesState=Pt.NOT_TRACKING,this.observing=[],this.newObserving=null,this.isPendingUnobservation=!1,this.observers=[],this.observersIndexes={},this.diffValue=0,this.runId=0,this.lastAccessedBy=0,this.lowestObserverState=Pt.UP_TO_DATE,this.unboundDepsCount=0,this.__mapid="#"+lt(),this.value=void 0,this.isComputing=!1,this.isRunningSetter=!1,this.name=r||"ComputedValue@"+lt(),o&&(this.setter=D(r+"-setter",o))}return e.prototype.peek=function(){this.isComputing=!0;var e=N(!1),t=this.derivation.call(this.scope);return U(e),this.isComputing=!1,t},e.prototype.peekUntracked=function(){var e=!0;try{var t=this.peek();return e=!1,t}finally{e&&K(this)}},e.prototype.onBecomeStale=function(){fe(this)},e.prototype.onBecomeUnobserved=function(){pt(this.dependenciesState!==Pt.NOT_TRACKING,"INTERNAL ERROR only onBecomeUnobserved shouldn't be called twice in a row"),W(this),this.value=void 0},e.prototype.get=function(){pt(!this.isComputing,"Cycle detected in computation "+this.name,this.derivation),se(),1===$t.inBatch?B(this)&&(this.value=this.peekUntracked()):(ue(this),B(this)&&this.trackAndCompute()&&pe(this));var e=this.value;return ae(),e},e.prototype.recoverFromError=function(){this.isComputing=!1},e.prototype.set=function(e){if(this.setter){pt(!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 pt(!1,"[ComputedValue '"+this.name+"'] It is not possible to assign a new value to a computed value.")},e.prototype.trackAndCompute=function(){de()&&ve({object:this,type:"compute",fn:this.derivation,target:this.scope});var e=this.value,t=this.value=G(this,this.peek);return mt(this.compareStructural,t,e)},e.prototype.observe=function(e,t){var n=this,r=!0,i=void 0;return o(function(){var o=n.get();if(!r||t){var s=X();e(o,i),Y(s)}r=!1,i=o})},e.prototype.toJSON=function(){return this.get()},e.prototype.toString=function(){return this.name+"["+this.derivation.toString()+"]"},e.prototype.whyRun=function(){var e=Boolean($t.trackingDerivation),t=dt(this.isComputing?this.newObserving:this.observing).map(function(e){return e.name}),n=dt(te(this).map(function(e){return e.name}));return"\nWhyRun? computation '"+this.name+"':\n * Running because: "+(e?"[active] the value of this computation is needed by a reaction":this.isComputing?"[get] The value of this computed was requested outside a reaction":"[idle] not running at the moment")+"\n"+(this.dependenciesState===Pt.NOT_TRACKING?" * This computation is suspended (not in use by any reaction) and won't run automatically.\n\tDidn't expect this computation to be suspended at this point?\n\t 1. Make sure this computation is used by a reaction (reaction, autorun, observer).\n\t 2. Check whether you are using this computation synchronously (in the same stack as they reaction that needs it).\n":" * This computation will re-run if any of the following observables changes:\n "+vt(t)+"\n "+(this.isComputing&&e?" (... or any observable accessed during the remainder of the current run)":"")+"\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n * If the outcome of this computation changes, the following observers will be re-run:\n "+vt(n)+"\n"); },e}(),Pt;!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"}(Pt||(Pt={})),exports.IDerivationState=Pt,exports.untracked=H;var Vt=["mobxGuid","resetId","spyListeners","strictMode","runId"],Mt=function(){function e(){this.version=4,this.trackingDerivation=null,this.runId=0,this.mobxGuid=0,this.inTransaction=0,this.isRunningReactions=!1,this.inBatch=0,this.pendingUnobservations=[],this.pendingReactions=[],this.allowStateChanges=!0,this.strictMode=!1,this.resetId=0,this.spyListeners=[]}return e}(),$t=function(){var e=new Mt;if(global.__mobservableTrackingStack||global.__mobservableViewStack)throw new Error("[mobx] An incompatible version of mobservable is already loaded.");if(global.__mobxGlobal&&global.__mobxGlobal.version!==e.version)throw new Error("[mobx] An incompatible version of mobx is already loaded.");return global.__mobxGlobal?global.__mobxGlobal:global.__mobxGlobal=e}(),Nt=function(){function e(e,t){void 0===e&&(e="Reaction@"+lt()),this.name=e,this.onInvalidate=t,this.observing=[],this.newObserving=[],this.dependenciesState=Pt.NOT_TRACKING,this.diffValue=0,this.runId=0,this.unboundDepsCount=0,this.__mapid="#"+lt(),this.isDisposed=!1,this._isScheduled=!1,this._isTrackPending=!1,this._isRunning=!1}return e.prototype.onBecomeStale=function(){this.schedule()},e.prototype.schedule=function(){this._isScheduled||(this._isScheduled=!0,$t.pendingReactions.push(this),se(),he(),ae())},e.prototype.isScheduled=function(){return this._isScheduled},e.prototype.runReaction=function(){this.isDisposed||(this._isScheduled=!1,B(this)&&(this._isTrackPending=!0,this.onInvalidate(),this._isTrackPending&&de()&&ve({object:this,type:"scheduled-reaction"})))},e.prototype.track=function(e){se();var t,n=de();n&&(t=Date.now(),be({object:this,type:"reaction",fn:e})),this._isRunning=!0,G(this,e),this._isRunning=!1,this._isTrackPending=!1,this.isDisposed&&W(this),n&&ye({time:Date.now()-t}),ae()},e.prototype.recoverFromError=function(){this._isRunning=!1,this._isTrackPending=!1},e.prototype.dispose=function(){this.isDisposed||(this.isDisposed=!0,this._isRunning||(se(),W(this),ae()))},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.whyRun=function(){var e=dt(this._isRunning?this.newObserving:this.observing).map(function(e){return e.name});return"\nWhyRun? reaction '"+this.name+"':\n * Status: ["+(this.isDisposed?"stopped":this._isRunning?"running":this.isScheduled()?"scheduled":"idle")+"]\n * This reaction will re-run if any of the following observables changes:\n "+vt(e)+"\n "+(this._isRunning?" (... or any observable accessed during the remainder of the current run)":"")+"\n\tMissing items in this list?\n\t 1. Check whether all used values are properly marked as observable (use isObservable to verify)\n\t 2. Make sure you didn't dereference values too early. MobX observes props, not primitives. E.g: use 'person.name' instead of 'name' in your computation.\n"},e}();exports.Reaction=Nt;var Ut=100,Bt=!1,zt={spyReportEnd:!0};exports.spy=me,exports.transaction=xe;var Ft;!function(e){e[e.Recursive=0]="Recursive",e[e.Reference=1]="Reference",e[e.Structure=2]="Structure",e[e.Flat=3]="Flat"}(Ft||(Ft={})),exports.asReference=Ie,exports.asStructure=Ee,exports.asFlat=je;var Gt=function(){function e(e){this.value=e,Ve(e,"Modifiers are not allowed to be nested")}return e}(),Kt=function(){function e(e){this.value=e,Ve(e,"Modifiers are not allowed to be nested")}return e}(),Jt=function(){function e(e){this.value=e,Ve(e,"Modifiers are not allowed to be nested")}return e}();exports.asMap=Le;var Wt=function(){var e=!1,t={};return Object.defineProperty(t,"0",{set:function(){e=!0}}),Object.create(t)[0]=1,e===!1}(),Ht=0,Xt=function(){function e(){}return e}();Xt.prototype=[];var Yt=function(){function e(e,t,n,r){this.mode=t,this.array=n,this.owned=r,this.lastKnownLength=0,this.interceptors=null,this.changeListeners=null,this.atom=new Lt(e||"ObservableArray@"+lt())}return e.prototype.makeReactiveArrayItem=function(e){return Ve(e,"Array values cannot have modifiers"),this.mode===Ft.Flat||this.mode===Ft.Reference?e:Pe(e,this.mode,this.atom.name+"[..]")},e.prototype.intercept=function(e){return Se(this,e)},e.prototype.observe=function(e,t){return void 0===t&&(t=!1),t&&e({object:this.array,type:"splice",index:0,added:this.values.slice(),addedCount:this.values.length,removed:[],removedCount:0}),ke(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;e!==t&&(e>t?this.spliceWithArray(t,0,new Array(e-t)):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. Did you use peek() to change it?");this.lastKnownLength+=t,t>0&&e+t+1>Ht&&Ue(e+t+1)},e.prototype.spliceWithArray=function(e,t,n){F();var r=this.values.length;if(void 0===e?e=0:e>r?e=r:e<0&&(e=Math.max(0,r+e)),t=1===arguments.length?r-e:void 0===t||null===t?0:Math.max(0,Math.min(t,r-e)),void 0===n&&(n=[]),Oe(this)){var o=Ae(this,{object:this.array,type:"splice",index:e,removedCount:t,added:n});if(!o)return cn;t=o.removedCount,n=o.added}n=n.map(this.makeReactiveArrayItem,this);var i=n.length-t;this.updateArrayLength(r,i);var s=(a=this.values).splice.apply(a,[e,t].concat(n));return 0===t&&0===n.length||this.notifyArraySplice(e,n,s),s;var a},e.prototype.notifyArrayChildUpdate=function(e,t,n){var r=!this.owned&&de(),o=Re(this),i=o||r?{object:this.array,type:"update",index:e,newValue:t,oldValue:n}:null;r&&be(i),this.atom.reportChanged(),o&&Te(this,i),r&&ye()},e.prototype.notifyArraySplice=function(e,t,n){var r=!this.owned&&de(),o=Re(this),i=o||r?{object:this.array,type:"splice",index:e,removed:n,added:t,removedCount:n.length,addedCount:t.length}:null;r&&be(i),this.atom.reportChanged(),o&&Te(this,i),r&&ye()},e}(),qt=function(e){function t(t,n,r,o){void 0===o&&(o=!1),e.call(this);var i=new Yt(r,n,this,o);_t(this,"$mobx",i),t&&t.length?(i.updateArrayLength(0,t.length),i.values=t.map(i.makeReactiveArrayItem,i),i.notifyArraySplice(0,i.values.slice(),cn)):i.values=[],Wt&&Object.defineProperty(i.array,"0",Qt)}return kt(t,e),t.prototype.intercept=function(e){return this.$mobx.intercept(e)},t.prototype.observe=function(e,t){return void 0===t&&(t=!1),this.$mobx.observe(e,t)},t.prototype.clear=function(){return this.splice(0)},t.prototype.concat=function(){for(var e=[],t=0;t<arguments.length;t++)e[t-0]=arguments[t];return this.$mobx.atom.reportObserved(),Array.prototype.concat.apply(this.slice(),e.map(function(e){return Fe(e)?e.slice():e}))},t.prototype.replace=function(e){return this.$mobx.spliceWithArray(0,this.$mobx.values.length,e)},t.prototype.toJS=function(){return this.slice()},t.prototype.toJSON=function(){return this.toJS()},t.prototype.peek=function(){return this.$mobx.values},t.prototype.find=function(e,t,n){void 0===n&&(n=0),this.$mobx.atom.reportObserved();for(var r=this.$mobx.values,o=r.length,i=n;i<o;i++)if(e.call(t,r[i],i,this))return r[i]},t.prototype.splice=function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];switch(arguments.length){case 0:return[];case 1:return this.$mobx.spliceWithArray(e);case 2:return this.$mobx.spliceWithArray(e,t)}return this.$mobx.spliceWithArray(e,t,n)},t.prototype.push=function(){for(var e=[],t=0;t<arguments.length;t++)e[t-0]=arguments[t];var n=this.$mobx;return n.spliceWithArray(n.values.length,0,e),n.values.length},t.prototype.pop=function(){return this.splice(Math.max(this.$mobx.values.length-1,0),1)[0]},t.prototype.shift=function(){return this.splice(0,1)[0]},t.prototype.unshift=function(){for(var e=[],t=0;t<arguments.length;t++)e[t-0]=arguments[t];var n=this.$mobx;return n.spliceWithArray(0,0,e),n.values.length},t.prototype.reverse=function(){this.$mobx.atom.reportObserved();var e=this.slice();return e.reverse.apply(e,arguments)},t.prototype.sort=function(e){this.$mobx.atom.reportObserved();var t=this.slice();return t.sort.apply(t,arguments)},t.prototype.remove=function(e){var t=this.$mobx.values.indexOf(e);return t>-1&&(this.splice(t,1),!0)},t.prototype.toString=function(){return"[mobx.array] "+Array.prototype.toString.apply(this.$mobx.values,arguments)},t.prototype.toLocaleString=function(){return"[mobx.array] "+Array.prototype.toLocaleString.apply(this.$mobx.values,arguments)},t}(Xt);ct(qt.prototype,function(){return ut(this.slice())}),xt(qt.prototype,["constructor","intercept","observe","clear","concat","replace","toJS","toJSON","peek","find","splice","push","pop","shift","unshift","reverse","sort","remove","toString","toLocaleString"]),Object.defineProperty(qt.prototype,"length",{enumerable:!1,configurable:!0,get:function(){return this.$mobx.getArrayLength()},set:function(e){this.$mobx.setArrayLength(e)}}),["every","filter","forEach","indexOf","join","lastIndexOf","map","reduce","reduceRight","slice","some"].forEach(function(e){var t=Array.prototype[e];wt(qt.prototype,e,function(){return this.$mobx.atom.reportObserved(),t.apply(this.$mobx.values,arguments)})});var Qt={configurable:!0,enumerable:!1,set:$e(0),get:Ne(0)};Ue(1e3),exports.fastArray=ze,exports.isObservableArray=Fe;var Zt={},en=function(){function e(e,t){var n=this;this.$mobx=Zt,this._data={},this._hasMap={},this.name="ObservableMap@"+lt(),this._keys=new qt(null,Ft.Reference,this.name+".keys()",(!0)),this.interceptors=null,this.changeListeners=null,this._valueMode=De(t),this._valueMode===Ft.Flat&&(this._valueMode=Ft.Reference),$(!0,function(){bt(e)?n.merge(e):Array.isArray(e)&&e.forEach(function(e){var t=e[0],r=e[1];return n.set(t,r)})})}return e.prototype._has=function(e){return"undefined"!=typeof this._data[e]},e.prototype.has=function(e){return!!this.isValidKey(e)&&(e=""+e,this._hasMap[e]?this._hasMap[e].get():this._updateHasMapEntry(e,!1).get())},e.prototype.set=function(e,t){this.assertValidKey(e),e=""+e;var n=this._has(e);if(Ve(t,"[mobx.map.set] Expected unwrapped value to be inserted to key '"+e+"'. If you need to use modifiers pass them as second argument to the constructor"),Oe(this)){var r=Ae(this,{type:n?"update":"add",object:this,newValue:t,name:e});if(!r)return;t=r.newValue}n?this._updateValue(e,t):this._addValue(e,t)},e.prototype.delete=function(e){var t=this;if(this.assertValidKey(e),e=""+e,Oe(this)){var n=Ae(this,{type:"delete",object:this,name:e});if(!n)return!1}if(this._has(e)){var r=de(),o=Re(this),n=o||r?{type:"delete",object:this,oldValue:this._data[e].value,name:e}:null;return r&&be(n),xe(function(){t._keys.remove(e),t._updateHasMapEntry(e,!1);var n=t._data[e];n.setNewValue(void 0),t._data[e]=void 0},void 0,!1),o&&Te(this,n),r&&ye(),!0}return!1},e.prototype._updateHasMapEntry=function(e,t){var n=this._hasMap[e];return n?n.setNewValue(t):n=this._hasMap[e]=new sn(t,Ft.Reference,this.name+"."+e+"?",(!1)),n},e.prototype._updateValue=function(e,t){var n=this._data[e];if(t=n.prepareNewValue(t),t!==on){var r=de(),o=Re(this),i=o||r?{type:"update",object:this,oldValue:n.value,name:e,newValue:t}:null;r&&be(i),n.setNewValue(t),o&&Te(this,i),r&&ye()}},e.prototype._addValue=function(e,t){var n=this;xe(function(){var r=n._data[e]=new sn(t,n._valueMode,n.name+"."+e,(!1));t=r.value,n._updateHasMapEntry(e,!0),n._keys.push(e)},void 0,!1);var r=de(),o=Re(this),i=o||r?{type:"add",object:this,name:e,newValue:t}:null;r&&be(i),o&&Te(this,i),r&&ye()},e.prototype.get=function(e){if(e=""+e,this.has(e))return this._data[e].get()},e.prototype.keys=function(){return ut(this._keys.slice())},e.prototype.values=function(){return ut(this._keys.map(this.get,this))},e.prototype.entries=function(){var e=this;return ut(this._keys.map(function(t){return[t,e.get(t)]}))},e.prototype.forEach=function(e,t){var n=this;this.keys().forEach(function(r){return e.call(t,n.get(r),r)})},e.prototype.merge=function(t){var n=this;return xe(function(){t instanceof e?t.keys().forEach(function(e){return n.set(e,t.get(e))}):Object.keys(t).forEach(function(e){return n.set(e,t[e])})},void 0,!1),this},e.prototype.clear=function(){var e=this;xe(function(){H(function(){e.keys().forEach(e.delete,e)})},void 0,!1)},Object.defineProperty(e.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),e.prototype.toJS=function(){var e=this,t={};return this.keys().forEach(function(n){return t[n]=e.get(n)}),t},e.prototype.toJs=function(){return ft("toJs is deprecated, use toJS instead"),this.toJS()},e.prototype.toJSON=function(){return this.toJS()},e.prototype.isValidKey=function(e){return null!==e&&void 0!==e&&("string"==typeof e||"number"==typeof e||"boolean"==typeof e)},e.prototype.assertValidKey=function(e){if(!this.isValidKey(e))throw new Error("[mobx.map] Invalid key: '"+e+"'")},e.prototype.toString=function(){var e=this;return this.name+"[{ "+this.keys().map(function(t){return t+": "+e.get(t)}).join(", ")+" }]"},e.prototype.observe=function(e,t){return pt(t!==!0,"`observe` doesn't support the fire immediately property for observable maps."),ke(this,e)},e.prototype.intercept=function(e){return Se(this,e)},e}();exports.ObservableMap=en,ct(en.prototype,function(){return this.entries()}),exports.map=Ge,exports.isObservableMap=Ke;var tn=function(){function e(e,t,n){this.target=e,this.name=t,this.mode=n,this.values={},this.changeListeners=null,this.interceptors=null}return e.prototype.observe=function(e,t){return pt(t!==!0,"`observe` doesn't support the fire immediately property for observable objects."),ke(this,e)},e.prototype.intercept=function(e){return Se(this,e)},e}(),nn={},rn={};exports.isObservableObject=Ze;var on={},sn=function(e){function t(t,n,r,o){void 0===r&&(r="ObservableValue@"+lt()),void 0===o&&(o=!0),e.call(this,r),this.mode=n,this.hasUnreportedChange=!1,this.value=void 0;var i=Ce(t,Ft.Recursive),s=i[0],a=i[1];this.mode===Ft.Recursive&&(this.mode=s),this.value=Pe(a,this.mode,this.name),o&&de()&&ve({type:"create",object:this,newValue:this.value})}return kt(t,e),t.prototype.set=function(e){var t=this.value;if(e=this.prepareNewValue(e),e!==on){var n=de();n&&be({type:"update",object:this,newValue:e,oldValue:t}),this.setNewValue(e),n&&ye()}},t.prototype.prepareNewValue=function(e){if(Ve(e,"Modifiers cannot be used on non-initial values."),F(),Oe(this)){var t=Ae(this,{object:this,type:"update",newValue:e});if(!t)return on;e=t.newValue}var n=mt(this.mode===Ft.Structure,this.value,e);return n?Pe(e,this.mode,this.name):on},t.prototype.setNewValue=function(e){var t=this.value;this.value=e,this.reportChanged(),Re(this)&&Te(this,[e,t])},t.prototype.get=function(){return this.reportObserved(),this.value},t.prototype.intercept=function(e){return Se(this,e)},t.prototype.observe=function(e,t){return t&&e(this.value,void 0),ke(this,e)},t.prototype.toJSON=function(){return this.get()},t.prototype.toString=function(){return this.name+"["+this.value+"]"},t}(Lt),an="__$$iterating",un=function(){function e(){this.listeners=[],ft("extras.SimpleEventEmitter is deprecated and will be removed in the next major release")}return e.prototype.emit=function(){for(var e=this.listeners.slice(),t=0,n=e.length;t<n;t++)e[t].apply(null,arguments)},e.prototype.on=function(e){var t=this;return this.listeners.push(e),ht(function(){var n=t.listeners.indexOf(e);n!==-1&&t.listeners.splice(n,1)})},e.prototype.once=function(e){var t=this.on(function(){t(),e.apply(this,arguments)});return t},e}();exports.SimpleEventEmitter=un;var cn=[];Object.freeze(cn);var ln=[],pn=function(){},fn=Object.prototype.hasOwnProperty; //# sourceMappingURL=lib/mobx.min.js.map
fluxible-router/components/Timestamp.js
sensduo/flux-examples
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ import React from 'react'; import updateTime from '../actions/updateTime'; import TimeStore from '../stores/TimeStore'; import { connectToStores } from 'fluxible-addons-react'; @connectToStores([TimeStore], (context) => { return context.getStore(TimeStore).getState() }) class Timestamp extends React.Component { static contextTypes = { getStore: React.PropTypes.func, executeAction: React.PropTypes.func }; constructor(props, context) { super(props, context); } onReset() { this.context.executeAction(updateTime); } render() { return ( <em onClick={this.onReset.bind(this)} style={{fontSize: '.8em'}}>{this.props.time}</em> ); } } export default Timestamp;
app/javascript/mastodon/components/setting_text.js
5thfloor/ichiji-social
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; export default class SettingText extends React.PureComponent { static propTypes = { settings: ImmutablePropTypes.map.isRequired, settingKey: PropTypes.array.isRequired, label: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, }; handleChange = (e) => { this.props.onChange(this.props.settingKey, e.target.value); } render () { const { settings, settingKey, label } = this.props; return ( <label> <span style={{ display: 'none' }}>{label}</span> <input className='setting-text' value={settings.getIn(settingKey)} onChange={this.handleChange} placeholder={label} /> </label> ); } }
storybook/stories/progress-circle/gauge.js
JesperLekland/react-native-svg-charts
import React from 'react' import { ProgressCircle } from 'react-native-svg-charts' class ProgressCircleExample extends React.PureComponent { render() { return ( <ProgressCircle style={{ height: 200, marginTop: 10 }} progress={0.7} progressColor={'rgb(134, 65, 244)'} startAngle={-Math.PI * 0.8} endAngle={Math.PI * 0.8} /> ) } } export default ProgressCircleExample
src/router.js
alxyee/berkeley-onederful-demo
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-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'; function decodeParam(val) { if (!(typeof val === 'string' || val.length === 0)) { return val; } try { return decodeURIComponent(val); } catch (err) { if (err instanceof URIError) { err.message = `Failed to decode param '${val}'`; err.status = 400; } throw err; } } // Match the provided URL path pattern to an actual URI string. For example: // matchURI({ path: '/posts/:id' }, '/dummy') => null // matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 } function matchURI(route, path) { const match = route.pattern.exec(path); if (!match) { return null; } const params = Object.create(null); for (let i = 1; i < match.length; i += 1) { params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined; } return params; } // Find the route matching the specified location (context), fetch the required data, // instantiate and return a React component function resolve(routes, context) { for (const route of routes) { // eslint-disable-line no-restricted-syntax const params = matchURI(route, context.error ? '/error' : context.pathname); if (!params) { continue; // eslint-disable-line no-continue } // Check if the route has any data requirements, for example: // { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' } if (route.data) { // Load page component and all required data in parallel const keys = Object.keys(route.data); return Promise.all([ route.load(), ...keys.map((key) => { const query = route.data[key]; const method = query.substring(0, query.indexOf(' ')); // GET let url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id // TODO: Optimize Object.keys(params).forEach((k) => { url = url.replace(`${k}`, params[k]); }); return fetch(url, { method }).then(resp => resp.json()); }), ]).then(([Page, ...data]) => { const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {}); return <Page route={{ ...route, params }} error={context.error} {...props} />; }); } return route.load().then(Page => <Page route={{ ...route, params }} error={context.error} />); } const error = new Error('Page not found'); error.status = 404; return Promise.reject(error); } export default { resolve };
.history/src/components/InstaCelebs/index_20171001004931.js
oded-soffrin/gkm_viewer
import React from 'react'; import { connect } from 'react-redux' import _ from 'lodash' const imgMap = { d: 'https://instagram.ftlv1-2.fna.fbcdn.net/t51.2885-19/s150x150/18095129_753964814784600_2717222797960019968_a.jpg', e: 'https://instagram.ftlv1-2.fna.fbcdn.net/t51.2885-19/s150x150/12071219_1640349196212432_2045004332_a.jpg' } const InstaCelebs = ({instaCeleb}) => { console.log('instaCeleb', instaCeleb) const stats = _.map(instaCeleb.stats, (x, y) => ( <div> <img src={imgMap[y]}/> <div>{y} - like {x.like} - comment {x.comment}</div> </div> )) return ( <div className="stats"> <h1>Stats</h1> {stats} </div> ) } const mapStateToProps = (state) => ({ instaCeleb: state.instaCeleb }) const InstaCelebsConnected = connect( mapStateToProps, { } )(InstaCelebs) export default InstaCelebsConnected
src-client/components/InputTextStateful.js
ipselon/structor
/* * Copyright 2017 Alexander Pustovalov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; class InputTextStateful extends Component { constructor (props, content) { super(props, content); this.state = { value: this.props.value || this.props.defaultValue || '' }; this.handleOnChange = this.handleOnChange.bind(this); } componentWillReceiveProps (nextProps) { if (nextProps.value) { this.setState({ value: nextProps.value }); } } handleOnChange () { this.setState({ value: this.inputElement.value }); } getValue () { return this.state.value; } focus () { this.inputElement.focus(); } validate (value) { const {validateFunc} = this.props; if (validateFunc) { return validateFunc(value) ? 'has-success' : 'has-error'; } } render () { const {value} = this.state; return ( <div className={'form-group ' + this.validate(value)}> <input style={this.props.style} type={this.props.type} ref={me => this.inputElement = me} className="form-control" value={ value } disabled={this.props.disabled} list={this.props.list} autoComplete={this.props.autoComplete} placeholder={this.props.placeholder} onChange={ this.handleOnChange } /> </div> ); } } InputTextStateful.defaultProps = { defaultValue: undefined, value: undefined, validateFunc: undefined, type: 'text', disabled: false, }; InputTextStateful.propTypes = { defaultValue: PropTypes.string, value: PropTypes.string, validateFunc: PropTypes.func, type: PropTypes.string, list: PropTypes.string, autoComplete: PropTypes.string, placeholder: PropTypes.string, disabled: PropTypes.bool, }; export default InputTextStateful;
src/containers/ProfileContainer.js
Arinono/uReflect_POC_Electron01
import React from 'react'; import Widget from './Widget'; import { ListGroup, ListGroupItem } from 'react-bootstrap'; import Chip from 'material-ui/Chip'; import Avatar from 'material-ui/Avatar'; import {grey50, grey700} from 'material-ui/styles/colors'; const styles = { chip: { margin: 4, width:100, // backgroundColor: "#616161" }, }; var ProfileContainer = React.createClass({ render: function() { var render = <div> <Chip backgroundColor={this.props.actual == 'father' ? grey50 : grey700} onClick={this.props.father} style={styles.chip}> <Avatar src="assets/images/father.svg" /> Father </Chip> <Chip backgroundColor={this.props.actual == 'mother' ? grey50 : grey700} onClick={this.props.mother} style={styles.chip}> <Avatar src="assets/images/mother.svg" /> Mother </Chip> <Chip backgroundColor={this.props.actual == 'child' ? grey50 : grey700} onClick={this.props.child} style={styles.chip}> <Avatar src="assets/images/child.svg" /> Child </Chip> </div>; var options = { size: { width: 1, height: 1 }, pos: { x: 12, y: 6 }, behaviour: { resizable: false, draggable: false, debug: false }, resizeOpt: { horizontal: false, vertical: false } } return ( <Widget options={options} render={render} /> ); }, }); export default ProfileContainer;
node_modules/styled-components/src/hoc/withTheme.js
esteladiaz/esteladiaz.github.io
// @flow /* globals ReactClass */ import React from 'react' import PropTypes from 'prop-types' import hoistStatics from 'hoist-non-react-statics' import { CHANNEL, CHANNEL_NEXT, CONTEXT_CHANNEL_SHAPE, } from '../models/ThemeProvider' import _isStyledComponent from '../utils/isStyledComponent' import determineTheme from '../utils/determineTheme' const wrapWithTheme = (Component: ReactClass<any>) => { const componentName = Component.displayName || Component.name || 'Component' const isStatelessFunctionalComponent = typeof Component === 'function' && !(Component.prototype && 'isReactComponent' in Component.prototype) // NOTE: We can't pass a ref to a stateless functional component const shouldSetInnerRef = _isStyledComponent(Component) || isStatelessFunctionalComponent class WithTheme extends React.Component { static displayName = `WithTheme(${componentName})` // NOTE: This is so that isStyledComponent passes for the innerRef unwrapping static styledComponentId = 'withTheme' static contextTypes = { [CHANNEL]: PropTypes.func, [CHANNEL_NEXT]: CONTEXT_CHANNEL_SHAPE, } state: { theme?: ?Object } = {} unsubscribeId: number = -1 componentWillMount() { const { defaultProps } = this.constructor const styledContext = this.context[CHANNEL_NEXT] const themeProp = determineTheme(this.props, undefined, defaultProps) if ( styledContext === undefined && themeProp === undefined && process.env.NODE_ENV !== 'production' ) { // eslint-disable-next-line no-console console.warn( '[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps' ) } else if (styledContext === undefined && themeProp !== undefined) { this.setState({ theme: themeProp }) } else { const { subscribe } = styledContext this.unsubscribeId = subscribe(nextTheme => { const theme = determineTheme(this.props, nextTheme, defaultProps) this.setState({ theme }) }) } } componentWillReceiveProps(nextProps: { theme?: ?Object, [key: string]: any, }) { const { defaultProps } = this.constructor this.setState(oldState => { const theme = determineTheme(nextProps, oldState.theme, defaultProps) return { theme } }) } componentWillUnmount() { if (this.unsubscribeId !== -1) { this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId) } } render() { const props = { theme: this.state.theme, ...this.props, } if (!shouldSetInnerRef) { props.ref = props.innerRef delete props.innerRef } return <Component {...props} /> } } return hoistStatics(WithTheme, Component) } export default wrapWithTheme
ajax/libs/yui/3.4.0/simpleyui/simpleyui-debug.js
chinakids/cdnjs
/** * 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('*');
app/components/Application.js
dariobanfi/react-avocado-starter
import React from 'react'; import Switch from 'react-router-dom/Switch'; import Route from 'react-router-dom/Route'; import Helmet from 'react-helmet'; import config from '../../config'; import '../styles/globals'; import routes from '../routes'; import Header from './header/Header'; import Footer from './footer/Footer'; const Application = () => ( <div style={{ padding: '2rem' }}> <Helmet> <html lang="en" /> <title> {config('htmlPage.defaultTitle')} </title> <meta name="application-name" content={config('htmlPage.defaultTitle')} /> <meta name="description" content={config('htmlPage.description')} /> <meta charSet="utf-8" /> <meta httpEquiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="msapplication-TileColor" content="#2b2b2b" /> <meta name="msapplication-TileImage" content="/favicons/mstile-144x144.png" /> <meta name="theme-color" content="#2b2b2b" /> <link rel="apple-touch-icon-precomposed" sizes="152x152" href="/favicons/apple-touch-icon-152x152.png" /> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/favicons/apple-touch-icon-144x144.png" /> <link rel="apple-touch-icon-precomposed" sizes="120x120" href="/favicons/apple-touch-icon-120x120.png" /> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="/favicons/apple-touch-icon-114x114.png" /> <link rel="apple-touch-icon-precomposed" sizes="76x76" href="/favicons/apple-touch-icon-76x76.png" /> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="/favicons/apple-touch-icon-72x72.png" /> <link rel="apple-touch-icon-precomposed" sizes="57x57" href="/favicons/apple-touch-icon-57x57.png" /> <link rel="apple-touch-icon-precomposed" sizes="60x60" href="/favicons/apple-touch-icon-60x60.png" /> <link rel="apple-touch-icon" sizes="180x180" href="/favicons/apple-touch-icon-180x180.png" /> <link rel="mask-icon" href="/favicons/safari-pinned-tab.svg" color="#629035" /> <link rel="icon" type="image/png" href="/favicons/favicon-196x196.png" sizes="196x196" /> <link rel="icon" type="image/png" href="/favicons/favicon-128.png" sizes="128x128" /> <link rel="icon" type="image/png" href="/favicons/favicon-96x96.png" sizes="96x96" /> <link rel="icon" type="image/png" href="/favicons/favicon-32x32.png" sizes="32x32" /> <link rel="icon" sizes="16x16 32x32" href="/favicon.ico" /> <meta name="msapplication-TileColor" content="#F7F4A1" /> <meta name="msapplication-TileImage" content="/favicons/mstile-144x144.png" /> <meta name="msapplication-square70x70logo" content="/favicons/mstile-70x70.png" /> <meta name="msapplication-square150x150logo" content="/favicons/mstile-150x150.png" /> <meta name="msapplication-wide310x150logo" content="/favicons/mstile-310x150.png" /> <meta name="msapplication-square310x310logo" content="/favicons/mstile-310x310.png" /> <link rel="manifest" href="/manifest.json" /> </Helmet> <Header /> <div style={{ paddingTop: '2rem', paddingBottom: '2rem' }}> <Switch> {routes.map(route => ( <Route key={route.path} {...route} /> ))} </Switch> </div> <Footer /> </div> ); export default Application;
example/__tests__/App-test.js
gitboss2000/react-native-swipeable-flat-list
/** * @format */ import 'react-native'; import React from 'react'; import App from '../src/App'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { renderer.create(<App />); });
packages/canvas-media/src/MediaRecorder.js
djbender/canvas-lms
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react' import {Alert} from '@instructure/ui-alerts' import {canUseMediaCapture, MediaCapture} from '@instructure/media-capture' import {func, object, string} from 'prop-types' export default function MediaRecorder(props) { return ( <div> {canUseMediaCapture() ? ( <MediaCapture translations={props.MediaCaptureStrings} onCompleted={props.onSave} /> ) : ( <Alert variant="error" margin="small"> {props.errorMessage} </Alert> )} </div> ) } MediaRecorder.propTypes = { onSave: func.isRequired, errorMessage: string.isRequired, MediaCaptureStrings: object }
src/index.js
fullstackreact/google-maps-react
import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import {camelize} from './lib/String'; import {makeCancelable} from './lib/cancelablePromise'; const mapStyles = { container: { position: 'absolute', width: '100%', height: '100%' }, map: { position: 'absolute', left: 0, right: 0, bottom: 0, top: 0 } }; const evtNames = [ 'ready', 'click', 'dragend', 'recenter', 'bounds_changed', 'center_changed', 'dblclick', 'dragstart', 'heading_change', 'idle', 'maptypeid_changed', 'mousemove', 'mouseout', 'mouseover', 'projection_changed', 'resize', 'rightclick', 'tilesloaded', 'tilt_changed', 'zoom_changed' ]; export {wrapper as GoogleApiWrapper} from './GoogleApiComponent'; export {Marker} from './components/Marker'; export {InfoWindow} from './components/InfoWindow'; export {HeatMap} from './components/HeatMap'; export {Polygon} from './components/Polygon'; export {Polyline} from './components/Polyline'; export {Circle} from './components/Circle'; export {Rectangle} from './components/Rectangle'; export class Map extends React.Component { constructor(props) { super(props); if (!props.hasOwnProperty('google')) { throw new Error('You must include a `google` prop'); } this.listeners = {}; this.state = { currentLocation: { lat: this.props.initialCenter.lat, lng: this.props.initialCenter.lng } }; this.mapRef=React.createRef(); } componentDidMount() { if (this.props.centerAroundCurrentLocation) { if (navigator && navigator.geolocation) { this.geoPromise = makeCancelable( new Promise((resolve, reject) => { navigator.geolocation.getCurrentPosition(resolve, reject); }) ); this.geoPromise.promise .then(pos => { const coords = pos.coords; this.setState({ currentLocation: { lat: coords.latitude, lng: coords.longitude } }); }) .catch(e => e); } } this.loadMap(); } componentDidUpdate(prevProps, prevState) { if (prevProps.google !== this.props.google) { this.loadMap(); } if (this.props.visible !== prevProps.visible) { this.restyleMap(); } if (this.props.zoom !== prevProps.zoom) { this.map.setZoom(this.props.zoom); } if (this.props.center !== prevProps.center) { this.setState({ currentLocation: this.props.center }); } if (prevState.currentLocation !== this.state.currentLocation) { this.recenterMap(); } if (this.props.bounds && this.props.bounds !== prevProps.bounds) { this.map.fitBounds(this.props.bounds); } } componentWillUnmount() { const {google} = this.props; if (this.geoPromise) { this.geoPromise.cancel(); } Object.keys(this.listeners).forEach(e => { google.maps.event.removeListener(this.listeners[e]); }); } loadMap() { if (this.props && this.props.google) { const {google} = this.props; const maps = google.maps; const mapRef = this.mapRef.current; const node = ReactDOM.findDOMNode(mapRef); const curr = this.state.currentLocation; const center = new maps.LatLng(curr.lat, curr.lng); const mapTypeIds = this.props.google.maps.MapTypeId || {}; const mapTypeFromProps = String(this.props.mapType).toUpperCase(); const mapConfig = Object.assign( {}, { mapTypeId: mapTypeIds[mapTypeFromProps], center: center, zoom: this.props.zoom, maxZoom: this.props.maxZoom, minZoom: this.props.minZoom, clickableIcons: !!this.props.clickableIcons, disableDefaultUI: this.props.disableDefaultUI, zoomControl: this.props.zoomControl, zoomControlOptions: this.props.zoomControlOptions, mapTypeControl: this.props.mapTypeControl, mapTypeControlOptions: this.props.mapTypeControlOptions, scaleControl: this.props.scaleControl, streetViewControl: this.props.streetViewControl, streetViewControlOptions: this.props.streetViewControlOptions, panControl: this.props.panControl, rotateControl: this.props.rotateControl, fullscreenControl: this.props.fullscreenControl, scrollwheel: this.props.scrollwheel, draggable: this.props.draggable, draggableCursor: this.props.draggableCursor, keyboardShortcuts: this.props.keyboardShortcuts, disableDoubleClickZoom: this.props.disableDoubleClickZoom, noClear: this.props.noClear, styles: this.props.styles, gestureHandling: this.props.gestureHandling } ); Object.keys(mapConfig).forEach(key => { // Allow to configure mapConfig with 'false' if (mapConfig[key] === null) { delete mapConfig[key]; } }); this.map = new maps.Map(node, mapConfig); evtNames.forEach(e => { this.listeners[e] = this.map.addListener(e, this.handleEvent(e)); }); maps.event.trigger(this.map, 'ready'); this.forceUpdate(); } } handleEvent(evtName) { let timeout; const handlerName = `on${camelize(evtName)}`; return e => { if (timeout) { clearTimeout(timeout); timeout = null; } timeout = setTimeout(() => { if (this.props[handlerName]) { this.props[handlerName](this.props, this.map, e); } }, 0); }; } recenterMap() { const map = this.map; const {google} = this.props; if (!google) return; const maps = google.maps; if (map) { let center = this.state.currentLocation; if (!(center instanceof google.maps.LatLng)) { center = new google.maps.LatLng(center.lat, center.lng); } // map.panTo(center) map.setCenter(center); maps.event.trigger(map, 'recenter'); } } restyleMap() { if (this.map) { const {google} = this.props; google.maps.event.trigger(this.map, 'resize'); } } renderChildren() { const {children} = this.props; if (!children) return; return React.Children.map(children, c => { if (!c) return; return React.cloneElement(c, { map: this.map, google: this.props.google, mapCenter: this.state.currentLocation }); }); } render() { const style = Object.assign({}, mapStyles.map, this.props.style, { display: this.props.visible ? 'inherit' : 'none' }); const containerStyles = Object.assign( {}, mapStyles.container, this.props.containerStyle ); return ( <div style={containerStyles} className={this.props.className}> <div style={style} ref={this.mapRef}> Loading map... </div> {this.renderChildren()} </div> ); } } Map.propTypes = { google: PropTypes.object, zoom: PropTypes.number, centerAroundCurrentLocation: PropTypes.bool, center: PropTypes.object, initialCenter: PropTypes.object, className: PropTypes.string, style: PropTypes.object, containerStyle: PropTypes.object, visible: PropTypes.bool, mapType: PropTypes.string, maxZoom: PropTypes.number, minZoom: PropTypes.number, clickableIcons: PropTypes.bool, disableDefaultUI: PropTypes.bool, zoomControl: PropTypes.bool, zoomControlOptions: PropTypes.object, mapTypeControl: PropTypes.bool, mapTypeControlOptions: PropTypes.bool, scaleControl: PropTypes.bool, streetViewControl: PropTypes.bool, streetViewControlOptions: PropTypes.object, panControl: PropTypes.bool, rotateControl: PropTypes.bool, fullscreenControl: PropTypes.bool, scrollwheel: PropTypes.bool, draggable: PropTypes.bool, draggableCursor: PropTypes.string, keyboardShortcuts: PropTypes.bool, disableDoubleClickZoom: PropTypes.bool, noClear: PropTypes.bool, styles: PropTypes.array, gestureHandling: PropTypes.string, bounds: PropTypes.object }; evtNames.forEach(e => (Map.propTypes[camelize(e)] = PropTypes.func)); Map.defaultProps = { zoom: 14, initialCenter: { lat: 37.774929, lng: -122.419416 }, center: {}, centerAroundCurrentLocation: false, style: {}, containerStyle: {}, visible: true }; export default Map;
frontend/src/lib/mui-components/MoreButton/MoreButton.js
jf248/scrape-the-plate
import React from 'react'; import { Compose, callAll } from 'lib/react-powerplug'; import { MenuController } from 'lib/mui-components'; import MoreButtonPres from './MoreButtonPres'; function MoreButton(props) { const renderFunc = (menu, login, auth) => { const { onClick, anchorEl, open, onClose } = menu; return ( <MoreButtonPres {...{ anchorEl, open, ...props, onClick: callAll(props.onClick, onClick), onClose: callAll(props.onClose, onClose), }} /> ); }; return ( /* eslint-disable react/jsx-key */ <Compose components={[<MenuController />]} render={renderFunc} /> /* eslint-enable react/jsx-key */ ); } export default MoreButton;
app/components/navbar.js
danieloliveira079/healthy-life-app-v1
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { logout } from '../actions/auth'; import { Strings } from '../constants'; class Navbar extends Component { handleLogout () { const { dispatch } = this.props; dispatch(logout()); } renderLoggedIn () { const menuStyle = { marginLeft: '20px', }; return ( <nav className="navbar-component blue"> <div className="left" style={menuStyle}> <ul id="slide-out" className="side-nav"> {this.props.children} </ul> <a href="#" data-activates="slide-out" className="button-collapse show-on-large"><i className="mdi-navigation-menu"></i></a> <a href="#" className="brand-logo center">{Strings.App.Name}</a> </div> <div className="right login-info"> <span><Link to="/" onClick={::this.handleLogout}>{Strings.Login.LogoutAction}</Link></span> </div> </nav> ); } renderNotLoggedIn () { const menuStyle = { marginLeft: '20px', }; return ( <nav className="navbar-component blue"> <div className="left" style={menuStyle}> <a href="#" className="brand-logo center">{Strings.App.Name}</a> </div> </nav> ); } render () { if (this.props.auth.isLoggedIn) { return (this.renderLoggedIn()); } return (this.renderNotLoggedIn()); } } export default connect((state) => { return { auth: state.auth, }; })(Navbar);
ajax/libs/react-dropzone/4.1.2/index.js
jonobr1/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("prop-types")); else if(typeof define === 'function' && define.amd) define(["react", "prop-types"], factory); else if(typeof exports === 'object') exports["Dropzone"] = factory(require("react"), require("prop-types")); else root["Dropzone"] = factory(root["react"], root["prop-types"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__) { 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; /******/ /******/ // 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 = 0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) { 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 _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _propTypes = __webpack_require__(3); var _propTypes2 = _interopRequireDefault(_propTypes); var _utils = __webpack_require__(4); var _styles = __webpack_require__(6); var _styles2 = _interopRequireDefault(_styles); 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 _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 _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 prefer-template: 0 */ var Dropzone = function (_React$Component) { _inherits(Dropzone, _React$Component); function Dropzone(props, context) { _classCallCheck(this, Dropzone); var _this = _possibleConstructorReturn(this, (Dropzone.__proto__ || Object.getPrototypeOf(Dropzone)).call(this, props, context)); _this.renderChildren = function (children, isDragActive, isDragAccept, isDragReject) { if (typeof children === 'function') { return children(_extends({}, _this.state, { isDragActive: isDragActive, isDragAccept: isDragAccept, isDragReject: isDragReject })); } return children; }; _this.composeHandlers = _this.composeHandlers.bind(_this); _this.onClick = _this.onClick.bind(_this); _this.onDocumentDrop = _this.onDocumentDrop.bind(_this); _this.onDragEnter = _this.onDragEnter.bind(_this); _this.onDragLeave = _this.onDragLeave.bind(_this); _this.onDragOver = _this.onDragOver.bind(_this); _this.onDragStart = _this.onDragStart.bind(_this); _this.onDrop = _this.onDrop.bind(_this); _this.onFileDialogCancel = _this.onFileDialogCancel.bind(_this); _this.onInputElementClick = _this.onInputElementClick.bind(_this); _this.setRef = _this.setRef.bind(_this); _this.setRefs = _this.setRefs.bind(_this); _this.isFileDialogActive = false; _this.state = { draggedFiles: [], acceptedFiles: [], rejectedFiles: [] }; return _this; } _createClass(Dropzone, [{ key: 'componentDidMount', value: function componentDidMount() { var preventDropOnDocument = this.props.preventDropOnDocument; this.dragTargets = []; if (preventDropOnDocument) { document.addEventListener('dragover', _utils.onDocumentDragOver, false); document.addEventListener('drop', this.onDocumentDrop, false); } this.fileInputEl.addEventListener('click', this.onInputElementClick, false); // Tried implementing addEventListener, but didn't work out document.body.onfocus = this.onFileDialogCancel; } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { var preventDropOnDocument = this.props.preventDropOnDocument; if (preventDropOnDocument) { document.removeEventListener('dragover', _utils.onDocumentDragOver); document.removeEventListener('drop', this.onDocumentDrop); } this.fileInputEl.removeEventListener('click', this.onInputElementClick, false); // Can be replaced with removeEventListener, if addEventListener works document.body.onfocus = null; } }, { key: 'composeHandlers', value: function composeHandlers(handler) { if (this.props.disabled) { return null; } return handler; } }, { key: 'onDocumentDrop', value: function onDocumentDrop(evt) { if (this.node.contains(evt.target)) { // if we intercepted an event for our instance, let it propagate down to the instance's onDrop handler return; } evt.preventDefault(); this.dragTargets = []; } }, { key: 'onDragStart', value: function onDragStart(evt) { if (this.props.onDragStart) { this.props.onDragStart.call(this, evt); } } }, { key: 'onDragEnter', value: function onDragEnter(evt) { evt.preventDefault(); // Count the dropzone and any children that are entered. if (this.dragTargets.indexOf(evt.target) === -1) { this.dragTargets.push(evt.target); } this.setState({ isDragActive: true, // Do not rely on files for the drag state. It doesn't work in Safari. draggedFiles: (0, _utils.getDataTransferItems)(evt) }); if (this.props.onDragEnter) { this.props.onDragEnter.call(this, evt); } } }, { key: 'onDragOver', value: function onDragOver(evt) { // eslint-disable-line class-methods-use-this evt.preventDefault(); evt.stopPropagation(); try { evt.dataTransfer.dropEffect = 'copy'; // eslint-disable-line no-param-reassign } catch (err) { // continue regardless of error } if (this.props.onDragOver) { this.props.onDragOver.call(this, evt); } return false; } }, { key: 'onDragLeave', value: function onDragLeave(evt) { var _this2 = this; evt.preventDefault(); // Only deactivate once the dropzone and all children have been left. this.dragTargets = this.dragTargets.filter(function (el) { return el !== evt.target && _this2.node.contains(el); }); if (this.dragTargets.length > 0) { return; } // Clear dragging files state this.setState({ isDragActive: false, draggedFiles: [] }); if (this.props.onDragLeave) { this.props.onDragLeave.call(this, evt); } } }, { key: 'onDrop', value: function onDrop(evt) { var _this3 = this; var _props = this.props, onDrop = _props.onDrop, onDropAccepted = _props.onDropAccepted, onDropRejected = _props.onDropRejected, multiple = _props.multiple, disablePreview = _props.disablePreview, accept = _props.accept; var fileList = (0, _utils.getDataTransferItems)(evt); var acceptedFiles = []; var rejectedFiles = []; // Stop default browser behavior evt.preventDefault(); // Reset the counter along with the drag on a drop. this.dragTargets = []; this.isFileDialogActive = false; fileList.forEach(function (file) { if (!disablePreview) { try { file.preview = window.URL.createObjectURL(file); // eslint-disable-line no-param-reassign } catch (err) { if (process.env.NODE_ENV !== 'production') { console.error('Failed to generate preview for file', file, err); // eslint-disable-line no-console } } } if ((0, _utils.fileAccepted)(file, accept) && (0, _utils.fileMatchSize)(file, _this3.props.maxSize, _this3.props.minSize)) { acceptedFiles.push(file); } else { rejectedFiles.push(file); } }); if (!multiple) { // if not in multi mode add any extra accepted files to rejected. // This will allow end users to easily ignore a multi file drop in "single" mode. rejectedFiles.push.apply(rejectedFiles, _toConsumableArray(acceptedFiles.splice(1))); } if (onDrop) { onDrop.call(this, acceptedFiles, rejectedFiles, evt); } if (rejectedFiles.length > 0 && onDropRejected) { onDropRejected.call(this, rejectedFiles, evt); } if (acceptedFiles.length > 0 && onDropAccepted) { onDropAccepted.call(this, acceptedFiles, evt); } // Clear files value this.draggedFiles = null; // Reset drag state this.setState({ isDragActive: false, draggedFiles: [], acceptedFiles: acceptedFiles, rejectedFiles: rejectedFiles }); } }, { key: 'onClick', value: function onClick(evt) { var _props2 = this.props, onClick = _props2.onClick, disableClick = _props2.disableClick; if (!disableClick) { evt.stopPropagation(); if (onClick) { onClick.call(this, evt); } // in IE11/Edge the file-browser dialog is blocking, ensure this is behind setTimeout // this is so react can handle state changes in the onClick prop above above // see: https://github.com/react-dropzone/react-dropzone/issues/450 setTimeout(this.open.bind(this), 0); } } }, { key: 'onInputElementClick', value: function onInputElementClick(evt) { evt.stopPropagation(); if (this.props.inputProps && this.props.inputProps.onClick) { this.props.inputProps.onClick(); } } }, { key: 'onFileDialogCancel', value: function onFileDialogCancel() { // timeout will not recognize context of this method var onFileDialogCancel = this.props.onFileDialogCancel; var fileInputEl = this.fileInputEl; var isFileDialogActive = this.isFileDialogActive; // execute the timeout only if the onFileDialogCancel is defined and FileDialog // is opened in the browser if (onFileDialogCancel && isFileDialogActive) { setTimeout(function () { // Returns an object as FileList var FileList = fileInputEl.files; if (!FileList.length) { isFileDialogActive = false; onFileDialogCancel(); } }, 300); } } }, { key: 'setRef', value: function setRef(ref) { this.node = ref; } }, { key: 'setRefs', value: function setRefs(ref) { this.fileInputEl = ref; } /** * Open system file upload dialog. * * @public */ }, { key: 'open', value: function open() { this.isFileDialogActive = true; this.fileInputEl.value = null; this.fileInputEl.click(); } }, { key: 'render', value: function render() { var _props3 = this.props, accept = _props3.accept, acceptClassName = _props3.acceptClassName, activeClassName = _props3.activeClassName, children = _props3.children, disabled = _props3.disabled, disabledClassName = _props3.disabledClassName, inputProps = _props3.inputProps, multiple = _props3.multiple, name = _props3.name, rejectClassName = _props3.rejectClassName, rest = _objectWithoutProperties(_props3, ['accept', 'acceptClassName', 'activeClassName', 'children', 'disabled', 'disabledClassName', 'inputProps', 'multiple', 'name', 'rejectClassName']); var acceptStyle = rest.acceptStyle, activeStyle = rest.activeStyle, className = rest.className, disabledStyle = rest.disabledStyle, rejectStyle = rest.rejectStyle, style = rest.style, props = _objectWithoutProperties(rest, ['acceptStyle', 'activeStyle', 'className', 'disabledStyle', 'rejectStyle', 'style']); var _state = this.state, isDragActive = _state.isDragActive, draggedFiles = _state.draggedFiles; var filesCount = draggedFiles.length; var isMultipleAllowed = multiple || filesCount <= 1; var isDragAccept = filesCount > 0 && (0, _utils.allFilesAccepted)(draggedFiles, this.props.accept); var isDragReject = filesCount > 0 && (!isDragAccept || !isMultipleAllowed); className = className || ''; var noStyles = !className && !style && !activeStyle && !acceptStyle && !rejectStyle && !disabledStyle; if (isDragActive && activeClassName) { className += ' ' + activeClassName; } if (isDragAccept && acceptClassName) { className += ' ' + acceptClassName; } if (isDragReject && rejectClassName) { className += ' ' + rejectClassName; } if (disabled && disabledClassName) { className += ' ' + disabledClassName; } if (noStyles) { style = _styles2.default.default; activeStyle = _styles2.default.active; acceptStyle = style.active; rejectStyle = _styles2.default.rejected; disabledStyle = _styles2.default.disabled; } var appliedStyle = _extends({}, style); if (activeStyle && isDragActive) { appliedStyle = _extends({}, style, activeStyle); } if (acceptStyle && isDragAccept) { appliedStyle = _extends({}, appliedStyle, acceptStyle); } if (rejectStyle && isDragReject) { appliedStyle = _extends({}, appliedStyle, rejectStyle); } if (disabledStyle && disabled) { appliedStyle = _extends({}, style, disabledStyle); } var inputAttributes = { accept: accept, disabled: disabled, type: 'file', style: { display: 'none' }, multiple: _utils.supportMultiple && multiple, ref: this.setRefs, onChange: this.onDrop, autoComplete: 'off' }; if (name && name.length) { inputAttributes.name = name; } // Remove custom properties before passing them to the wrapper div element var customProps = ['acceptedFiles', 'preventDropOnDocument', 'disablePreview', 'disableClick', 'onDropAccepted', 'onDropRejected', 'onFileDialogCancel', 'maxSize', 'minSize']; var divProps = _extends({}, props); customProps.forEach(function (prop) { return delete divProps[prop]; }); return _react2.default.createElement( 'div', _extends({ className: className, style: appliedStyle }, divProps /* expand user provided props first so event handlers are never overridden */, { onClick: this.composeHandlers(this.onClick), onDragStart: this.composeHandlers(this.onDragStart), onDragEnter: this.composeHandlers(this.onDragEnter), onDragOver: this.composeHandlers(this.onDragOver), onDragLeave: this.composeHandlers(this.onDragLeave), onDrop: this.composeHandlers(this.onDrop), ref: this.setRef, 'aria-disabled': disabled }), this.renderChildren(children, isDragActive, isDragAccept, isDragReject), _react2.default.createElement('input', _extends({}, inputProps /* expand user provided inputProps first so inputAttributes override them */, inputAttributes)) ); } }]); return Dropzone; }(_react2.default.Component); exports.default = Dropzone; Dropzone.propTypes = { /** * Allow specific types of files. See https://github.com/okonet/attr-accept for more information. * Keep in mind that mime type determination is not reliable across platforms. CSV files, * for example, are reported as text/plain under macOS but as application/vnd.ms-excel under * Windows. In some cases there might not be a mime type set at all. * See: https://github.com/react-dropzone/react-dropzone/issues/276 */ accept: _propTypes2.default.string, /** * Contents of the dropzone */ children: _propTypes2.default.oneOfType([_propTypes2.default.node, _propTypes2.default.func]), /** * Disallow clicking on the dropzone container to open file dialog */ disableClick: _propTypes2.default.bool, /** * Enable/disable the dropzone entirely */ disabled: _propTypes2.default.bool, /** * Enable/disable preview generation */ disablePreview: _propTypes2.default.bool, /** * If false, allow dropped items to take over the current browser window */ preventDropOnDocument: _propTypes2.default.bool, /** * Pass additional attributes to the `<input type="file"/>` tag */ inputProps: _propTypes2.default.object, /** * Allow dropping multiple files */ multiple: _propTypes2.default.bool, /** * `name` attribute for the input tag */ name: _propTypes2.default.string, /** * Maximum file size */ maxSize: _propTypes2.default.number, /** * Minimum file size */ minSize: _propTypes2.default.number, /** * className */ className: _propTypes2.default.string, /** * className for active state */ activeClassName: _propTypes2.default.string, /** * className for accepted state */ acceptClassName: _propTypes2.default.string, /** * className for rejected state */ rejectClassName: _propTypes2.default.string, /** * className for disabled state */ disabledClassName: _propTypes2.default.string, /** * CSS styles to apply */ style: _propTypes2.default.object, /** * CSS styles to apply when drag is active */ activeStyle: _propTypes2.default.object, /** * CSS styles to apply when drop will be accepted */ acceptStyle: _propTypes2.default.object, /** * CSS styles to apply when drop will be rejected */ rejectStyle: _propTypes2.default.object, /** * CSS styles to apply when dropzone is disabled */ disabledStyle: _propTypes2.default.object, /** * onClick callback * @param {Event} event */ onClick: _propTypes2.default.func, /** * onDrop callback */ onDrop: _propTypes2.default.func, /** * onDropAccepted callback */ onDropAccepted: _propTypes2.default.func, /** * onDropRejected callback */ onDropRejected: _propTypes2.default.func, /** * onDragStart callback */ onDragStart: _propTypes2.default.func, /** * onDragEnter callback */ onDragEnter: _propTypes2.default.func, /** * onDragOver callback */ onDragOver: _propTypes2.default.func, /** * onDragLeave callback */ onDragLeave: _propTypes2.default.func, /** * Provide a callback on clicking the cancel button of the file dialog */ onFileDialogCancel: _propTypes2.default.func }; Dropzone.defaultProps = { preventDropOnDocument: true, disabled: false, disablePreview: false, disableClick: false, multiple: true, maxSize: Infinity, minSize: 0 }; module.exports = exports['default']; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) /***/ }), /* 1 */ /***/ (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; }; /***/ }), /* 2 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }), /* 3 */ /***/ (function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.supportMultiple = undefined; exports.getDataTransferItems = getDataTransferItems; exports.fileAccepted = fileAccepted; exports.fileMatchSize = fileMatchSize; exports.allFilesAccepted = allFilesAccepted; exports.onDocumentDragOver = onDocumentDragOver; var _attrAccept = __webpack_require__(5); var _attrAccept2 = _interopRequireDefault(_attrAccept); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var supportMultiple = exports.supportMultiple = typeof document !== 'undefined' && document && document.createElement ? 'multiple' in document.createElement('input') : true; function getDataTransferItems(event) { var dataTransferItemsList = []; if (event.dataTransfer) { var dt = event.dataTransfer; if (dt.files && dt.files.length) { dataTransferItemsList = dt.files; } else if (dt.items && dt.items.length) { // During the drag even the dataTransfer.files is null // but Chrome implements some drag store, which is accesible via dataTransfer.items dataTransferItemsList = dt.items; } } else if (event.target && event.target.files) { dataTransferItemsList = event.target.files; } // Convert from DataTransferItemsList to the native Array return Array.prototype.slice.call(dataTransferItemsList); } // Firefox versions prior to 53 return a bogus MIME type for every file drag, so dragovers with // that MIME type will always be accepted function fileAccepted(file, accept) { return file.type === 'application/x-moz-file' || (0, _attrAccept2.default)(file, accept); } function fileMatchSize(file, maxSize, minSize) { return file.size <= maxSize && file.size >= minSize; } function allFilesAccepted(files, accept) { return files.every(function (file) { return fileAccepted(file, accept); }); } // allow the entire document to be a drag target function onDocumentDragOver(evt) { evt.preventDefault(); } /***/ }), /* 5 */ /***/ (function(module, exports) { module.exports=function(t){function n(e){if(r[e])return r[e].exports;var o=r[e]={exports:{},id:e,loaded:!1};return t[e].call(o.exports,o,o.exports,n),o.loaded=!0,o.exports}var r={};return n.m=t,n.c=r,n.p="",n(0)}([function(t,n,r){"use strict";n.__esModule=!0,r(8),r(9),n["default"]=function(t,n){if(t&&n){var r=function(){var r=Array.isArray(n)?n:n.split(","),e=t.name||"",o=t.type||"",i=o.replace(/\/.*$/,"");return{v:r.some(function(t){var n=t.trim();return"."===n.charAt(0)?e.toLowerCase().endsWith(n.toLowerCase()):/\/\*$/.test(n)?i===n.replace(/\/.*$/,""):o===n})}}();if("object"==typeof r)return r.v}return!0},t.exports=n["default"]},function(t,n){var r=t.exports={version:"1.2.2"};"number"==typeof __e&&(__e=r)},function(t,n){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,n,r){var e=r(2),o=r(1),i=r(4),u=r(19),c="prototype",f=function(t,n){return function(){return t.apply(n,arguments)}},s=function(t,n,r){var a,p,l,y,d=t&s.G,h=t&s.P,v=d?e:t&s.S?e[n]||(e[n]={}):(e[n]||{})[c],x=d?o:o[n]||(o[n]={});d&&(r=n);for(a in r)p=!(t&s.F)&&v&&a in v,l=(p?v:r)[a],y=t&s.B&&p?f(l,e):h&&"function"==typeof l?f(Function.call,l):l,v&&!p&&u(v,a,l),x[a]!=l&&i(x,a,y),h&&((x[c]||(x[c]={}))[a]=l)};e.core=o,s.F=1,s.G=2,s.S=4,s.P=8,s.B=16,s.W=32,t.exports=s},function(t,n,r){var e=r(5),o=r(18);t.exports=r(22)?function(t,n,r){return e.setDesc(t,n,o(1,r))}:function(t,n,r){return t[n]=r,t}},function(t,n){var r=Object;t.exports={create:r.create,getProto:r.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:r.getOwnPropertyDescriptor,setDesc:r.defineProperty,setDescs:r.defineProperties,getKeys:r.keys,getNames:r.getOwnPropertyNames,getSymbols:r.getOwnPropertySymbols,each:[].forEach}},function(t,n){var r=0,e=Math.random();t.exports=function(t){return"Symbol(".concat(void 0===t?"":t,")_",(++r+e).toString(36))}},function(t,n,r){var e=r(20)("wks"),o=r(2).Symbol;t.exports=function(t){return e[t]||(e[t]=o&&o[t]||(o||r(6))("Symbol."+t))}},function(t,n,r){r(26),t.exports=r(1).Array.some},function(t,n,r){r(25),t.exports=r(1).String.endsWith},function(t,n){t.exports=function(t){if("function"!=typeof t)throw TypeError(t+" is not a function!");return t}},function(t,n){var r={}.toString;t.exports=function(t){return r.call(t).slice(8,-1)}},function(t,n,r){var e=r(10);t.exports=function(t,n,r){if(e(t),void 0===n)return t;switch(r){case 1:return function(r){return t.call(n,r)};case 2:return function(r,e){return t.call(n,r,e)};case 3:return function(r,e,o){return t.call(n,r,e,o)}}return function(){return t.apply(n,arguments)}}},function(t,n){t.exports=function(t){if(void 0==t)throw TypeError("Can't call method on "+t);return t}},function(t,n,r){t.exports=function(t){var n=/./;try{"/./"[t](n)}catch(e){try{return n[r(7)("match")]=!1,!"/./"[t](n)}catch(o){}}return!0}},function(t,n){t.exports=function(t){try{return!!t()}catch(n){return!0}}},function(t,n){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,n,r){var e=r(16),o=r(11),i=r(7)("match");t.exports=function(t){var n;return e(t)&&(void 0!==(n=t[i])?!!n:"RegExp"==o(t))}},function(t,n){t.exports=function(t,n){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:n}}},function(t,n,r){var e=r(2),o=r(4),i=r(6)("src"),u="toString",c=Function[u],f=(""+c).split(u);r(1).inspectSource=function(t){return c.call(t)},(t.exports=function(t,n,r,u){"function"==typeof r&&(o(r,i,t[n]?""+t[n]:f.join(String(n))),"name"in r||(r.name=n)),t===e?t[n]=r:(u||delete t[n],o(t,n,r))})(Function.prototype,u,function(){return"function"==typeof this&&this[i]||c.call(this)})},function(t,n,r){var e=r(2),o="__core-js_shared__",i=e[o]||(e[o]={});t.exports=function(t){return i[t]||(i[t]={})}},function(t,n,r){var e=r(17),o=r(13);t.exports=function(t,n,r){if(e(n))throw TypeError("String#"+r+" doesn't accept regex!");return String(o(t))}},function(t,n,r){t.exports=!r(15)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(t,n){var r=Math.ceil,e=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?e:r)(t)}},function(t,n,r){var e=r(23),o=Math.min;t.exports=function(t){return t>0?o(e(t),9007199254740991):0}},function(t,n,r){"use strict";var e=r(3),o=r(24),i=r(21),u="endsWith",c=""[u];e(e.P+e.F*r(14)(u),"String",{endsWith:function(t){var n=i(this,t,u),r=arguments,e=r.length>1?r[1]:void 0,f=o(n.length),s=void 0===e?f:Math.min(o(e),f),a=String(t);return c?c.call(n,a,s):n.slice(s-a.length,s)===a}})},function(t,n,r){var e=r(5),o=r(3),i=r(1).Array||Array,u={},c=function(t,n){e.each.call(t.split(","),function(t){void 0==n&&t in i?u[t]=i[t]:t in[]&&(u[t]=r(12)(Function.call,[][t],n))})};c("pop,reverse,shift,keys,values,entries",1),c("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3),c("join,slice,concat,push,splice,unshift,sort,lastIndexOf,reduce,reduceRight,copyWithin,fill"),o(o.S,"Array",u)}]); /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { rejected: { borderStyle: 'solid', borderColor: '#c66', backgroundColor: '#eee' }, disabled: { opacity: 0.5 }, active: { borderStyle: 'solid', borderColor: '#6c6', backgroundColor: '#eee' }, default: { width: 200, height: 200, borderWidth: 2, borderColor: '#666', borderStyle: 'dashed', borderRadius: 5 } }; module.exports = exports['default']; /***/ }) /******/ ]); }); //# sourceMappingURL=index.js.map
src/containers/NotFoundPage/NotFoundPage.js
armaniExchange/work-genius
// Style import './_NotFoundPage.css'; // React & Redux import React, { Component } from 'react'; class NotFoundPage extends Component { render() { return ( <div className="Not-Found-Page"> <h1 className="Not-Found-Page__header">404</h1> <div className="Not-Found-Page__content">The page you are looking for is not here :(</div> </div> ); } } export default NotFoundPage;
lib/direct-node.min.js
lisb/direct-js
!function(e,t){"use strict";function s(){return Va.__string_rec(this,"")}var n={};function i(e,t){function n(){}n.prototype=e;var i=new n;for(var r in t)i[r]=t[r];return t.toString!==Object.prototype.toString&&(i.toString=t.toString),i}var r=e.DirectAPI=function(){this.eventEmitter=new o,require("unorm")};(n.DirectAPI=r).__name__=["DirectAPI"],r.getInstance=function(){return null==r.instance&&(r.instance=new r),r.instance},r.main=function(){},r.prototype={setOptions:function(e){null!=e&&(Eo.host=e.host,Eo.endpoint=e.endpoint,Eo.accessToken=e.access_token,Eo.proxyURL=e.proxyURL,Eo.account=e.account,Eo.talkWithBot=e.talkWithBot,Eo.acceptableEventTimeDiff=e.acceptableEventTimeDiff,Eo.name=e.name,Eo.storagePath=e.storage_path,Eo.storageQuota=e.storage_quota,Eo.wsConfig=e.ws_config),Gi._d("["+$e.dateStr(new Date)+"] ","current settings",Eo,"","",""),null==Eo.accessToken&&Gi._e("["+$e.dateStr(new Date)+"] ","Not enough parameters provided. I need a access token","","","","")},announce:function(e,t){var n,i=e.room;if(null!=i){var r,a=i.split("_");if(2<a.length)r=new Kn(K.parseInt(a[1]),K.parseInt(a[2]));else r=null;if(null==r||null==t)return;var o=this.data.getTalk(r);if(null==o)return;n=o.domainId}else{var s=e.id.split("_");if(2<s.length)n=new Kn(K.parseInt(s[1]),K.parseInt(s[2]));else n=null}null!=n&&this.sendQueue.sendAnnouncement(n,t)},send:function(e,t){var n,i=e.room.split("_");2<i.length?n=new Kn(K.parseInt(i[1]),K.parseInt(i[2])):n=null;null!=n&&null!=t&&this.sendQueue.sendMessage(n,t)},topic:function(e,t){var n,i=e.room.split("_");2<i.length?n=new Kn(K.parseInt(i[1]),K.parseInt(i[2])):n=null;this.facade.sendNotification("Talk",Te.UPDATE_FOR_HUBOT(n,t))},download:function(e,t,n){var i,r=null,a=null;"string"==typeof t?i=t:(i=t.url,r=t.path,a=t.name),null!=i?(null==a&&(a=Xa.basename(i)),null==r&&(r=Xa.join(Ja.tmpdir(),a)),this.facade.sendNotification("File",Z.DOWNLOAD_PATH(i,r,n))):n(null,new Error("target URL is required"))},leave:function(e,t){var n,i,r=this,a=e.room.split("_");if(2<a.length){var o=new Kn(K.parseInt(a[1]),K.parseInt(a[2]));n=o}else n=null;if(null==t)i=null;else{var s=t.id.split("_");if(2<s.length){var l=new Kn(K.parseInt(s[1]),K.parseInt(s[2]));i=l}else i=null}Ea.delay(function(){r.facade.sendNotification("Talk",Te.DELETE_FOR_HUBOT(n,i))},500)},userForId:function(e,t){var n=tt.fromNullableIdStr(t);return this.hubotObject.userObjectByIdStr(n,e)},userObjects:function(e){var t=tt.fromNullableIdStr(e);return this.hubotObject.userObjects(t)},talkObjects:function(){return this.hubotObject.talkObjects()},domainObjects:function(){return this.hubotObject.domainObjects()},parseInt64:function(e){return 0<e.length&&"_"==e.charAt(0)?tt.makeFromIdStr(e):tt.parse(e)},stringifyInt64:function(e,t){return null==t&&(t=!1),t?"_"+e.high+"_"+e.low:wa.toString(e)},listen:function(){this.facade=p.getInstance(),this.api=Va.__cast(this.facade.retrieveProxy("api"),ur),this.data=Va.__cast(this.facade.retrieveProxy("dataStore"),mr),this.hubotObject=Va.__cast(this.facade.retrieveProxy("hubotObject"),ua),this.sendQueue=Va.__cast(this.facade.retrieveProxy("sendQueue"),ha);var e=Va.__cast(this.facade.retrieveProxy("fileService"),yr),t=Va.__cast(this.facade.retrieveProxy("fileInfoStore"),vr);this.notes=new Qr(new Jr(this,this.api,t,e)),this.facade.startup()},emit:function(e,t,n,i){this.eventEmitter.emit(e,t,n,i)},on:function(e,t){return this.eventEmitter.on(e,t)},getDomainInvites:function(e){this.api._getDomainInvites(e)},acceptDomainInvite:function(e){this.api.acceptDomainInvite(e)},__class__:r};function y(e,t){this.r=new RegExp(e,t.split("u").join(""))}(n.EReg=y).__name__=["EReg"],y.prototype={match:function(e){return this.r.global&&(this.r.lastIndex=0),this.r.m=this.r.exec(e),this.r.s=e,null!=this.r.m},matched:function(e){if(null!=this.r.m&&0<=e&&e<this.r.m.length)return this.r.m[e];throw new Wa("EReg::matched")},matchedPos:function(){if(null==this.r.m)throw new Wa("No string matched");return{pos:this.r.m.index,len:this.r.m[0].length}},matchSub:function(e,t,n){if(null==n&&(n=-1),this.r.global){this.r.lastIndex=t;var i=this.r,r=n<0?e:$e.substr(e,0,t+n);this.r.m=i.exec(r);var a=null!=this.r.m;return a&&(this.r.s=e),a}var o=this.match(n<0?$e.substr(e,t,null):$e.substr(e,t,n));return o&&(this.r.s=e,this.r.m.index+=t),o},split:function(e){var t="#__delim__#";return e.replace(this.r,t).split(t)},map:function(e,t){for(var n=0,i="";!(n>=e.length);){if(!this.matchSub(e,n)){i+=K.string($e.substr(e,n,null));break}var r=this.matchedPos();if(i+=K.string($e.substr(e,n,r.pos-n)),i+=K.string(t(this)),n=0==r.len?(i+=K.string($e.substr(e,r.pos,1)),r.pos+1):r.pos+r.len,!this.r.global)break}return!this.r.global&&0<n&&n<e.length&&(i+=K.string($e.substr(e,n,null))),i},__class__:y};var a=require("events").EventEmitter,o=function(){a.call(this)};(n.EventEmitter=o).__name__=["EventEmitter"],o.__super__=a,o.prototype=i(a.prototype,{__class__:o});var $e=function(){};(n.HxOverrides=$e).__name__=["HxOverrides"],$e.dateStr=function(e){var t=e.getMonth()+1,n=e.getDate(),i=e.getHours(),r=e.getMinutes(),a=e.getSeconds();return e.getFullYear()+"-"+(t<10?"0"+t:""+t)+"-"+(n<10?"0"+n:""+n)+" "+(i<10?"0"+i:""+i)+":"+(r<10?"0"+r:""+r)+":"+(a<10?"0"+a:""+a)},$e.strDate=function(e){switch(e.length){case 8:var t=e.split(":"),n=new Date;return n.setTime(0),n.setUTCHours(t[0]),n.setUTCMinutes(t[1]),n.setUTCSeconds(t[2]),n;case 10:var i=e.split("-");return new Date(i[0],i[1]-1,i[2],0,0,0);case 19:var r=e.split(" "),a=r[0].split("-"),o=r[1].split(":");return new Date(a[0],a[1]-1,a[2],o[0],o[1],o[2]);default:throw new Wa("Invalid date format : "+e)}},$e.cca=function(e,t){var n=e.charCodeAt(t);if(n==n)return n},$e.substr=function(e,t,n){if(null==n)n=e.length;else if(n<0){if(0!=t)return"";n=e.length+n}return e.substr(t,n)},$e.remove=function(e,t){var n=e.indexOf(t);return-1!=n&&(e.splice(n,1),!0)},$e.iter=function(e){return{cur:0,arr:e,hasNext:function(){return this.cur<this.arr.length},next:function(){return this.arr[this.cur++]}}};function et(){}(n.Lambda=et).__name__=["Lambda"],et.array=function(e){for(var t=[],n=fo(e)();n.hasNext();){var i=n.next();t.push(i)}return t},et.map=function(e,t){for(var n=new $,i=fo(e)();i.hasNext();){var r=i.next();n.add(t(r))}return n},et.mapi=function(e,t){for(var n=new $,i=0,r=fo(e)();r.hasNext();){var a=r.next();n.add(t(i++,a))}return n},et.exists=function(e,t){for(var n=fo(e)();n.hasNext();){if(t(n.next()))return!0}return!1},et.foreach=function(e,t){for(var n=fo(e)();n.hasNext();){if(!t(n.next()))return!1}return!0},et.iter=function(e,t){for(var n=fo(e)();n.hasNext();){t(n.next())}},et.filter=function(e,t){for(var n=new $,i=fo(e)();i.hasNext();){var r=i.next();t(r)&&n.add(r)}return n},et.fold=function(e,t,n){for(var i=fo(e)();i.hasNext();){n=t(i.next(),n)}return n},et.count=function(e,t){var n=0;if(null==t)for(var i=fo(e)();i.hasNext();){i.next();++n}else for(var r=fo(e)();r.hasNext();){t(r.next())&&++n}return n},et.find=function(e,t){for(var n=fo(e)();n.hasNext();){var i=n.next();if(t(i))return i}return null};var $=function(){this.length=0};(n.List=$).__name__=["List"],$.prototype={add:function(e){var t=new l(e,null);null==this.h?this.h=t:this.q.next=t,this.q=t,this.length++},isEmpty:function(){return null==this.h},remove:function(e){for(var t=null,n=this.h;null!=n;){if(n.item==e)return null==t?this.h=n.next:t.next=n.next,this.q==n&&(this.q=t),this.length--,!0;n=(t=n).next}return!1},iterator:function(){return new c(this.h)},map:function(e){for(var t=new $,n=this.h;null!=n;){var i=n.item;n=n.next,t.add(e(i))}return t},__class__:$};var l=function(e,t){this.item=e,this.next=t};(n["_List.ListNode"]=l).__name__=["_List","ListNode"],l.prototype={__class__:l};var c=function(e){this.head=e};(n["_List.ListIterator"]=c).__name__=["_List","ListIterator"],c.prototype={hasNext:function(){return null!=this.head},next:function(){var e=this.head.item;return this.head=this.head.next,e},__class__:c},Math.__name__=["Math"];function u(){}(n.ObjectHelper=u).__name__=["ObjectHelper"],u.deepCopy=function(e){return null==e?null:JSON.parse(JSON.stringify(e))};function _(e,t){this.basetime=0,this.count=0,this.max=e,this.interval=t}(n.RateLimit=_).__name__=["RateLimit"],_.prototype={_now:function(){return(new Date).getTime()},calculateRetryAfter:function(e){var t;return t=0<this.basetime?this.interval-(e-this.basetime):this.interval,Math.ceil(t/1e3)},createError:function(e){var t=this.max+" calls every "+Math.floor(this.interval/1e3)+" sec";return fa.createTooManyRequestsError(t,this.calculateRetryAfter(e))},apply:function(i){var r=this;return new Promise(function(e,t){var n=r._now();if(0<r.max&&n-r.basetime>r.interval)r.basetime=n,r.count=1;else{if(!(0<r.max&&r.count<r.max))return void t(r.createError(n));r.count++}i().then(e,t)})},__class__:_};function G(){}(n.Reflect=G).__name__=["Reflect"],G.field=function(e,t){try{return e[t]}catch(e){return null}},G.fields=function(e){var t=[];if(null!=e){var n=Object.prototype.hasOwnProperty;for(var i in e)"__id__"!=i&&"hx__closures__"!=i&&n.call(e,i)&&t.push(i)}return t},G.isFunction=function(e){return"function"==typeof e&&!(e.__name__||e.__ename__)},G.compare=function(e,t){return e==t?0:t<e?1:-1},G.isObject=function(e){if(null==e)return!1;var t=typeof e;return"string"==t||"object"==t&&null==e.__enum__||"function"==t&&null!=(e.__name__||e.__ename__)},G.isEnumValue=function(e){return null!=e&&null!=e.__enum__},G.deleteField=function(e,t){return!!Object.prototype.hasOwnProperty.call(e,t)&&(delete e[t],!0)};var K=function(){};(n.Std=K).__name__=["Std"],K.string=function(e){return Va.__string_rec(e,"")},K.parseInt=function(e){var t=parseInt(e,10);return 0!=t||120!=$e.cca(e,1)&&88!=$e.cca(e,1)||(t=parseInt(e)),isNaN(t)?null:t};function T(){this.b=""}(n.StringBuf=T).__name__=["StringBuf"],T.prototype={toString:function(){return this.b},__class__:T};function W(){}(n.StringTools=W).__name__=["StringTools"],W.htmlEscape=function(e,t){return e=e.split("&").join("&amp;").split("<").join("&lt;").split(">").join("&gt;"),t?e.split('"').join("&quot;").split("'").join("&#039;"):e},W.startsWith=function(e,t){return e.length>=t.length&&$e.substr(e,0,t.length)==t},W.isSpace=function(e,t){var n=$e.cca(e,t);return 8<n&&n<14||32==n},W.ltrim=function(e){for(var t=e.length,n=0;n<t&&W.isSpace(e,n);)++n;return 0<n?$e.substr(e,n,t-n):e},W.rtrim=function(e){for(var t=e.length,n=0;n<t&&W.isSpace(e,t-n-1);)++n;return 0<n?$e.substr(e,0,t-n):e},W.trim=function(e){return W.ltrim(W.rtrim(e))},W.replace=function(e,t,n){return e.split(t).join(n)},W.hex=function(e,t){for(var n="";n="0123456789ABCDEF".charAt(15&e)+n,0<(e>>>=4););if(null!=t)for(;n.length<t;)n="0"+n;return n};function h(){}(n.TextHelper=h).__name__=["TextHelper"],h.slice=function(e,n){for(var i=[],t=function(e){for(;e.length>n;){var t=$e.substr(e,0,n);i.push(t),e=$e.substr(e,n,null)}0<e.length&&i.push(e)},r="",a=e.split("\n");0<a.length;){var o=a.shift();r.length+o.length>n&&(t(r),r=""),0<r.length&&(r+="\n"),r+=o}return t(r),i};var d=n.ValueType={__ename__:["ValueType"],__constructs__:["TNull","TInt","TFloat","TBool","TObject","TFunction","TClass","TEnum","TUnknown"]};d.TNull=["TNull",0],d.TNull.toString=s,(d.TNull.__enum__=d).TInt=["TInt",1],d.TInt.toString=s,(d.TInt.__enum__=d).TFloat=["TFloat",2],d.TFloat.toString=s,(d.TFloat.__enum__=d).TBool=["TBool",3],d.TBool.toString=s,(d.TBool.__enum__=d).TObject=["TObject",4],d.TObject.toString=s,(d.TObject.__enum__=d).TFunction=["TFunction",5],d.TFunction.toString=s,(d.TFunction.__enum__=d).TClass=function(e){var t=["TClass",6,e];return t.__enum__=d,t.toString=s,t},d.TEnum=function(e){var t=["TEnum",7,e];return t.__enum__=d,t.toString=s,t},d.TUnknown=["TUnknown",8],d.TUnknown.toString=s,(d.TUnknown.__enum__=d).__empty_constructs__=[d.TNull,d.TInt,d.TFloat,d.TBool,d.TObject,d.TFunction,d.TUnknown];function ee(){}(n.Type=ee).__name__=["Type"],ee.getClassName=function(e){var t=e.__name__;return null==t?null:t.join(".")},ee.getEnumName=function(e){return e.__ename__.join(".")},ee.resolveClass=function(e){var t=n[e];return null!=t&&t.__name__?t:null},ee.resolveEnum=function(e){var t=n[e];return null!=t&&t.__ename__?t:null},ee.createInstance=function(e,t){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]);case 8:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7]);case 9:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8]);case 10:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9]);case 11:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10]);case 12:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11]);case 13:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12]);case 14:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6],t[7],t[8],t[9],t[10],t[11],t[12],t[13]);default:throw new Wa("Too many arguments")}},ee.createEmptyInstance=function(e){function t(){}return t.prototype=e.prototype,new t},ee.createEnum=function(e,t,n){var i=G.field(e,t);if(null==i)throw new Wa("No such constructor "+t);if(G.isFunction(i)){if(null==n)throw new Wa("Constructor "+t+" need parameters");return i.apply(e,n)}if(null!=n&&0!=n.length)throw new Wa("Constructor "+t+" does not need parameters");return i},ee.typeof=function(e){switch(typeof e){case"boolean":return d.TBool;case"function":return e.__name__||e.__ename__?d.TObject:d.TFunction;case"number":return Math.ceil(e)==e%2147483648?d.TInt:d.TFloat;case"object":if(null==e)return d.TNull;var t=e.__enum__;if(null!=t)return d.TEnum(t);var n=Va.getClass(e);return null!=n?d.TClass(n):d.TObject;case"string":return d.TClass(String);case"undefined":return d.TNull;default:return d.TUnknown}},ee.enumEq=function(e,t){if(e==t)return!0;try{if(e[0]!=t[0])return!1;for(var n=2,i=e.length;n<i;){var r=n++;if(!ee.enumEq(e[r],t[r]))return!1}var a=e.__enum__;if(a!=t.__enum__||null==a)return!1}catch(e){return!1}return!0};function f(){}(n["puremvc.interfaces.IFacade"]=f).__name__=["puremvc","interfaces","IFacade"],f.prototype={__class__:f};var m=function(){(m.instance=this).initializeFacade()};(n["puremvc.patterns.facade.Facade"]=m).__name__=["puremvc","patterns","facade","Facade"],m.__interfaces__=[f],m.getInstance=function(){return null==m.instance&&(m.instance=new m),m.instance},m.prototype={initializeFacade:function(){this.initializeModel(),this.initializeController(),this.initializeView()},initializeController:function(){null==this.controller&&(this.controller=ro.getInstance())},initializeModel:function(){null==this.model&&(this.model=oo.getInstance())},initializeView:function(){null==this.view&&(this.view=lo.getInstance())},registerCommand:function(e,t){this.controller.registerCommand(e,t)},removeCommand:function(e){this.controller.removeCommand(e)},hasCommand:function(e){return this.controller.hasCommand(e)},registerProxy:function(e){this.model.registerProxy(e)},retrieveProxy:function(e){return this.model.retrieveProxy(e)},removeProxy:function(e){var t=null;return null!=this.model&&(t=this.model.removeProxy(e)),t},hasProxy:function(e){return this.model.hasProxy(e)},registerMediator:function(e){null!=this.view&&this.view.registerMediator(e)},retrieveMediator:function(e){return this.view.retrieveMediator(e)},removeMediator:function(e){var t=null;return null!=this.view&&(t=this.view.removeMediator(e)),t},hasMediator:function(e){return this.view.hasMediator(e)},sendNotification:function(e,t,n){this.notifyObservers(new _o(e,t,n))},notifyObservers:function(e){null!=this.view&&this.view.notifyObservers(e)},__class__:m};var p=function(){m.call(this)};(n["albero.AppFacade"]=p).__name__=["albero","AppFacade"],p.getInstance=function(){return null==m.instance&&(m.instance=new p),Va.__cast(m.instance,p)},p.__super__=m,p.prototype=i(m.prototype,{initializeModel:function(){m.prototype.initializeModel.call(this);var e=[];(e=(e=e.concat([new ua,new ha,new ca])).concat([new Cr,new hr,new mr,new fr,new pr,new jr,new lr,new ur,new cr,new _r,Sr.newInstance(),new Ur,new vr,new Br,new Yr,new Tr,new gr,new kr,new Kr,new Hr,new xr,new Dr,new Wr,new dr,new zr,new br,new Gr,nr.newInstance()])).push(or.newInstance());for(var t=0;t<e.length;){var n=e[t];++t,this.registerProxy(n)}for(var i=0;i<e.length;){var r=e[i];++i,this.autoBind(r)}},initializeView:function(){m.prototype.initializeView.call(this);for(var e=0,t=this.getMediators();e<t.length;){var n=t[e];++e,this.registerMediator(n)}},getMediators:function(){return[new la]},initializeController:function(){m.prototype.initializeController.call(this);for(var e=[Q,ye,Se,he,ve,we,re,ce,te,X,pe,Ee,Ie,Ne,Ae,fe,B,oe,z,j,le],t=0;t<e.length;){var n=e[t];++t;var i=W.replace(ee.getClassName(n).split(".").pop(),"Command","");this.registerCommand(i,n)}},registerMediator:function(e){this.autoBind(e),m.prototype.registerMediator.call(this,e)},autoBind:function(e){for(var t=e,n=Ka.getFields(null==t?null:Va.getClass(t)),i=0,r=G.fields(n);i<r.length;){var a=r[i];++i;var o=G.field(n,a);if(Object.prototype.hasOwnProperty.call(o,"inject")){var s=this.retrieveProxy(a);null!=s&&(e[a]=s)}}},startup:function(){Va.__cast(this.retrieveProxy("appState"),hr).start()},__class__:p});var g=n["albero.AppState"]={__ename__:["albero","AppState"],__constructs__:["Active","Inactive"]};g.Active=["Active",0],g.Active.toString=s,(g.Active.__enum__=g).Inactive=["Inactive",1],g.Inactive.toString=s,(g.Inactive.__enum__=g).__empty_constructs__=[g.Active,g.Inactive];var v=n["albero.ConnectionStatus"]={__ename__:["albero","ConnectionStatus"],__constructs__:["Ok","Error","ConcurrentAccessError","ForcibliyClosedError"]};v.Ok=["Ok",0],v.Ok.toString=s,(v.Ok.__enum__=v).Error=["Error",1],v.Error.toString=s,(v.Error.__enum__=v).ConcurrentAccessError=["ConcurrentAccessError",2],v.ConcurrentAccessError.toString=s,(v.ConcurrentAccessError.__enum__=v).ForcibliyClosedError=["ForcibliyClosedError",3],v.ForcibliyClosedError.toString=s,(v.ForcibliyClosedError.__enum__=v).__empty_constructs__=[v.Ok,v.Error,v.ConcurrentAccessError,v.ForcibliyClosedError];function S(){}(n["albero.ContentTypeResolver"]=S).__name__=["albero","ContentTypeResolver"],S.prototype={__class__:S};function w(){}(n["albero.DefaultContentTypeResolver"]=w).__name__=["albero","DefaultContentTypeResolver"],w.__interfaces__=[S],w.getContentTypeByFileName=function(e,t){if(k.isNotEmpty(t))return"csv"==w.getExtension(e)?"text/csv":t;switch(w.getExtension(e)){case"csv":return"text/csv";case"doc":return"application/msword";case"docm":return"application/vnd.ms-word.document.macroenabled.12";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"gif":return"image/gif";case"htm":case"html":return"text/html";case"jpeg":case"jpg":return"image/jpeg";case"md":return"text/markdown";case"pdf":return"application/pdf";case"png":return"image/png";case"ppt":return"application/vnd.ms-powerpoint";case"pptm":return"application/vnd.ms-powerpoint.presentation.macroenabled.12";case"pptx":return"application/vnd.openxmlformats-officedocument.presentationml.presentation";case"svg":return"image/svg+xml";case"txt":return"text/plain";case"webp":return"image/webp";case"xls":return"application/vnd.ms-excel";case"xlsb":return"application/vnd.ms-excel.sheet.binary.macroenabled.12";case"xlsm":return"application/vnd.ms-excel.sheet.macroenabled.12";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"xml":return"text/xml";default:return"application/octet-stream"}},w.getExtension=function(e){if(null==e)return"";var t=e.split("."),n=t.length;return 0==n?"":t[n-1]},w.prototype={resolve:function(e){return w.getContentTypeByFileName(e.name,e.type)},__class__:w};function I(){}(n["albero.DateTimeHelper"]=I).__name__=["albero","DateTimeHelper"],I.isSameDate=function(e,t){return e.getFullYear()==t.getFullYear()&&e.getMonth()==t.getMonth()&&e.getDate()==t.getDate()},I.dateString=function(e,t){var n=new Date,i="";return e.getFullYear()!=n.getFullYear()&&(i+=e.getFullYear()+"/"),i+=e.getMonth()+1+"/"+e.getDate(),t&&(i+=" ("+I.dayOfWeekString(e)+")"),i},I.dayOfWeekString=function(e){switch(e.getDay()){case 0:return Yi.localize("DateTimeHelper.sun");case 1:return Yi.localize("DateTimeHelper.mon");case 2:return Yi.localize("DateTimeHelper.tue");case 3:return Yi.localize("DateTimeHelper.wed");case 4:return Yi.localize("DateTimeHelper.thu");case 5:return Yi.localize("DateTimeHelper.fri");default:return Yi.localize("DateTimeHelper.sat")}},I.getDateStringForFile=function(){var e=new Date;return e.getFullYear()+I.toDoubleDigits(e.getMonth()+1)+I.toDoubleDigits(e.getDate())+"_"+I.toDoubleDigits(e.getHours())+I.toDoubleDigits(e.getMinutes())+I.toDoubleDigits(e.getSeconds())},I.getTimeStringForVoice=function(e){return I.toDoubleDigits(e/60|0)+":"+I.toDoubleDigits((0|e)%60)},I.toDoubleDigits=function(e){var t=null==e?"null":""+e;return 1==t.length&&(t="0"+t),t},I.nowAsInt64=function(){return I.dateAsInt64((new Date).getTime())},I.oneDayAfterAsInt64=function(){return I.dateAsInt64((new Date).getTime()+864e5)},I.afterAsInt64=function(e){return I.dateAsInt64((new Date).getTime()+e)},I.dateAsInt64=function(e){var t=4294967296;return new Kn(e/t|0,e%t|0)},I.abbreviateDatetimeString=function(e){if(null==e)return"";var t=new Date,n=4294967296,i=e.high,r=e.low,a=new Date(i*n+(0<=r?r:r+n));return t.getFullYear()==a.getFullYear()&&t.getMonth()==a.getMonth()&&t.getDate()==a.getDate()?a.getHours()+":"+(a.getMinutes()<10?"0":"")+a.getMinutes():I.dateString(a,!1)},I.datetimeStringIn11Chars=function(e){if(null==e)return"";var t=new Date,n=4294967296,i=e.high,r=e.low,a=new Date(i*n+(0<=r?r:r+n)),o=I.dateString(a,!1);return t.getFullYear()==a.getFullYear()&&(o+=" "+a.getHours()+":"+(a.getMinutes()<10?"0":"")+a.getMinutes()),o},I.timeString=function(e){if(null==e)return"";var t=4294967296,n=e.high,i=e.low,r=new Date(n*t+(0<=i?i:i+t));return r.getHours()+":"+(r.getMinutes()<10?"0":"")+r.getMinutes()},I.datetimeString=function(e){if(null==e)return"";var t=parseFloat(wa.toString(e)),n=new Date(t);return n.getFullYear()+"/"+(n.getMonth()+1)+"/"+n.getDate()+" "+n.getHours()+":"+(n.getMinutes()<10?"0":"")+n.getMinutes()};function E(){}(n["albero.FileDynamicHelper"]=E).__name__=["albero","FileDynamicHelper"],E.filterDeleted=function(e){return null==e?[]:e.filter(E.isNotDeleted)},E.isNotDeleted=function(e){return null==e.deleted||!e.deleted},E.createFileInfoDynamic=function(e,t,n,i){var r={url:i.get_url,content_type:e.type,content_size:e.size,name:t,file_id:i.file_id};return it.foreach(n,function(e){null!=e.auth&&(r.thumbnail_url=e.auth.get_url),null!=e.dimension&&(r.thumbnail_dimension=e.dimension.toObject())}),r};function N(){}(n["albero.FileHelper"]=N).__name__=["albero","FileHelper"],N.createByteSizeStringWithUnit=function(e){if(null==e)return"0 B";for(var t,n=["","K","M","G","T"];;){var i=new Kn(0,1024),r=t=wa.divMod(e,i).quotient,a=new Kn(0,0),o=r.high-a.high|0;if(o=0!=o?o:Sa.ucompare(r.low,a.low),!(0<(r.high<0?a.high<0?o:-1:0<=a.high?o:1)))break;e=t,n.shift()}return wa.toString(e)+" "+n.shift()+"B"},N.extractFilenameExceptExtension=function(e){return new y("\\.(?=[^.]+$)","").split(e)[0]};function A(){}(n["albero.History"]=A).__name__=["albero","History"],A.replaceState=function(e,t,n){return null!=window.history&&(window.history.replaceState(e,t,n),!0)};var tt=function(){};(n["albero.Int64Helper"]=tt).__name__=["albero","Int64Helper"],tt.parse=function(e){if(!new y("^\\d+$","").match(e))return null;for(var t=new Kn(0,0),n=new Kn(0,10),i=0,r=e.length;i<r;){var a=i++,o=65535&t.low,s=t.low>>>16,l=65535&n.low,u=n.low>>>16,c=Sa._mul(o,l),_=Sa._mul(s,l),h=Sa._mul(o,u),d=c,f=(Sa._mul(s,u)+(h>>>16)|0)+(_>>>16)|0;if(d=d+(h<<=16)|0,Sa.ucompare(d,h)<0){f++;f|=0}if(d=d+(_<<=16)|0,Sa.ucompare(d,_)<0){f++;f|=0}f=f+(Sa._mul(t.low,n.high)+Sa._mul(t.high,n.low)|0)|0;var m=new Kn(f,d),p=new Kn(0,K.parseInt(e.charAt(a))),g=m.high+p.high|0,v=m.low+p.low|0;if(Sa.ucompare(v,m.low)<0){g++;g|=0}t=new Kn(g,v)}return t},tt.getHigh=function(e){return e.high},tt.getLow=function(e){return e.low},tt.idStr=function(e){return"_"+e.high+"_"+e.low},tt.makeFromIdStr=function(e){var t=new y("^_(-?\\d*)_(-?\\d*)$","");return t.match(e)?new Kn(K.parseInt(t.matched(1)),K.parseInt(t.matched(2))):null},tt.fromNullableIdStr=function(e){return null!=e?tt.makeFromIdStr(e):null},tt.toStr=function(e){return wa.toString(e)},tt.isNeg=function(e){return e.high<0},tt.add=function(e,t){var n=e.high+t.high|0,i=e.low+t.low|0;if(Sa.ucompare(i,e.low)<0){n++;n|=0}return new Kn(n,i)},tt.sub=function(e,t){var n=e.high-t.high|0,i=e.low-t.low|0;if(Sa.ucompare(e.low,t.low)<0){n--;n|=0}return new Kn(n,i)},tt.compare=function(e,t){var n=e.high-t.high|0;return n=0!=n?n:Sa.ucompare(e.low,t.low),e.high<0?t.high<0?n:-1:0<=t.high?n:1},tt.eq=function(e,t){return null!=e&&null!=t&&e.high==t.high&&e.low==t.low},tt.eqOrBothNull=function(e,t){return null==e&&null==t||null!=e&&null!=t&&e.high==t.high&&e.low==t.low},tt.toFloat=function(e){var t=4294967296,n=e.high,i=e.low;return n*t+(0<=i?i:i+t)},tt.idStrToInt64=function(e){var t=e.split("_");return 2<t.length?new Kn(K.parseInt(t[1]),K.parseInt(t[2])):null},tt.decrement=function(e){if(null==e)return null;var t=new Kn(0,1),n=e.high-t.high|0,i=e.low-t.low|0;if(Sa.ucompare(e.low,t.low)<0){n--;n|=0}return new Kn(n,i)},tt.increment=function(e){if(null==e)return null;var t=new Kn(0,1),n=e.high+t.high|0,i=e.low+t.low|0;if(Sa.ucompare(i,e.low)<0){n++;n|=0}return new Kn(n,i)},tt.unique=function(e){if(null==e)return[];for(var t=[],n=0,i=e.length;n<i;){var r=n++,a=e[r];tt.indexOf(e,a)==r&&t.push(a)}return t},tt.indexOf=function(e,t){if(null==e)return-1;for(var n=0,i=e.length;n<i;){var r=n++,a=e[r];if(null!=a&&null!=t&&a.high==t.high&&a.low==t.low)return r}return-1},tt.contains=function(e,t){if(null==e)return!1;for(var n=0;n<e.length;){var i=e[n];if(++n,null!=i&&null!=t&&i.high==t.high&&i.low==t.low)return!0}return!1},tt.notContains=function(e,t){return!tt.contains(e,t)},tt.remove=function(e,t){if(null==e)return!1;for(var n=0;n<e.length;){var i=e[n];if(++n,null!=i&&null!=t&&i.high==t.high&&i.low==t.low)return $e.remove(e,i),!0}return!1},tt.fromIntOrInt64=function(e){if(null==e||Va.__instanceof(e,Kn))return e;var t=Va.__cast(e,vo);return new Kn(t>>31,t)},tt.eqArray=function(e,t){if(e!=t){if(null==e||null==t)return!1;if(e.length!=t.length)return!1;for(var n=0,i=e.length;n<i;){var r=n++,a=e[r],o=t[r];if(null==a||null==o||a.high!=o.high||a.low!=o.low)return!1}}return!0},tt.splitUsingMaxCount=function(e,t){for(var n=[],i=0;i<e.length;){var r=i+t,a=e.slice(i,r);n.push(a),i=r}return n};function b(){}(n["albero.LambdaHelper"]=b).__name__=["albero","LambdaHelper"],b.flatten=function(e){return et.filter(e,function(e){return it.isDefined(e)}).map(function(e){return it.get(e)})},b.headOption=function(e){for(var t=fo(e)();t.hasNext();){var n=t.next();return Ra.Some(n)}return Ra.None},b.lastOption=function(e){for(var t=Ra.None,n=fo(e)();n.hasNext();){var i=n.next();t=Ra.Some(i)}return t},b.findOption=function(e,t){return it.option(et.find(e,t))},b.indexWhere=function(e,t){for(var n=0,i=fo(e)();i.hasNext();){if(t(i.next()))return n;++n}return-1},b.forall=function(e,t){return!et.exists(e,function(e){return!t(e)})};function nt(){}(n["albero.ArrayHelper"]=nt).__name__=["albero","ArrayHelper"],nt.lastOption=function(e){return 0==e.length?Ra.None:Ra.Some(e[e.length-1])},nt.sortAndReturn=function(e,t){return e.sort(t),e},nt.reverseAndReturn=function(e){return e.reverse(),e},nt.asArray=function(e){return Va.__cast(e,Array)};var it=function(){};(n["albero.OptionHelper"]=it).__name__=["albero","OptionHelper"],it.map=function(e,t){switch(e[1]){case 0:var n=e[2];return Ra.Some(t(n));case 1:return Ra.None}},it.flatMap=function(e,t){switch(e[1]){case 0:return t(e[2]);case 1:return Ra.None}},it.foreach=function(e,t){switch(e[1]){case 0:t(e[2])}},it.filter=function(e,t){switch(e[1]){case 0:return t(e[2])?e:Ra.None;case 1:return Ra.None}},it.exists=function(e,t){return it.isDefined(it.filter(e,t))},it.isDefined=function(e){switch(e[1]){case 0:return!0;case 1:return!1}},it.isEmpty=function(e){switch(e[1]){case 0:return!1;case 1:return!0}},it.get=function(e){switch(e[1]){case 0:return e[2];case 1:throw new Wa("None.get called")}},it.orNull=function(e){switch(e[1]){case 0:return e[2];case 1:return null}},it.flatten=function(e){return it.flatMap(e,function(e){return e})},it.eq=function(e,t){return ee.enumEq(e,t)},it.option=function(e){return null!=e?Ra.Some(e):Ra.None};function D(){}(n["albero.StorageHelper"]=D).__name__=["albero","StorageHelper"],D.getItemAsJson=function(e){var t=D.getItem(e);if(null==t)return null;try{return JSON.parse(t)}catch(e){return null}},D.getItemAsInt=function(e){var t=D.getItem(e);return null==t?null:K.parseInt(t)},D.getItem=function(e){var t=ji.getLocalStorage();if(null==t)Gi._e("["+$e.dateStr(new Date)+"] ","storage not found","","","","");else try{return t.getItem(e)}catch(e){e instanceof Wa&&(e=e.val),Gi._e("["+$e.dateStr(new Date)+"] ","storage error occered.",e,"","","")}return null},D.removeItem=function(e){var t=ji.getLocalStorage();if(null==t)Gi._e("["+$e.dateStr(new Date)+"] ","storage not found","","","","");else try{return t.removeItem(e),!0}catch(e){e instanceof Wa&&(e=e.val),Gi._e("["+$e.dateStr(new Date)+"] ","storage error occered.",e,"","","")}return!1},D.setItem=function(e,t){var n=ji.getLocalStorage();if(null==n)Gi._e("["+$e.dateStr(new Date)+"] ","storage not found","","","","");else try{return n.setItem(e,t),!0}catch(e){e instanceof Wa&&(e=e.val),Gi._e("["+$e.dateStr(new Date)+"] ","storage error occered.",e,"","","")}return!1},D.getItemWithUnserialize=function(e){var t=D.getItem(e);if(null!=t)try{return Aa.run(t)}catch(e){e instanceof Wa&&(e=e.val),Gi._w("["+$e.dateStr(new Date)+"] ",e,"","","","")}return null},D.setItemWithSerialize=function(e,t){D.setItem(e,Ia.run(t))};var k=function(){};(n["albero.StringHelper"]=k).__name__=["albero","StringHelper"],k.trim=function(e){return e.trim()},k.compare=function(e,t){return t<e?1:e<t?-1:0},k.isEmpty=function(e){return null==e||0==e.length},k.isNotEmpty=function(e){return!k.isEmpty(e)},k.randomString=function(){var e="",t=8;for(e+=K.string(W.hex(0|(new Date).getTime(),8));t++<36;)e+=K.string(0!=(51*t&52)?W.hex(0!=(15^t)?8^(Math.random()*(0!=(20^t)?16:4)|0):4):"-");return e.toLowerCase()};var V=n["albero.Urls"]={__ename__:["albero","Urls"],__constructs__:["auto","domains","domain","members","talks","actions","bookmarks","settings","announcements","error","loading","environment","unknown"]};V.auto=["auto",0],V.auto.toString=s,(V.auto.__enum__=V).domains=["domains",1],V.domains.toString=s,(V.domains.__enum__=V).domain=function(e){var t=["domain",2,e];return t.__enum__=V,t.toString=s,t},V.members=function(e){var t=["members",3,e];return t.__enum__=V,t.toString=s,t},V.talks=function(e,t){var n=["talks",4,e,t];return n.__enum__=V,n.toString=s,n},V.actions=function(e){var t=["actions",5,e];return t.__enum__=V,t.toString=s,t},V.bookmarks=function(e){var t=["bookmarks",6,e];return t.__enum__=V,t.toString=s,t},V.settings=function(e){var t=["settings",7,e];return t.__enum__=V,t.toString=s,t},V.announcements=["announcements",8],V.announcements.toString=s,(V.announcements.__enum__=V).error=["error",9],V.error.toString=s,(V.error.__enum__=V).loading=["loading",10],V.loading.toString=s,(V.loading.__enum__=V).environment=function(e){var t=["environment",11,e];return t.__enum__=V,t.toString=s,t},V.unknown=["unknown",12],V.unknown.toString=s,(V.unknown.__enum__=V).__empty_constructs__=[V.auto,V.domains,V.announcements,V.error,V.loading,V.unknown];var C=n["albero.TalkUrlParam"]={__ename__:["albero","TalkUrlParam"],__constructs__:["multi","single"]};C.multi=function(e){var t=["multi",0,e];return t.__enum__=C,t.toString=s,t},C.single=function(e){var t=["single",1,e];return t.__enum__=C,t.toString=s,t},C.__empty_constructs__=[];function O(){}(n["albero.TalkUrlParamHelper"]=O).__name__=["albero","TalkUrlParamHelper"],O.getTalkSelectionForSingle=function(e){switch(e[1]){case 0:return Ra.None;case 1:var t=e[2];return Ra.Some(t)}},O.getTalkSelectionsForMulti=function(e){switch(e[1]){case 0:var t=e[2];return Ra.Some(t);case 1:return Ra.None}};function M(){}(n["albero.UrlConverter"]=M).__name__=["albero","UrlConverter"],M.createUrls=function(e,t){if(null==e)return V.unknown;var n=e.split("/");return""!=n[0]?V.unknown:n.length<2?V.unknown:2==n.length?M.createUrlsWithoutDomain(n,t):M.createUrlsWithDomain(n,t)},M.createUrlsWithoutDomain=function(e,t){switch(e[1]){case"":return V.domains;case"environment":var n=t.getFallbackDomainId();return it.foreach(n,function(e){A.replaceState("environment",null,"#"+M.createFragment(V.environment(e),t))}),V.environment(it.orNull(n));case"error":return V.error;case"loading":return V.loading;case"settings":var i=t.getFallbackDomainId();return it.foreach(i,function(e){A.replaceState("settings",null,"#"+M.createFragment(V.settings(e),t))}),V.settings(it.orNull(i));default:return V.unknown}},M.createUrlsWithDomain=function(e,t){var n=tt.parse(e[1]);if(null==n)return V.unknown;switch(e[2]){case"":return V.domain(n);case"actions":return V.actions(n);case"bookmarks":return V.bookmarks(n);case"environment":return V.environment(n);case"members":return V.members(n);case"settings":return V.settings(n);case"talks":if(e.length<4)return V.talks(n,C.single(Fn.NotSelected));if("multi"==e[3]||",,"==e[3])return V.talks(n,C.multi([Fn.NotSelected,Fn.NotSelected,Fn.NotSelected]));if("single"==e[3]||""==e[3])return V.talks(n,C.single(Fn.NotSelected));var i=e[3].split(",");if(1==i.length){var r=e.length<5?Ra.None:it.option(tt.parse(e[4])),a=M.createTalkSelection(i[0],r);return V.talks(n,C.single(a))}if(3!=i.length)break;var o=i.map(function(e){return M.createTalkSelection(e,Ra.None)});return V.talks(n,C.multi(o))}return V.unknown},M.createTalkSelection=function(e,t){if(e==M.ANNOUNCEMENTS_KEY)return Fn.AnnouncementsSelected;var n=tt.parse(e);return null==n?Fn.NotSelected:Fn.TalkSelected(n,t)},M.createFragment=function(e,t){switch(e[1]){case 1:return"/";case 2:var n=e[2];return"/"+wa.toString(n)+"/";case 3:var i=e[2];return"/"+wa.toString(i)+"/members";case 4:var r=e[3],a=e[2];switch(r[1]){case 0:var o="/"+r[2].map(M.createTalkPartFragment).join(",");return"/"+wa.toString(a)+"/talks"+o;case 1:var s=r[2],l=M.createTalkPartFragment(s),u=k.isEmpty(l)?"":"/"+l;return"/"+wa.toString(a)+"/talks"+u}break;case 5:var c=e[2];return"/"+wa.toString(c)+"/actions";case 6:var _=e[2];return"/"+wa.toString(_)+"/bookmarks";case 7:var h,d=e[2];switch(Gi._d("["+$e.dateStr(new Date)+"] ","convert urls.settings to fragment. domainId:",null!=d?d:"","","",""),it.option(d)[1]){case 0:h=it.option(d);break;case 1:h=t.getLastSelectedDomainId()}var f=it.map(h,function(e){return"/"+wa.toString(e)+"/settings"});switch(f[1]){case 0:return f[2];case 1:return"/settings"}break;case 9:case 10:return"/"+K.string(e);case 11:var m,p=e[2];switch(Gi._d("["+$e.dateStr(new Date)+"] ","convert urls.environment to fragment. domainId:",null!=p?p:"","","",""),it.option(p)[1]){case 0:m=it.option(p);break;case 1:m=t.getLastSelectedDomainId()}var g=it.map(m,function(e){return"/"+wa.toString(e)+"/environment"});switch(g[1]){case 0:return g[2];case 1:return"/environment"}break;default:return null}},M.createTalkPartFragment=function(e){switch(e[1]){case 0:return"";case 1:var t,n=e[3],i=e[2],r=it.map(n,function(e){return"/"+wa.toString(e)});switch(r[1]){case 0:t=r[2];break;case 1:t=""}return wa.toString(i)+t;case 2:return M.ANNOUNCEMENTS_KEY}};function R(){}(n["albero.IUrlConverterDelegate"]=R).__name__=["albero","IUrlConverterDelegate"],R.prototype={__class__:R};function F(){}(n["puremvc.interfaces.INotifier"]=F).__name__=["puremvc","interfaces","INotifier"],F.prototype={__class__:F};function x(){this.facade=m.getInstance()}(n["puremvc.patterns.observer.Notifier"]=x).__name__=["puremvc","patterns","observer","Notifier"],x.__interfaces__=[F],x.prototype={sendNotification:function(e,t,n){this.facade.sendNotification(e,t,n)},__class__:x};function U(){}(n["puremvc.interfaces.ICommand"]=U).__name__=["puremvc","interfaces","ICommand"],U.prototype={__class__:U};function P(){x.call(this)}(n["puremvc.patterns.command.SimpleCommand"]=P).__name__=["puremvc","patterns","command","SimpleCommand"],P.__interfaces__=[U],P.__super__=x,P.prototype=i(x.prototype,{execute:function(e){},__class__:P});function L(){P.call(this),p.getInstance().autoBind(this)}(n["albero.command.AutoBindCommand"]=L).__name__=["albero","command","AutoBindCommand"],L.__super__=P,L.prototype=i(P.prototype,{__class__:L});var B=function(){L.call(this)};(n["albero.command.AccountControlRequestCommand"]=B).__name__=["albero","command","AccountControlRequestCommand"],B.__super__=L,B.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:var n=t[2];this.api.acceptAccountControlRequest(n);break;case 1:var i=t[2];this.api.rejectAccountControlRequest(i)}},__class__:B});var H=n["albero.command.AccountControlRequestAction"]={__ename__:["albero","command","AccountControlRequestAction"],__constructs__:["ACCEPT_REQUEST","REJECT_REQUEST"]};H.ACCEPT_REQUEST=function(e){var t=["ACCEPT_REQUEST",0,e];return t.__enum__=H,t.toString=s,t},H.REJECT_REQUEST=function(e){var t=["REJECT_REQUEST",1,e];return t.__enum__=H,t.toString=s,t},H.__empty_constructs__=[];var j=function(){L.call(this)};(n["albero.command.ConferenceCommand"]=j).__name__=["albero","command","ConferenceCommand"],j.__super__=L,j.prototype=i(L.prototype,{execute:function(e){var t=this,n=e.getBody();switch(n[1]){case 0:var i=n[3],r=n[2];this.api.joinConference(r,i);break;case 1:var a=n[2];this.api.leaveConference(a);var o=it.filter(this.conferenceStore.getConference(a),function(e){return e.isExpired()});it.foreach(o,function(e){t.conferenceStore.removeConference(e),t.sendNotification("notify_close_conference",e)});break;case 2:var s=n[2];this.api.rejectConference(s);break;case 3:var l=n[2];this.api.getConferenceParticipants(l)}},__class__:j});var Y=n["albero.command.ConferenceAction"]={__ename__:["albero","command","ConferenceAction"],__constructs__:["JOIN_CONFERENCE","LEAVE_CONFERENCE","REJECT_CONFERENCE","GET_CONFERENCE_PARTICIPANTS"]};Y.JOIN_CONFERENCE=function(e,t){var n=["JOIN_CONFERENCE",0,e,t];return n.__enum__=Y,n.toString=s,n},Y.LEAVE_CONFERENCE=function(e){var t=["LEAVE_CONFERENCE",1,e];return t.__enum__=Y,t.toString=s,t},Y.REJECT_CONFERENCE=function(e){var t=["REJECT_CONFERENCE",2,e];return t.__enum__=Y,t.toString=s,t},Y.GET_CONFERENCE_PARTICIPANTS=function(e){var t=["GET_CONFERENCE_PARTICIPANTS",3,e];return t.__enum__=Y,t.toString=s,t},Y.__empty_constructs__=[];var z=function(){L.call(this)};(n["albero.command.DeviceCommand"]=z).__name__=["albero","command","DeviceCommand"],z.__super__=L,z.prototype=i(L.prototype,{execute:function(e){var n=this;e.getBody();require("read")({prompt:"Code: "},function(e,t){n.api.authorizeDevice(t,function(){n.sendNotification("SignIn")})})},__class__:z});var q=n["albero.command.DeviceAction"]={__ename__:["albero","command","DeviceAction"],__constructs__:["AUTHORIZE"]};q.AUTHORIZE=["AUTHORIZE",0],q.AUTHORIZE.toString=s,(q.AUTHORIZE.__enum__=q).__empty_constructs__=[q.AUTHORIZE];var Q=function(){L.call(this)};(n["albero.command.DomainCommand"]=Q).__name__=["albero","command","DomainCommand"],Q.__super__=L,Q.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:var n=t[2];this.api.acceptDomainInvite(n);break;case 1:var i=t[2];this.api.deleteDomainInvite(i);break;case 2:var r=t[2];this.api.leaveDomain(r)}},__class__:Q});var J=n["albero.command.DomainAction"]={__ename__:["albero","command","DomainAction"],__constructs__:["ACCEPT_INVITE","DELETE_INVITE","LEAVE"]};J.ACCEPT_INVITE=function(e){var t=["ACCEPT_INVITE",0,e];return t.__enum__=J,t.toString=s,t},J.DELETE_INVITE=function(e){var t=["DELETE_INVITE",1,e];return t.__enum__=J,t.toString=s,t},J.LEAVE=function(e){var t=["LEAVE",2,e];return t.__enum__=J,t.toString=s,t},J.__empty_constructs__=[];var X=function(){L.call(this)};(n["albero.command.FileCommand"]=X).__name__=["albero","command","FileCommand"],X.__super__=L,X.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:var n=t[3],i=t[2];this.api.uploadV2(i.domainId,i.id,n);break;case 1:var r=t[4],a=t[3],o=t[2];this.api.uploadMultiV2(o.domainId,o.id,a,r);break;case 2:var s=t[2];s.deleted=!0,this.api.deleteAttachment(s.id,s.messageId);break;case 3:var l=t[6],u=t[5],c=t[4],_=t[3],h=t[2];this.api.createDownloadAuth(h,_,c,u,l);break;case 4:var d=t[6],f=t[5],m=t[4],p=t[3],g=t[2],v=this.fileService.createDummyFile(p,m,f);this.api.uploadForHubot(g,v,d);break;case 5:for(var y=t[7],S=t[6],w=t[5],T=t[4],I=t[3],E=t[2],N=[],A=0,b=T.length;A<b;){var D=A++;N.push(this.fileService.createDummyFile(T[D],w[D],S[D]))}this.api.uploadMultiForHubot(E,I,N,y);break;case 6:var k=t[4],C=t[3],O=t[2];this.fileService.download(O,C,k)}},__class__:X});var Z=n["albero.command.FileAction"]={__ename__:["albero","command","FileAction"],__constructs__:["UPLOAD","UPLOAD_MULTI","DELETE","AUTH","UPLOAD_PATH","UPLOAD_MULTI_PATH","DOWNLOAD_PATH"]};Z.UPLOAD=function(e,t){var n=["UPLOAD",0,e,t];return n.__enum__=Z,n.toString=s,n},Z.UPLOAD_MULTI=function(e,t,n){var i=["UPLOAD_MULTI",1,e,t,n];return i.__enum__=Z,i.toString=s,i},Z.DELETE=function(e){var t=["DELETE",2,e];return t.__enum__=Z,t.toString=s,t},Z.AUTH=function(e,t,n,i,r){var a=["AUTH",3,e,t,n,i,r];return a.__enum__=Z,a.toString=s,a},Z.UPLOAD_PATH=function(e,t,n,i,r){var a=["UPLOAD_PATH",4,e,t,n,i,r];return a.__enum__=Z,a.toString=s,a},Z.UPLOAD_MULTI_PATH=function(e,t,n,i,r,a){var o=["UPLOAD_MULTI_PATH",5,e,t,n,i,r,a];return o.__enum__=Z,o.toString=s,o},Z.DOWNLOAD_PATH=function(e,t,n){var i=["DOWNLOAD_PATH",6,e,t,n];return i.__enum__=Z,i.toString=s,i},Z.__empty_constructs__=[];var te=function(){L.call(this)};(n["albero.command.LoadStampsetCommand"]=te).__name__=["albero","command","LoadStampsetCommand"],te.__super__=L,te.prototype=i(L.prototype,{execute:function(e){e.getBody();this.loadCommonStampset()},getOriginalStampset:function(t){var n=ie.getInstance(),e=n.get(t);if(null!=e)return e;var i=this.api.getStampsets([t]);return n.add(t,i),i.then(function(e){n.remove(t)},function(e){n.remove(t)}),i},getOriginalStamp:function(n){var i=this,e=this.stampsStore.getOriginalStamp(n.stampId);return null!=e?Promise.resolve(e):this.getOriginalStampset(n.stampsetId).then(function(e){var t=i.stampsStore.getOriginalStamp(n.stampId);return null==t?Promise.reject("stamp_not_found"):Promise.resolve(t)})},loadCommonStampset:function(){},__class__:te});var ne=n["albero.command.LoadStampsetAction"]={__ename__:["albero","command","LoadStampsetAction"],__constructs__:["COMMON"]};ne.COMMON=["COMMON",0],ne.COMMON.toString=s,(ne.COMMON.__enum__=ne).__empty_constructs__=[ne.COMMON];var ie=function(){this.loadings=new xa};(n["albero.command.StampsetLoadingPromises"]=ie).__name__=["albero","command","StampsetLoadingPromises"],ie.getInstance=function(){return null==ie.instance&&(ie.instance=new ie),ie.instance},ie.prototype={get:function(e){var t="_"+e.high+"_"+e.low,n=this.loadings;return null!=No[t]?n.getReserved(t):n.h[t]},add:function(e,t){var n="_"+e.high+"_"+e.low,i=this.loadings;null!=No[n]?i.setReserved(n,t):i.h[n]=t},remove:function(e){this.loadings.remove("_"+e.high+"_"+e.low)},__class__:ie};var re=function(){L.call(this)};(n["albero.command.ManageFriendsCommand"]=re).__name__=["albero","command","ManageFriendsCommand"],re.__super__=L,re.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t.action[1]){case 0:for(var n=0,i=t.users;n<i.length;){var r=i[n];++n,this.api.addFriend(r)}break;case 1:for(var a=0,o=t.users;a<o.length;){var s=o[a];++a,this.api.deleteFriend(s)}}},__class__:re});var ae=n["albero.command.ManageFriendsAction"]={__ename__:["albero","command","ManageFriendsAction"],__constructs__:["ADD","DELETE"]};ae.ADD=["ADD",0],ae.ADD.toString=s,(ae.ADD.__enum__=ae).DELETE=["DELETE",1],ae.DELETE.toString=s,(ae.DELETE.__enum__=ae).__empty_constructs__=[ae.ADD,ae.DELETE];var oe=function(){L.call(this)};(n["albero.command.MessageCommand"]=oe).__name__=["albero","command","MessageCommand"],oe.__super__=L,oe.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:var n=t[3],i=t[2];this.api.deleteMessage(i,n);break;case 1:var r=t[3],a=t[2];this.api.forwardMessages(a,r,0);break;case 2:var o=t[4],s=t[3],l=t[2];this.api.addFavoriteMessage(l,s,o);break;case 3:var u=t[3],c=t[2];this.api.deleteFavoriteMessage(c,u);break;case 4:var _=t[4],h=t[3],d=t[2];this.api.getFavoriteMessages(d,h,_)}},__class__:oe});var se=n["albero.command.MessageAction"]={__ename__:["albero","command","MessageAction"],__constructs__:["DELETE","FORWARD","ADD_FAVORITE","DELETE_FAVORITE","GET_FAVORITES"]};se.DELETE=function(e,t){var n=["DELETE",0,e,t];return n.__enum__=se,n.toString=s,n},se.FORWARD=function(e,t){var n=["FORWARD",1,e,t];return n.__enum__=se,n.toString=s,n},se.ADD_FAVORITE=function(e,t,n){var i=["ADD_FAVORITE",2,e,t,n];return i.__enum__=se,i.toString=s,i},se.DELETE_FAVORITE=function(e,t){var n=["DELETE_FAVORITE",3,e,t];return n.__enum__=se,n.toString=s,n},se.GET_FAVORITES=function(e,t,n){var i=["GET_FAVORITES",4,e,t,n];return i.__enum__=se,i.toString=s,i},se.__empty_constructs__=[];var le=function(){L.call(this)};(n["albero.command.NoteCommand"]=le).__name__=["albero","command","NoteCommand"],le.__super__=L,le.prototype=i(L.prototype,{execute:function(e){var t=this,n=e.getBody();switch(n[1]){case 0:var i=n[3],r=n[2];this.api.getNoteStatuses(r,i);break;case 1:var a=n[2];this.api.getNote(a);break;case 2:n[3];var o=n[2];cr.delayForReplicationLag().then(function(e){t.api.getNote(o)});break;case 3:var s=n[4],l=n[3],u=n[2];this.api.createNoteV2(u,l,s);break;case 4:var c=n[5],_=n[4],h=n[3],d=n[2],f=this.createNoteLocalEdit(d,h,c);this.api.createNoteV2(d,f,_);break;case 5:var m=n[4],p=n[3],g=n[2];this.api.updateNoteSetting(g,p,m);break;case 6:var v=n[5],y=n[4],S=n[3],w=n[2];this.api.updateNoteV2(w,S,y,v);break;case 7:var T=n[2];this.api.deleteNote(T);break;case 8:var I=n[2];this.dataStore.setNoteLocalEdit(I,null)}},createNoteLocalEdit:function(e,t,n){var i=Ti.createDummyId(),r=this.createNoteAttachmentFileInfoList(e,t.attachments);return new Ii(e,i,t.title,t.content,r,n)},createNoteAttachmentFileInfoList:function(e,t){for(var n=[],i=0;i<t.length;){var r=t[i];++i;var a=this.fileService.createDummyFile(r.path,r.name,r.type);n.push(this.fileInfoStore.createStagedFileInfoFromDummyFile(e,a,null))}return n},updateNote:function(e,t,n,i){return this.api.updateNoteV2(e,t,n,i)},lockNote:function(e,t){return this.api.lockNote(e,t)},unlockNote:function(e,t){return this.api.unlockNote(e,t)},__class__:le});var ue=n["albero.command.NoteAction"]={__ename__:["albero","command","NoteAction"],__constructs__:["GET_NOTE_STATUSES","GET_NOTE","GET_NOTE_ON_NOTIFY_UPDATE","CREATE_NOTE","CREATE_NOTE_FOR_HUBOT","UPDATE_NOTE_SETTING","UPDATE_NOTE","DELETE_NOTE","DELETE_NOTE_LOCAL_EDIT"]};ue.GET_NOTE_STATUSES=function(e,t){var n=["GET_NOTE_STATUSES",0,e,t];return n.__enum__=ue,n.toString=s,n},ue.GET_NOTE=function(e){var t=["GET_NOTE",1,e];return t.__enum__=ue,t.toString=s,t},ue.GET_NOTE_ON_NOTIFY_UPDATE=function(e,t){var n=["GET_NOTE_ON_NOTIFY_UPDATE",2,e,t];return n.__enum__=ue,n.toString=s,n},ue.CREATE_NOTE=function(e,t,n){var i=["CREATE_NOTE",3,e,t,n];return i.__enum__=ue,i.toString=s,i},ue.CREATE_NOTE_FOR_HUBOT=function(e,t,n,i){var r=["CREATE_NOTE_FOR_HUBOT",4,e,t,n,i];return r.__enum__=ue,r.toString=s,r},ue.UPDATE_NOTE_SETTING=function(e,t,n){var i=["UPDATE_NOTE_SETTING",5,e,t,n];return i.__enum__=ue,i.toString=s,i},ue.UPDATE_NOTE=function(e,t,n,i){var r=["UPDATE_NOTE",6,e,t,n,i];return r.__enum__=ue,r.toString=s,r},ue.DELETE_NOTE=function(e){var t=["DELETE_NOTE",7,e];return t.__enum__=ue,t.toString=s,t},ue.DELETE_NOTE_LOCAL_EDIT=function(e){var t=["DELETE_NOTE_LOCAL_EDIT",8,e];return t.__enum__=ue,t.toString=s,t},ue.__empty_constructs__=[];var ce=function(){L.call(this)};(n["albero.command.ReadCommand"]=ce).__name__=["albero","command","ReadCommand"],ce.__super__=L,ce.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:var n=t[3],i=t[2];this.readStatusUpdater.updateReadStatuses(i,n);break;case 1:var r=t[3],a=t[2];this.readStatusUpdater.updateAnnouncementReadStatus(a,r);break;case 2:var o=t[3],s=t[2];this.api.getReadStatus(s,o);break;case 3:var l=t[3],u=t[2];this.keywordWatcher.readKeywordDetection(u,null,l);break;case 4:var c=t[3],_=t[2];this.keywordWatcher.readKeywordDetection(null,_,c)}},__class__:ce});var _e=n["albero.command.ReadType"]={__ename__:["albero","command","ReadType"],__constructs__:["TALK","ANNOUNCEMENT","READ_STATUS","KEYWORD_IN_ANNOUNCEMENTS","KEYWORD_IN_MESSAGES"]};_e.TALK=function(e,t){var n=["TALK",0,e,t];return n.__enum__=_e,n.toString=s,n},_e.ANNOUNCEMENT=function(e,t){var n=["ANNOUNCEMENT",1,e,t];return n.__enum__=_e,n.toString=s,n},_e.READ_STATUS=function(e,t){var n=["READ_STATUS",2,e,t];return n.__enum__=_e,n.toString=s,n},_e.KEYWORD_IN_ANNOUNCEMENTS=function(e,t){var n=["KEYWORD_IN_ANNOUNCEMENTS",3,e,t];return n.__enum__=_e,n.toString=s,n},_e.KEYWORD_IN_MESSAGES=function(e,t){var n=["KEYWORD_IN_MESSAGES",4,e,t];return n.__enum__=_e,n.toString=s,n},_e.__empty_constructs__=[];var he=function(){L.call(this)};(n["albero.command.ReloadDataCommand"]=he).__name__=["albero","command","ReloadDataCommand"],he.__super__=L,he.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:this.api.getDomains();break;case 1:this.api.getFriends(),this.api.getAcquaintances();break;case 2:this.api.getTalks();break;case 3:var n=t[5],i=t[4],r=t[3],a=t[2];this.api.getMessages(a,r,i,n);break;case 4:var o=t[2];this.api.getAllUsers(o);break;case 5:var s=t[3],l=t[2];this.api.getUsers(l,s);break;case 6:var u=t[3],c=t[2];this.api.getProfile(c,u);break;case 7:var _=t[3],h=t[2];this.api.searchDomainUsers(h,_);break;case 8:var d=t[4],f=t[3],m=t[2];this.api.getAnnouncements(m,f,d);break;case 9:var p=t[5],g=t[4],v=t[3],y=t[2];this.api.getQuestions(y,v,g,p);break;case 10:var S=t[3],w=t[2];this.api.getQuestion(w,S);break;case 11:var T=t[3],I=t[2];this.api.getAttachments(I,T);break;case 12:var E=t[3],N=t[2];this.api.getSolutions(N,E);break;case 13:this.api.getMe();break;case 14:var A=t[2];this.api.getDepartmentTree(A);break;case 15:var b=t[3],D=t[2];this.api.getDepartmentUsers(D,b);break;case 16:var k=t[2];this.api.getDepartmentAllUsers(k);break;case 17:var C=t[3],O=t[2];this.api.getDepartmentUserCount(O,C)}},__class__:he});var de=n["albero.command.ReloadDataType"]={__ename__:["albero","command","ReloadDataType"],__constructs__:["Domains","Friends","Talks","Messages","AllUsers","GetUsers","GetProfile","SearchDomainUsers","Announcements","Questions","Question","Files","Solutions","Me","DepartmentTree","DepartmentUsers","DepartmentAllUsers","DepartmentUserCount"]};de.Domains=["Domains",0],de.Domains.toString=s,(de.Domains.__enum__=de).Friends=["Friends",1],de.Friends.toString=s,(de.Friends.__enum__=de).Talks=["Talks",2],de.Talks.toString=s,(de.Talks.__enum__=de).Messages=function(e,t,n,i){var r=["Messages",3,e,t,n,i];return r.__enum__=de,r.toString=s,r},de.AllUsers=function(e){var t=["AllUsers",4,e];return t.__enum__=de,t.toString=s,t},de.GetUsers=function(e,t){var n=["GetUsers",5,e,t];return n.__enum__=de,n.toString=s,n},de.GetProfile=function(e,t){var n=["GetProfile",6,e,t];return n.__enum__=de,n.toString=s,n},de.SearchDomainUsers=function(e,t){var n=["SearchDomainUsers",7,e,t];return n.__enum__=de,n.toString=s,n},de.Announcements=function(e,t,n){var i=["Announcements",8,e,t,n];return i.__enum__=de,i.toString=s,i},de.Questions=function(e,t,n,i){var r=["Questions",9,e,t,n,i];return r.__enum__=de,r.toString=s,r},de.Question=function(e,t){var n=["Question",10,e,t];return n.__enum__=de,n.toString=s,n},de.Files=function(e,t){var n=["Files",11,e,t];return n.__enum__=de,n.toString=s,n},de.Solutions=function(e,t){var n=["Solutions",12,e,t];return n.__enum__=de,n.toString=s,n},de.Me=["Me",13],de.Me.toString=s,(de.Me.__enum__=de).DepartmentTree=function(e){var t=["DepartmentTree",14,e];return t.__enum__=de,t.toString=s,t},de.DepartmentUsers=function(e,t){var n=["DepartmentUsers",15,e,t];return n.__enum__=de,n.toString=s,n},de.DepartmentAllUsers=function(e){var t=["DepartmentAllUsers",16,e];return t.__enum__=de,t.toString=s,t},de.DepartmentUserCount=function(e,t){var n=["DepartmentUserCount",17,e,t];return n.__enum__=de,n.toString=s,n},de.__empty_constructs__=[de.Domains,de.Friends,de.Talks,de.Me];var fe=function(){L.call(this)};(n["albero.command.SearchCommand"]=fe).__name__=["albero","command","SearchCommand"],fe.__super__=L,fe.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:var n=t[4],i=t[3],r=t[2];if(this.searchService.isSearching())return;switch(null==n&&this.searchService.saveParams(r),r.searchType[1]){case 0:this.api.searchMessages(r.copy(),i,n);break;case 1:this.api.searchAttachments(r.copy(),i,n)}break;case 1:this.searchService.clearEditingParams(),this.searchService.clearRecentParams(),this.searchService.clearSearching(),this.sendNotification("notify_search_clear",{})}},__class__:fe});var me=n["albero.command.SearchAction"]={__ename__:["albero","command","SearchAction"],__constructs__:["SEARCH","CLEAR"]};me.SEARCH=function(e,t,n){var i=["SEARCH",0,e,t,n];return i.__enum__=me,i.toString=s,i},me.CLEAR=["CLEAR",1],me.CLEAR.toString=s,(me.CLEAR.__enum__=me).__empty_constructs__=[me.CLEAR];var pe=function(){L.call(this)};(n["albero.command.SelectTalkCommand"]=pe).__name__=["albero","command","SelectTalkCommand"],pe.__super__=L,pe.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:var n=t[3],i=t[2],r=new On(i,Fn.NotSelected);this.sendNotification("Url",be.REDIRECT(r.createUrls(n,this.settings)));break;case 1:var a=t[4],o=t[3],s=t[2],l=new On(s,Fn.TalkSelected(o.id,Ra.Some(a)));this.sendNotification("Url",be.REDIRECT(l.createUrls(o.domainId,this.settings)));break;case 2:var u=t[3],c=t[2],_=new On(c,Fn.TalkSelected(u.id,Ra.None));this.sendNotification("Url",be.REDIRECT(_.createUrls(u.domainId,this.settings)));break;case 3:var h=t[3],d=t[2],f=new On(d,Fn.AnnouncementsSelected);this.sendNotification("Url",be.REDIRECT(f.createUrls(h,this.settings)));break;case 4:var m=t[4],p=t[3],g=t[2],v=this.getFallbackUrls(g,et.array(p));if(it.isEmpty(v)){var y=go(this,this.updateSelectionIfNeed),S=g,w=m;et.iter(p,function(e){y(S,w,e)})}}},updateSelectionIfNeed:function(e,t,n){if(t||!this.isSelectionParametersNotChanged(e,n)){var i=n.talkSelection;switch(i[1]){case 0:this.settings.clearSelectedTalk(n.paneType);break;case 1:var r=i[3],a=i[2];this.settings.selectTalk(n.paneType,e,a,r);break;case 2:this.settings.selectAnnouncement(n.paneType)}}},isSelectionParametersNotChanged:function(e,t){var n=this.settings.getSelectedDomainIdOnTalkSelectionChanged();return null!=e&&null!=n&&e.high==n.high&&e.low==n.low&&xn.eqTalkSelection(t.talkSelection,this.settings.getTalkSelection(e,t.paneType))},getFallbackUrls:function(e,t){var n=go(this,this.getValidTalkSelection),i=e,r=t.map(function(e){return n(i,e)});if(!et.exists(r,it.isEmpty))return Ra.None;var a=r.map(go(this,this.getOrNotSelected)),o=1==r.length?C.single(a[0]):C.multi(a);return Ra.Some(V.talks(e,o))},getOrNotSelected:function(e){switch(e[1]){case 0:return e[2];case 1:return Fn.NotSelected}},getValidTalkSelection:function(e,t){var n=t.talkSelection;switch(n[1]){case 0:break;case 1:n[3];var i,r=n[2],a=this.dataStore.getTalk(r);if(null!=a){var o=a.domainId;i=!(null!=o&&null!=e&&o.high==e.high&&o.low==e.low)}else i=!0;if(i)return Ra.None;break;case 2:var s=this.dataStore.getDomain(e),l=this.dataStore.getAnnouncementStatus(e);if(!Fe.hasAnnouncement(s,l))return Ra.None}return Ra.Some(t.talkSelection)},__class__:pe});var ge=n["albero.command.SelectTalkAction"]={__ename__:["albero","command","SelectTalkAction"],__constructs__:["SelectNone","SelectTalkAndMessage","SelectTalk","SelectAnnouncement","UpdateSelection"]};ge.SelectNone=function(e,t){var n=["SelectNone",0,e,t];return n.__enum__=ge,n.toString=s,n},ge.SelectTalkAndMessage=function(e,t,n){var i=["SelectTalkAndMessage",1,e,t,n];return i.__enum__=ge,i.toString=s,i},ge.SelectTalk=function(e,t){var n=["SelectTalk",2,e,t];return n.__enum__=ge,n.toString=s,n},ge.SelectAnnouncement=function(e,t){var n=["SelectAnnouncement",3,e,t];return n.__enum__=ge,n.toString=s,n},ge.UpdateSelection=function(e,t,n){var i=["UpdateSelection",4,e,t,n];return i.__enum__=ge,i.toString=s,i},ge.__empty_constructs__=[];var ve=function(){L.call(this)};(n["albero.command.SendCommand"]=ve).__name__=["albero","command","SendCommand"],ve.__super__=L,ve.prototype=i(L.prototype,{execute:function(e){var t,n=e.getBody();if(null!=n.id){var i=n.id;t="_"+i.high+"_"+i.low}else t=null;null!=n.talkId?this.api.createMessage(n.talkId,n.type,n.content,t):this.api.createAnnouncement(n.domainId,n.type,n.content,t)},__class__:ve});var ye=function(){L.call(this)};(n["albero.command.SignInCommand"]=ye).__name__=["albero","command","SignInCommand"],ye.__super__=L,ye.prototype=i(L.prototype,{execute:function(e){this.accessTokenResolver.asyncGetAccessToken(e.getBody(),go(mo=this.session,mo.start))},__class__:ye});var Se=function(){L.call(this)};(n["albero.command.SignOutCommand"]=Se).__name__=["albero","command","SignOutCommand"],Se.__super__=L,Se.prototype=i(L.prototype,{execute:function(e){this.api.deleteSession(),this.settings.clearInputTextForAll(),this.dataStore.clear(!0),Gi._e("["+$e.dateStr(new Date)+"] ","signout","","","",""),process.exit(1)},__class__:Se});var we=function(){L.call(this)};(n["albero.command.TalkCommand"]=we).__name__=["albero","command","TalkCommand"],we.__super__=L,we.prototype=i(L.prototype,{execute:function(e){var t=this,n=e.getBody();switch(n[1]){case 0:var i=n[4],r=n[3],a=n[2],o=this.dataStore.getValidPairTalk(r,a);null!=o?(this.sendNotification("SelectTalk",ge.SelectTalk(i,o)),this.sendNotification("open_existing_pair_talk_completed")):this.api.createPairTalk(a,r,i);break;case 1:var s=n[5],l=n[4],u=n[3],c=n[2];this.api.createGroupTalk(c,u,l,s);break;case 2:var _=n[4],h=n[3],d=n[2];this.api.addTalkers(d,h,_);break;case 3:var f=n[2],m=this.dataStore.me.id;this.api.deleteTalker(f,m);break;case 4:var p=n[3],g=n[2],v=this.dataStore.getTalk(g);null==p&&(p=this.dataStore.me.id),this.api.deleteTalker(v,p);break;case 5:var y=n[6],S=n[5],w=n[4],T=n[3],I=n[2];if(I.type!=bn.GroupTalk)return;null==y&&(y=Va.__cast(I,Nn).isSystemMessageVisibled()),this.prepareIconUrl(I.domainId,w,S,function(e){t.api.updateGroupTalk(I,T,e,y)});break;case 6:var E=n[6],N=n[5],A=n[4],b=n[3],D=n[2],k=this.dataStore.getTalk(D);if(k.type!=bn.GroupTalk)return;null==E&&(E=Va.__cast(k,Nn).isSystemMessageVisibled()),this.prepareIconUrl(k.domainId,A,N,function(e){t.api.updateGroupTalk(k,b,e,E)});break;case 7:var C=n[3],O=n[2];this.api.addFavoriteTalk(O,C);break;case 8:var M=n[3],R=n[2];this.api.deleteFavoriteTalk(R,M);break;case 9:var F=n[3],x=n[2];this.api.disablePushNotification(x,F);break;case 10:var U=n[3],P=n[2];this.api.enablePushNotification(P,U)}},prepareIconUrl:function(e,t,n,i){var r=this;null==n&&null!=t?this.api.uploadFile(t,e,Yn.TALK_ICON,function(e){i(e.get_url)},function(e){r.sendNotification("notify_update_group_talk_ERRORED")}):i(n)},__class__:we});var Te=n["albero.command.TalkAction"]={__ename__:["albero","command","TalkAction"],__constructs__:["OPEN_PAIR_TALK","OPEN_GROUP_TALK","ADD","DELETE","DELETE_FOR_HUBOT","UPDATE","UPDATE_FOR_HUBOT","ADD_FAVORITE","DELETE_FAVORITE","DISABLE_PUSH_NOTIFICATION","ENABLE_PUSH_NOTIFICATION"]};Te.OPEN_PAIR_TALK=function(e,t,n){var i=["OPEN_PAIR_TALK",0,e,t,n];return i.__enum__=Te,i.toString=s,i},Te.OPEN_GROUP_TALK=function(e,t,n,i){var r=["OPEN_GROUP_TALK",1,e,t,n,i];return r.__enum__=Te,r.toString=s,r},Te.ADD=function(e,t,n){var i=["ADD",2,e,t,n];return i.__enum__=Te,i.toString=s,i},Te.DELETE=function(e){var t=["DELETE",3,e];return t.__enum__=Te,t.toString=s,t},Te.DELETE_FOR_HUBOT=function(e,t){var n=["DELETE_FOR_HUBOT",4,e,t];return n.__enum__=Te,n.toString=s,n},Te.UPDATE=function(e,t,n,i,r){var a=["UPDATE",5,e,t,n,i,r];return a.__enum__=Te,a.toString=s,a},Te.UPDATE_FOR_HUBOT=function(e,t,n,i,r){var a=["UPDATE_FOR_HUBOT",6,e,t,n,i,r];return a.__enum__=Te,a.toString=s,a},Te.ADD_FAVORITE=function(e,t){var n=["ADD_FAVORITE",7,e,t];return n.__enum__=Te,n.toString=s,n},Te.DELETE_FAVORITE=function(e,t){var n=["DELETE_FAVORITE",8,e,t];return n.__enum__=Te,n.toString=s,n},Te.DISABLE_PUSH_NOTIFICATION=function(e,t){var n=["DISABLE_PUSH_NOTIFICATION",9,e,t];return n.__enum__=Te,n.toString=s,n},Te.ENABLE_PUSH_NOTIFICATION=function(e,t){var n=["ENABLE_PUSH_NOTIFICATION",10,e,t];return n.__enum__=Te,n.toString=s,n},Te.__empty_constructs__=[];var Ie=function(){L.call(this)};(n["albero.command.UpdateProfileCommand"]=Ie).__name__=["albero","command","UpdateProfileCommand"],Ie.__super__=L,Ie.prototype=i(L.prototype,{execute:function(e){var t=e.getBody().domainId,n=e.getBody().profileItemValues,i=e.getBody().copyToAllDomains,r=this.dataStore.getDomain(t);if(null!=r&&null!=r.profileDefinition.itemDefinitions){var a=[];if(i){for(var o=[],s=0;s<n.length;){var l=n[s];++s;var u=Vt.findById(r.profileDefinition.itemDefinitions,l.profileItemId);null!=u&&o.push({name:u.name,value:l.value})}for(var c=0,_=this.dataStore.getDomains();c<_.length;){var h=_[c];if(++c,!h.domainInfo.frozen){for(var d=[],f=0,m=h.profileDefinition.itemDefinitions;f<m.length;){var p=m[f];if(++f,p.visible&&!p.locked)for(var g=0;g<o.length;){var v=o[g];if(++g,v.name==p.name){var y=new qt;y.profileItemId=p.profileItemId,y.value=v.value,d.push(y);break}}}0<d.length&&a.push(new Qt(h.id,d))}}}else{for(var S=[],w=($e.iter(n),0);w<n.length;){var T=n[w];++w;var I=Vt.findById(r.profileDefinition.itemDefinitions,T.profileItemId);null!=I&&I.visible&&!I.locked&&S.push(T)}0<S.length&&a.push(new Qt(r.id,S))}0==a.length?this.sendNotification("update_profile_responsed",this.dataStore.me):this.api.updateProfile(a)}},__class__:Ie});var Ee=function(){L.call(this)};(n["albero.command.UpdateUserCommand"]=Ee).__name__=["albero","command","UpdateUserCommand"],Ee.__super__=L,Ee.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();if(null!=t.profileImage){var n=t.profileImage;if(!W.startsWith(n.type,"image/"))return}this.api.updateUser(t.displayName,t.profileImage,t.profileImageUrl,t.phoneticDisplayName,t.status)},__class__:Ee});var Ne=function(){L.call(this)};(n["albero.command.UpdateUserPresencesCommand"]=Ne).__name__=["albero","command","UpdateUserPresencesCommand"],Ne.__super__=L,Ne.prototype=i(L.prototype,{execute:function(e){var t=e.getBody().domainId,n=e.getBody().userIds;if(null!=t&&null!=n){var i=this.filterOnlyExpired(tt.unique(n));0!=i.length&&this.updateIfNeedPerSub(t,i)}},filterOnlyExpired:function(e){var n=this,i=I.nowAsInt64(),t=this.settings.getConfiguration().presenceExpiration,r=new Kn(t>>31,t);return e.filter(function(e){var t=it.map(n.userPresences.getUserPresence(e),function(e){return e.isExpired(i,r)});switch(t[1]){case 0:return t[2];case 1:return!0}})},updateIfNeedPerSub:function(n,e){for(var i=this,t=Promise.resolve([]),r=tt.splitUsingMaxCount(e,100),a=0;a<r.length;){var o=[r[a]];++a,t=t.then(function(t){return function(e){return i.api.getPresences(n,t[0])}}(o))}t.catch(function(e){})},__class__:Ne});var Ae=function(){L.call(this)};(n["albero.command.UrlCommand"]=Ae).__name__=["albero","command","UrlCommand"],Ae.__super__=L,Ae.prototype=i(L.prototype,{execute:function(e){var t=e.getBody();switch(t[1]){case 0:var n=t[2];this.routing.forward(n);break;case 1:var i=t[2];this.routing.redirect(i);break;case 2:this.routing.back()}},__class__:Ae});var be=n["albero.command.UrlAction"]={__ename__:["albero","command","UrlAction"],__constructs__:["FORWARD","REDIRECT","BACK"]};be.FORWARD=function(e){var t=["FORWARD",0,e];return t.__enum__=be,t.toString=s,t},be.REDIRECT=function(e){var t=["REDIRECT",1,e];return t.__enum__=be,t.toString=s,t},be.BACK=["BACK",2],be.BACK.toString=s,(be.BACK.__enum__=be).__empty_constructs__=[be.BACK];function De(e,t,n){this.email=e,this.pass=t,this.accessToken=n}(n["albero.entity.Account"]=De).__name__=["albero","entity","Account"],De.prototype={__class__:De};function rt(e){null!=e&&(this.id=e.id,this.group=new ke(e.group),this.profilePolicy=new Ce(e.profile_policy))}(n["albero.entity.AccountControlGroup"]=rt).__name__=["albero","entity","AccountControlGroup"],rt.prototype={isAllowedUpdateProfileImage:function(){return null==this.profilePolicy||this.profilePolicy.allowUpdateProfileImage},isAllowedUpdateDisplayName:function(){return null==this.profilePolicy||this.profilePolicy.allowUpdateDisplayName},__class__:rt};var ke=function(e){null!=e&&(this.name=e.name,this.alias=e.alias,this.ownerName=e.owner_name,this.version=e.version)};(n["albero.entity.AccountControlGroupGroup"]=ke).__name__=["albero","entity","AccountControlGroupGroup"],ke.prototype={__class__:ke};var Ce=function(e){null!=e&&(this.allowUpdateDisplayName=e.allow_update_display_name,this.allowUpdateProfileImage=e.allow_update_profile_image,this.version=e.version)};(n["albero.entity.AccountControlGroupProfilePolicy"]=Ce).__name__=["albero","entity","AccountControlGroupProfilePolicy"],Ce.prototype={__class__:Ce};function at(e){null!=e&&(this.id=e.id,null!=e.group&&(this.group=new ke(e.group)),null!=e.profile_policy&&(this.profilePolicy=new Ce(e.profile_policy)))}(n["albero.entity.AccountControlGroupPartialUpdate"]=at).__name__=["albero","entity","AccountControlGroupPartialUpdate"],at.prototype={__class__:at};function ot(e){null!=e&&(this.id=tt.fromIntOrInt64(e.id),this.groupName=e.group_name,this.groupOwnerName=e.group_owner_name,this.groupOwnerEmail=e.group_owner_email,this.hasDomainInvite=e.has_domain_invite,this.updatedAt=e.updated_at,this.version=e.version)}(n["albero.entity.AccountControlRequest"]=ot).__name__=["albero","entity","AccountControlRequest"],ot.prototype={__class__:ot};var Oe=n["albero.entity.AllowAttachmentTypeValue"]={__ename__:["albero","entity","AllowAttachmentTypeValue"],__constructs__:["ng","ok","image","imageOrVideo","imageOrVideoOrAudio","other"]};Oe.ng=["ng",0],Oe.ng.toString=s,(Oe.ng.__enum__=Oe).ok=["ok",1],Oe.ok.toString=s,(Oe.ok.__enum__=Oe).image=["image",2],Oe.image.toString=s,(Oe.image.__enum__=Oe).imageOrVideo=["imageOrVideo",3],Oe.imageOrVideo.toString=s,(Oe.imageOrVideo.__enum__=Oe).imageOrVideoOrAudio=["imageOrVideoOrAudio",4],Oe.imageOrVideoOrAudio.toString=s,(Oe.imageOrVideoOrAudio.__enum__=Oe).other=["other",5],Oe.other.toString=s,(Oe.other.__enum__=Oe).__empty_constructs__=[Oe.ng,Oe.ok,Oe.image,Oe.imageOrVideo,Oe.imageOrVideoOrAudio,Oe.other];function Me(e){this.value=e}(n["albero.entity.AllowAttachmentType"]=Me).__name__=["albero","entity","AllowAttachmentType"],Me.fromInt=function(e){if(null==e)return new Me(Oe.other);var t;if(null==e)t=Oe.other;else switch(e){case 0:t=Oe.ng;break;case 1:t=Oe.ok;break;case 2:t=Oe.image;break;case 3:t=Oe.imageOrVideo;break;case 4:t=Oe.imageOrVideoOrAudio;break;default:t=Oe.other}return new Me(t)},Me.fromValue=function(e){return new Me(e)},Me.createAttachmentErrorMessage=function(e,t,n){return null==n&&(n=""),0<e.compareStrongness(t)?e.createAttachmentErrorMessageByNetwork(n):t.createAttachmentErrorMessageByDomain(n)},Me.prototype={compareStrongness:function(e){return this.getStrongness()-e.getStrongness()},getStrongness:function(){switch(this.value[1]){case 0:return 40;case 2:return 30;case 3:return 20;case 4:return 10;case 1:case 5:return 0}},createAttachmentErrorMessageByDomain:function(e){switch(null==e&&(e=""),this.value[1]){case 0:return Yi.localize("AllowAttachmentType.ban_attach_file")+e;case 2:return Yi.localize("AllowAttachmentType.ban_attach_file_without_img")+e;case 3:return Yi.localize("AllowAttachmentType.ban_attach_file_without_img_movie")+e;case 4:return Yi.localize("AllowAttachmentType.ban_attach_file_without_img_movie_sound")+e;default:return""}},createAttachmentErrorMessageByNetwork:function(e){switch(null==e&&(e=""),this.value[1]){case 0:return Yi.localize("AllowAttachmentType.network_ban_attach_file")+e;case 2:return Yi.localize("AllowAttachmentType.network_ban_attach_file_without_img")+e;case 3:return Yi.localize("AllowAttachmentType.network_ban_attach_file_without_img_movie")+e;case 4:return Yi.localize("AllowAttachmentType.network_ban_attach_file_without_img_movie_sound")+e;default:return""}},createAttachmentFilter:function(){switch(this.value[1]){case 0:return function(e){return!1};case 2:return function(e){return new y("image.*","").match(e.type)};case 3:return function(e){return new y("image.*|video.*","").match(e.type)};case 4:return function(e){return new y("image.*|video.*|audio.*","").match(e.type)};default:return function(e){return!0}}},createDataTransferItemFilter:function(){switch(this.value[1]){case 0:return function(e){return!1};case 2:var t=new y("image.*","");return function(e){return t.match(e.type)};case 3:var n=new y("image.*|video.*","");return function(e){return n.match(e.type)};case 4:var i=new y("image.*|video.*|audio.*","");return function(e){return i.match(e.type)};default:return function(e){return!0}}},__class__:Me};function st(e){null!=e&&(this.id=e.announcement_id,this.domainId=e.domain_id,this.groupId=e.group_id,this.groupName=e.group_name,this.type=Ft.typeOf(e.type),this.content=e.content,this.userId=e.user_id,this.userName=e.user_name,this.createdAt=e.created_at)}(n["albero.entity.Announcement"]=st).__name__=["albero","entity","Announcement"],st.prototype={getDisplayTextWithoutEscape:function(){return Ft.getDisplayTextWithoutEscape(this.type,this.content)},getNotificatoinTextWithoutEscape:function(e){switch(null==e&&(e=this.userName),null==e&&(e=""),this.type[1]){case 1:case 7:return e+":"+this.getDisplayTextWithoutEscape();default:return Gi._e("["+$e.dateStr(new Date)+"] ","Unsupported announcement.type is detected. announcment:%o",this,"","",""),Ft.getUnsupportText()}},__class__:st};function Re(e){this.unreadCount=0,null!=e&&(this.domainId=e.domain_id,this.unreadCount=null!=e.unread_count?e.unread_count:0,this.maxAnnouncementId=e.max_announcement_id,null!=e.max_announcement&&(this.maxAnnouncement=new st(e.max_announcement)),this.maxReadAnnouncementId=e.max_read_announcement_id)}(n["albero.entity.AnnouncementStatus"]=Re).__name__=["albero","entity","AnnouncementStatus"],Re.prototype={updateReadWithStatusUpdate:function(e){var t=0,n=null;if(null!=e.readAnnouncementIds)for(var i=0,r=e.readAnnouncementIds;i<r.length;){var a,o=r[i];if(++i,null!=this.maxReadAnnouncementId){var s=this.maxReadAnnouncementId,l=o.high-s.high|0;l=0!=l?l:Sa.ucompare(o.low,s.low),a=0<(o.high<0?s.high<0?l:-1:0<=s.high?l:1)}else a=!0;if(a){var u;if(null!=n){var c=o.high-n.high|0;c=0!=c?c:Sa.ucompare(o.low,n.low),u=0<(o.high<0?n.high<0?c:-1:0<=n.high?c:1)}else u=!0;u&&(n=o),++t}}null!=n&&this.read(n,t)},updateByAnnouncementDeletion:function(e){var t,n=!1;if(this.isUnread(e)&&(this.unreadCount-=1,this.unreadCount<0&&(this.unreadCount=0),n=!0),null!=this.maxAnnouncementId){var i=this.maxAnnouncementId;t=null!=i&&null!=e&&i.high==e.high&&i.low==e.low}else t=!1;return t&&null!=this.maxAnnouncement&&(this.maxAnnouncement.type=xt.deleted,n=!(this.maxAnnouncement.content="")),n},updateByAnnouncement:function(e){this.isNewMax(e.id)&&(this.maxAnnouncementId=e.id,this.maxAnnouncement=e),this.unreadCount++},updateByReadingAnnouncements:function(e){if(null==e||this.canRegardAnnouncementReadCountZero(e)){if(!Fe.isUnreadAnnouncementExisted(this))return!1;if(null==this.maxAnnouncementId)return!1;this.readAll()}else{var t=e.filter(go(this,this.isUnread));if(0==t.length)return!1;this.read(t[t.length-1],t.length)}return!0},canRegardAnnouncementReadCountZero:function(e){var t=this.maxAnnouncementId,n=it.orNull(nt.lastOption(e));return null!=t&&null!=n&&t.high==n.high&&t.low==n.low},read:function(e,t){this.maxReadAnnouncementId=e,this.unreadCount-=t,this.unreadCount<0&&(this.unreadCount=0);var n=this.domainId,i=this.maxReadAnnouncementId,r=this.unreadCount;Gi._d("["+$e.dateStr(new Date)+"] ","Announcement status is updated. [domainId, maxReadAnnoundementId, unreadCount]:",n,i,r,"")},readAll:function(){this.maxReadAnnouncementId=this.maxAnnouncementId,this.unreadCount=0},isUnread:function(e){if(null==this.maxReadAnnouncementId)return!0;var t=this.maxReadAnnouncementId,n=t.high-e.high|0;return n=0!=n?n:Sa.ucompare(t.low,e.low),(t.high<0?e.high<0?n:-1:0<=e.high?n:1)<0},isMax:function(e){if(null==this.maxAnnouncementId)return!1;var t=this.maxAnnouncementId;return null!=t&&null!=e&&t.high==e.high&&t.low==e.low},isNewMax:function(e){if(null==this.maxAnnouncementId)return!0;var t=this.maxAnnouncementId,n=t.high-e.high|0;return n=0!=n?n:Sa.ucompare(t.low,e.low),(t.high<0?e.high<0?n:-1:0<=e.high?n:1)<0},__class__:Re};var Fe=function(){};(n["albero.entity.AnnouncementStatusHelper"]=Fe).__name__=["albero","entity","AnnouncementStatusHelper"],Fe.isUnreadAnnouncementExisted=function(e){return null!=e&&(null!=e.maxAnnouncement&&e.isUnread(e.maxAnnouncement.id))},Fe.hasAnnouncement=function(e,t){return!(null==e||!e.role.allowReadAnnouncements||null==t)&&null!=t.maxAnnouncementId};function lt(e){null!=e&&(this.domainId=e.domain_id,this.readAnnouncementIds=e.read_announcement_ids)}(n["albero.entity.AnnouncementStatusUpdate"]=lt).__name__=["albero","entity","AnnouncementStatusUpdate"],lt.prototype={__class__:lt};function xe(e){if(this.notificationInvisibleTalkSound=!0,this.notificationInvisibleTalkPopup=!1,this.notificationVisibleTalkSound=!1,this.notificationVisibleTalkPopup=!1,this.notificationIncludingMessageContent=!0,this.talkAutoScroll=1,this.keywordWatchingText="",this.keywordWatchingEmphasis=!1,this.keywordWatchingSelfMessage=!1,this.keywordWatchingActionReply=!1,this.userDataContainer=[],this.language="ja",this.conferenceIncomingSound=!0,null!=e){if(null!=e.notificationInvisibleTalkSound&&(this.notificationInvisibleTalkSound=e.notificationInvisibleTalkSound),null!=e.notificationInvisibleTalkPopup&&(this.notificationInvisibleTalkPopup=e.notificationInvisibleTalkPopup),null!=e.notificationVisibleTalkSound&&(this.notificationVisibleTalkSound=e.notificationVisibleTalkSound),null!=e.notificationVisibleTalkPopup&&(this.notificationVisibleTalkPopup=e.notificationVisibleTalkPopup),null!=e.notificationIncludingMessageContent&&(this.notificationIncludingMessageContent=e.notificationIncludingMessageContent),null!=e.notificationVisibleTalkAutoScroll&&(this.talkAutoScroll=e.notificationVisibleTalkAutoScroll?1:3),null!=e.talkAutoScroll&&(this.talkAutoScroll=e.talkAutoScroll),null!=e.keywordWatchingText&&(this.keywordWatchingText=e.keywordWatchingText),null!=e.keywordWatchingEmphasis&&(this.keywordWatchingEmphasis=e.keywordWatchingEmphasis),null!=e.keywordWatchingSelfMessage&&(this.keywordWatchingSelfMessage=e.keywordWatchingSelfMessage),null!=e.keywordWatchingActionReply&&(this.keywordWatchingActionReply=e.keywordWatchingActionReply),null!=e.userDataContainer)for(var t=0,n=Va.__cast(e.userDataContainer,Array);t<n.length;){var i=n[t];++t,this.userDataContainer.push(Ue.fromJson(i))}null!=e.language&&(this.language=e.language),null!=e.conferenceIncomingSound&&(this.conferenceIncomingSound=e.conferenceIncomingSound)}}(n["albero.entity.BrowserSettings"]=xe).__name__=["albero","entity","BrowserSettings"],xe.fromJson=function(e){return new xe(e)},xe.prototype={createCopy:function(){var e=new xe(null);return this.copyTo(e),e},equalNotificationSettings:function(e){return e.notificationInvisibleTalkSound==this.notificationInvisibleTalkSound&&e.notificationInvisibleTalkPopup==this.notificationInvisibleTalkPopup&&e.notificationVisibleTalkSound==this.notificationVisibleTalkSound&&e.notificationVisibleTalkPopup==this.notificationVisibleTalkPopup&&e.notificationIncludingMessageContent==this.notificationIncludingMessageContent},equalTalkSettings:function(e){return e.talkAutoScroll==this.talkAutoScroll},equalKeywordWatching:function(e){return e.keywordWatchingText==this.keywordWatchingText&&e.keywordWatchingEmphasis==this.keywordWatchingEmphasis&&e.keywordWatchingSelfMessage==this.keywordWatchingSelfMessage&&e.keywordWatchingActionReply==this.keywordWatchingActionReply},equalLanguageSettings:function(e){return e.language==this.language},equalConferenceSettings:function(e){return e.conferenceIncomingSound==this.conferenceIncomingSound},equalUserData:function(e,t){var n=e.getUserData(t),i=this.getUserData(t);if(null==n||null==n)return!0;var r=i.stampHistories.length;if(n.stampHistories.length!=r)return!0;for(var a=0,o=r;a<o;){var s=a++;if(!Pe.eq(n.stampHistories[s],i.stampHistories[s]))return!0}return!1},copyTo:function(e){this.copyNotificationSettingsTo(e),this.copyKeywordSettingsTo(e),this.copyTalkSettingsTo(e),this.copyUserDataContainerTo(e),this.copyLanguageSettingsTo(e),this.copyConferenceSettingsTo(e)},copyNotificationSettingsTo:function(e){e.notificationInvisibleTalkSound=this.notificationInvisibleTalkSound,e.notificationInvisibleTalkPopup=this.notificationInvisibleTalkPopup,e.notificationVisibleTalkSound=this.notificationVisibleTalkSound,e.notificationVisibleTalkPopup=this.notificationVisibleTalkPopup,e.notificationIncludingMessageContent=this.notificationIncludingMessageContent},copyKeywordSettingsTo:function(e){e.keywordWatchingText=this.keywordWatchingText,e.keywordWatchingEmphasis=this.keywordWatchingEmphasis,e.keywordWatchingSelfMessage=this.keywordWatchingSelfMessage,e.keywordWatchingActionReply=this.keywordWatchingActionReply},copyTalkSettingsTo:function(e){e.talkAutoScroll=this.talkAutoScroll},copyUserDataContainerTo:function(e){e.userDataContainer=this.userDataContainer},getUserData:function(t){return et.find(this.userDataContainer,function(e){return e.userIdString==t})},copyLanguageSettingsTo:function(e){e.language=this.language},copyConferenceSettingsTo:function(e){e.conferenceIncomingSound=this.conferenceIncomingSound},assureUserData:function(e){var t=this.getUserData(e);return null==t&&(t=Ue.fromUserIdString(e),this.userDataContainer.push(t)),t},isThumbnailExpansionEnabled:function(e){var t=this.getUserData(e);return null!=t&&t.useThumbnailExpansion},setThumbnailExpansionEnabled:function(e,t){this.assureUserData(e).useThumbnailExpansion=t},setPrevSelectedMic:function(e,t){var n=this.assureUserData(e);null==n.prevSelectedDevice?n.prevSelectedDevice={mic:t,speaker:"",camera:""}:n.prevSelectedDevice.mic=t},setPrevSelectedSpeaker:function(e,t){var n=this.assureUserData(e);null==n.prevSelectedDevice?n.prevSelectedDevice={mic:"",speaker:t,camera:""}:n.prevSelectedDevice.speaker=t},setPrevSelectedCamera:function(e,t){var n=this.assureUserData(e);null==n.prevSelectedDevice?n.prevSelectedDevice={mic:"",speaker:"",camera:t}:n.prevSelectedDevice.camera=t},getPrevSelectedDevice:function(e){var t=this.getUserData(e);return null==t||null==t.prevSelectedDevice?{mic:"",speaker:"",camera:""}:t.prevSelectedDevice},getStampHistories:function(e){var t=this.getUserData(e);return null==t?[]:t.stampHistories},addUsedStampJson:function(e,t){var n=this.assureUserData(e),i=n.stampHistories.filter(function(e){return!Pe.eq(t,e)});i.unshift(t),n.stampHistories=i.slice(0,Pe.MAX_SIZE)},isJaMode:function(){return null==this.language||"ja"==this.language},__class__:xe};var Ue=function(){};(n["albero.entity.UserData"]=Ue).__name__=["albero","entity","UserData"],Ue.fromUserIdString=function(e){var t=new Ue;return t.userIdString=e,t.stampHistories=[],t.useThumbnailExpansion=!1,t.prevSelectedDevice={mic:"",speaker:"",camera:""},t},Ue.fromJson=function(e){var t=new Ue;return null!=e&&(null!=e.userIdString&&(t.userIdString=e.userIdString),null!=e.stampHistories&&(t.stampHistories=e.stampHistories.map(Pe.migrate)),null!=e.useThumbnailExpansion&&(t.useThumbnailExpansion=e.useThumbnailExpansion),null!=e.prevSelectedDevice&&(t.prevSelectedDevice=e.prevSelectedDevice)),t},Ue.prototype={__class__:Ue};var Pe=function(){};(n["albero.entity.StampHisory"]=Pe).__name__=["albero","entity","StampHisory"],Pe.migrate=function(e){return"string"==typeof e?{commonStampId:e}:e},Pe.eq=function(e,t){return null==e||null==t?e!=t:null!=e.commonStampId&&null!=t.commonStampId?e.commonStampId==t.commonStampId:null!=e.originalStamp&&null!=t.originalStamp&&e.originalStamp.stampIdStr==t.originalStamp.stampIdStr};function ut(e){null!=e&&(this.userId=e.user_id,this.id=e.conference_id,this.domainId=e.domain_id,this.talkId=e.talk_id,this.messageId=e.message_id,this.createdAt=e.created_at,this.expiredAt=e.expired_at,this.participants=e.participants)}(n["albero.entity.Conference"]=ut).__name__=["albero","entity","Conference"],ut.prototype={isIncomingExpired:function(){var e=this.createdAt,t=4294967296,n=e.high,i=e.low;return n*t+(0<=i?i:i+t)+ut.INCOMING_TIME<(new Date).getTime()},isExpired:function(){var e=this.expiredAt,t=4294967296,n=e.high,i=e.low;return n*t+(0<=i?i:i+t)<(new Date).getTime()},__class__:ut};var Le=function(e){null!=e&&(this.maxFriends=e.max_friends,this.maxTalks=e.max_talks,this.maxTalkers=e.max_talkers,this.maxMessageContentLength=e.max_message_content_length,this.botExpiredVersion=e.bot_expired_version,this.presenceExpiration=null!=e.presence_expiration?e.presence_expiration:Le.DEFAULT_PRESENCE_EXPIRATION,this.allowAttachmentType=Me.fromInt(e.allow_attachment_type),this.imageSanitizationEnabled=!!e.image_sanitization_enabled)};(n["albero.entity.Configuration"]=Le).__name__=["albero","entity","Configuration"],Le.prototype={__class__:Le};function Be(e){this.contractConference=Ra.None,null!=e&&(this.id=e.contract_id,this.plan=new zt(e.plan),this.quota=new rn(e.quota),this.solutionIds=e.solution_ids,null!=e.conference&&(this.contractConference=Ra.Some(new He(e.conference))))}(n["albero.entity.Contract"]=Be).__name__=["albero","entity","Contract"],Be.prototype={getMaxMessageContentLength:function(){return it.map(it.option(this.quota),function(e){return e.maxMessageContentLength})},getMaxTalkers:function(){return it.flatMap(it.option(this.quota),function(e){return it.option(e.maxTalkers)})},getMaxTalks:function(){return it.flatMap(it.option(this.quota),function(e){return it.option(e.maxTalks)})},isConferenceEnalbed:function(){return it.isDefined(this.contractConference)},isVideoEnalbed:function(){var e=it.map(this.contractConference,function(e){return e.videoEnabled});switch(e[1]){case 0:return e[2];case 1:return!1}},getConferenceTtl:function(){return it.map(this.contractConference,function(e){return e.ttl})},getConferenceMaxParticipants:function(){return it.map(this.contractConference,function(e){return e.maxConferenceParticipants})},isGroupConfenreceEnalbed:function(){var e=it.map(this.contractConference,function(e){return e.groupConferenceEnabled});switch(e[1]){case 0:return e[2];case 1:return!1}},isTargetOfPlanAd:function(){return null!=this.quota&&this.quota.withAd},isFreePlan:function(){return null!=this.plan&&this.plan.free},__class__:Be};var He=function(e){this.groupConferenceEnabled=!1,this.maxConferenceParticipants=He.DEFAULT_MAX_PARTICIPANTS,this.ttl=He.DEFAULT_TTL,this.videoEnabled=!1,null!=e&&(this.videoEnabled=e.video_enabled,this.ttl=e.ttl,this.maxConferenceParticipants=e.max_conference_participants,this.groupConferenceEnabled=e.group_conference_enabled)};(n["albero.entity.ContractConference"]=He).__name__=["albero","entity","ContractConference"],He.prototype={__class__:He};var je=function(e){if(null!=e){switch(this.id=e.department_id,this.order=e.order,this.parentId=e.parent,this.nodeType=null==e.node?Ge.Normal:this.parseDepartmentNodeType(e.node),this.nodeType[1]){case 0:this.name=e.name;break;case 1:this.name=je.getLabelRoot();break;case 2:this.name=je.getLabelFree()}this.depth=0,this.childrenIds=null,this.userCount=null,this.userIds=null,this.userCountLoading=!1}};(n["albero.entity.Department"]=je).__name__=["albero","entity","Department"],je.getLabelFree=function(){return Yi.localize("Department.label_free")},je.getLabelRoot=function(){return Yi.localize("Department.label_root")},je.prototype={addChild:function(e){null==this.childrenIds&&(this.childrenIds=[]),this.childrenIds.push(e)},isRoot:function(){return this.nodeType==Ge.Root},isFree:function(){return this.nodeType==Ge.Free},parseDepartmentNodeType:function(e){switch(e){case 1:return Ge.Root;case 2:return Ge.Free;default:return Ge.Normal}},__class__:je};function Ye(){}(n["albero.entity.DepartmentHelper"]=Ye).__name__=["albero","entity","DepartmentHelper"],Ye.getName=function(e){return null==e?null:e.name};var Ge=n["albero.entity.DepartmentNodeType"]={__ename__:["albero","entity","DepartmentNodeType"],__constructs__:["Normal","Root","Free"]};Ge.Normal=["Normal",0],Ge.Normal.toString=s,(Ge.Normal.__enum__=Ge).Root=["Root",1],Ge.Root.toString=s,(Ge.Root.__enum__=Ge).Free=["Free",2],Ge.Free.toString=s,(Ge.Free.__enum__=Ge).__empty_constructs__=[Ge.Normal,Ge.Root,Ge.Free];function ze(e){null!=e&&(this.domainId=e.domain_id,this.departments=this.getDepartments(e.departments))}(n["albero.entity.DepartmentList"]=ze).__name__=["albero","entity","DepartmentList"],ze.prototype={getDepartments:function(e){return null==e?[]:e.map(function(e){return new je(e)})},__class__:ze};function Ke(e){null!=e&&(this.departmentId=e.department_id,this.all=e.all,this.partial=e.partial)}(n["albero.entity.DepartmentUserCount"]=Ke).__name__=["albero","entity","DepartmentUserCount"],Ke.prototype={__class__:Ke};function We(e){null!=e&&(this.departments=this.getDepartmentUserCounts(e.departments))}(n["albero.entity.DepartmentUserCountList"]=We).__name__=["albero","entity","DepartmentUserCountList"],We.prototype={getDepartmentUserCounts:function(e){return null==e?[]:e.map(function(e){return new Ke(e)})},__class__:We};function ct(e){null!=e&&(this.id=e.domain_id,this.updatedAt=e.updated_at,this.domainInfo=new Ve(e.domain),this.contract=new Be(e.contract),this.profileDefinition=new Wt(e.profile_definition),this.setting=new qe(e.setting),this.role=new Je(e.role),this.stampsetSetting=new Tn(e.stampset_setting),this.closed=!1)}(n["albero.entity.Domain"]=ct).__name__=["albero","entity","Domain"],ct.isChangedContractTreeEnabled=function(e,t){return ct.isDepartmentEnabled(e)!=ct.isDepartmentEnabled(t)},ct.isDepartmentEnabled=function(e){return null!=e&&(!!ct.isAllowListUser(e)&&!!e.setting.contactTreeEnabled)},ct.isAllowListUser=function(e){return null==e||e.role.allowListUsers},ct.isChangedRoleType=function(e,t){return(null==e?Xe.user:e.role.type)!=(null==t?Xe.user:t.role.type)},ct.isChangedMaxTalkers=function(e,t){var n,i,r=it.flatMap(it.option(e),function(e){return e.getMaxTalkers()});switch(r[1]){case 0:n=r[2];break;case 1:n=0}var a=it.flatMap(it.option(t),function(e){return e.getMaxTalkers()});switch(a[1]){case 0:i=a[2];break;case 1:i=0}return n!=i},ct.isAllowReadAnnouncement=function(e){return null!=e&&!!e.role.allowReadAnnouncements},ct.isSolutionChanged=function(e,t){var n=ct.getSolutionIds(e),i=ct.getSolutionIds(t);if(null==n&&null==i)return!1;if(null==n||null==i)return!0;if(n.length!=i.length)return!0;for(var r=0,a=n.length;r<a;){var o=r++;if(n[o]!=i[o])return!0}return!1},ct.getSolutionIds=function(e){return null==e||null==e.contract?null:e.contract.solutionIds},ct.isForwardTypeChanged=function(e,t){return null==e||e.setting.allowForwardMessageType!=t.setting.allowForwardMessageType},ct.isSaveAllowedChanged=function(e,t,n){return(null==e||e.isSaveAllowed(n))!=(null==t||t.isSaveAllowed(n))},ct.prototype={getMaxMessageContentLengthOrElse:function(e){var t=it.flatMap(it.option(this.contract),function(e){return e.getMaxMessageContentLength()});switch(t[1]){case 0:return t[2];case 1:return e}},getMaxTalkers:function(){return it.flatMap(it.option(this.contract),function(e){return e.getMaxTalkers()})},getMaxTalks:function(){return it.flatMap(it.option(this.contract),function(e){return e.getMaxTalks()})},isSaveAllowed:function(e){return e?this.setting.allowSaveAttachments.desktop:this.setting.allowSaveAttachments.web},isFreePlan:function(){return null!=this.contract&&this.contract.isFreePlan()},isTargetOfPlanAd:function(){return null!=this.contract&&this.contract.isTargetOfPlanAd()},isMyOwnDomain:function(){return this.role.isOwner()},updateStampsetSetting:function(e){e.isNewerThan(this.stampsetSetting)&&(this.stampsetSetting=e)},updateStampsetInfo:function(e){this.stampsetSetting.updateStampsetInfo(e)},deleteStampsetInfo:function(e){this.stampsetSetting.deleteStampsetInfo(e)},__class__:ct};var Ve=function(e){null!=e&&(this.name=e.domain_name,this.logoUrl=e.logo_url,this.frozen=e.frozen)};(n["albero.entity.DomainInfo"]=Ve).__name__=["albero","entity","DomainInfo"],Ve.prototype={__class__:Ve};var qe=function(e){null!=e&&(this.allowAttachmentType=Me.fromInt(e.allow_attachment_type),this.allowSaveAttachmentsToDevice=e.allow_save_attachments_to_device,null!=e.allow_save_attachments&&(this.allowSaveAttachments=new Qe(e.allow_save_attachments)),this.allowForwardMessageType=this.allowForwardMessageTypeOf(e.allow_forward_message_type),this.contactTreeEnabled=!!e.contact_tree_enabled,this.dropboxIntegrationEnabled=!!e.dropbox_integration_enabled,this.boxIntegrationEnabled=!!e.box_integration_enabled)};(n["albero.entity.DomainSetting"]=qe).__name__=["albero","entity","DomainSetting"],qe.prototype={allowForwardMessageTypeOf:function(e){switch(e){case 0:return Ze.ng;case 1:return Ze.ok;case 2:return Ze.onlyTextOrStamp;default:return Ze.other}},__class__:qe};var Qe=function(e){null!=e&&(this.web=null==e.web||e.web,this.ios=null==e.ios||e.ios,this.android=null==e.android||e.android,this.desktop=null==e.desktop||e.desktop)};(n["albero.entity.DomainSettingAllowSaveAttachments"]=Qe).__name__=["albero","entity","DomainSettingAllowSaveAttachments"],Qe.prototype={__class__:Qe};var Je=function(e){if(null!=e){this.type=this.typeOf(e.type);var t=e.allow_guests;this.allowGuests=t||!0;var n=e.allow_create_attachments;this.allowCreateAttachments=n||!0;var i=e.allow_read_attachments;this.allowReadAttachments=i||!0;var r=e.allow_create_announcement;this.allowCreateAnnouncement=r&&r,this.allowReadAnnouncements=e.allow_read_announcements,null==this.allowReadAnnouncements&&(this.allowReadAnnouncements=!0),this.allowListUsers=e.allow_list_users,null==this.allowListUsers&&(this.allowListUsers=!0)}};(n["albero.entity.DomainRole"]=Je).__name__=["albero","entity","DomainRole"],Je.prototype={def:function(e,t){return e||t},typeOf:function(e){switch(e){case 10:return Xe.owner;case 20:return Xe.manager;case 30:return Xe.user;default:return Xe.guest}},isOwner:function(){return ee.enumEq(this.type,Xe.owner)},__class__:Je};var Xe=n["albero.entity.DomainRoleType"]={__ename__:["albero","entity","DomainRoleType"],__constructs__:["owner","manager","user","guest"]};Xe.owner=["owner",0],Xe.owner.toString=s,(Xe.owner.__enum__=Xe).manager=["manager",1],Xe.manager.toString=s,(Xe.manager.__enum__=Xe).user=["user",2],Xe.user.toString=s,(Xe.user.__enum__=Xe).guest=["guest",3],Xe.guest.toString=s,(Xe.guest.__enum__=Xe).__empty_constructs__=[Xe.owner,Xe.manager,Xe.user,Xe.guest];var Ze=n["albero.entity.DomainAllowForwardMessageType"]={__ename__:["albero","entity","DomainAllowForwardMessageType"],__constructs__:["ng","ok","onlyTextOrStamp","other"]};Ze.ng=["ng",0],Ze.ng.toString=s,(Ze.ng.__enum__=Ze).ok=["ok",1],Ze.ok.toString=s,(Ze.ok.__enum__=Ze).onlyTextOrStamp=["onlyTextOrStamp",2],Ze.onlyTextOrStamp.toString=s,(Ze.onlyTextOrStamp.__enum__=Ze).other=["other",3],Ze.other.toString=s,(Ze.other.__enum__=Ze).__empty_constructs__=[Ze.ng,Ze.ok,Ze.onlyTextOrStamp,Ze.other];function _t(e){null!=e&&(this.domainId=e.domain_id,this.departments=e.departments)}(n["albero.entity.DomainDepartmentPath"]=_t).__name__=["albero","entity","DomainDepartmentPath"],_t.prototype={__class__:_t};function ht(e){null!=e&&(this.id=e.domain_id,this.name=e.domain_name,this.accountControlRequestId=tt.fromIntOrInt64(e.account_control_request_id),this.updatedAt=e.updated_at)}(n["albero.entity.DomainInvite"]=ht).__name__=["albero","entity","DomainInvite"],ht.prototype={__class__:ht};function dt(e){null!=e&&(this.id=e.user_id,this.status=e.status,this.displayName=e.display_name,this.canonicalDisplayName=e.canonical_display_name,this.phoneticDisplayName=e.phonetic_display_name,this.canonicalPhoneticDisplayName=e.canonical_phonetic_display_name,this.profileImageUrl=e.profile_image_url,this.updatedAt=e.updated_at)}(n["albero.entity.User"]=dt).__name__=["albero","entity","User"],dt.prototype={__class__:dt};function ft(e){dt.call(this,e),null!=e&&(this.domainId=e.domain_id,null!=e.profile_contact&&(this.profileContact=Va.__cast(e.profile_contact,Array).map(function(e){return new qt(e)})),this.departments=e.departments)}(n["albero.entity.DomainUser"]=ft).__name__=["albero","entity","DomainUser"],ft.__super__=dt,ft.prototype=i(dt.prototype,{match:function(e,t){if(this.matchNameOrPhonetic(e))return!0;if(null!=this.profileContact&&null!=t.profileDefinition.itemDefinitions)for(var n=0,i=this.profileContact;n<i.length;){var r=i[n];++n;for(var a=0,o=t.profileDefinition.itemDefinitions;a<o.length;){var s=o[a];if(++a,s.profileItemId==r.profileItemId){if(s.visible&&10==s.group&&-1<r.canonicalValue.indexOf(e))return!0;break}}}return!1},matchNameOrPhonetic:function(e){if(k.isEmpty(e))return!0;if(k.isEmpty(this.canonicalDisplayName)){this.canonicalDisplayName=Qi.canonicalize(this.displayName);var t=this.canonicalDisplayName,n=this.displayName;Gi._d("["+$e.dateStr(new Date)+"] ","create canonical display name from %s to %s.",t,n,"","")}return-1<this.canonicalDisplayName.indexOf(e)||null!=this.canonicalPhoneticDisplayName&&-1<this.canonicalPhoneticDisplayName.indexOf(e)},matchNameOrPhoneticRoman:function(e){if(this.matchNameOrPhonetic(e))return!0;if(k.isEmpty(this.canonicalDisplayNameRoman)){this.canonicalDisplayNameRoman=Qi.canonicalizeForRoman(this.displayName);var t=this.canonicalDisplayNameRoman,n=this.displayName;Gi._d("["+$e.dateStr(new Date)+"] ","create canonical display name(roman) from %s to %s.",t,n,"","")}return-1<this.canonicalDisplayNameRoman.indexOf(e)||null!=this.canonicalPhoneticDisplayName&&(k.isEmpty(this.canonicalPhoneticDisplayNameRoman)&&(this.canonicalPhoneticDisplayNameRoman=Qi.canonicalizeForRoman(this.canonicalPhoneticDisplayName)),-1<this.canonicalPhoneticDisplayNameRoman.indexOf(e))},__class__:ft});function mt(e){this.values=e}(n["albero.entity.Domains"]=mt).__name__=["albero","entity","Domains"],mt.prototype={orderByName:function(){var e=nt.sortAndReturn(this.values.map(pt.fromDomain),pt.compare).map(pt.toDomain);return new mt(e)},getOldestDomain:function(){return null==this.values||0==this.values.length?Ra.None:et.fold(this.values,function(r,e){switch(it.filter(e,function(e){var t=e.id,n=r.id,i=t.high-n.high|0;return i=0!=i?i:Sa.ucompare(t.low,n.low),(t.high<0?n.high<0?i:-1:0<=n.high?i:1)<=0})[1]){case 0:return it.filter(e,function(e){var t=e.id,n=r.id,i=t.high-n.high|0;return i=0!=i?i:Sa.ucompare(t.low,n.low),(t.high<0?n.high<0?i:-1:0<=n.high?i:1)<=0});case 1:return Ra.Some(r)}},Ra.None)},__class__:mt};var pt=function(e){this.domain=e,this.name=e.domainInfo.name,this.canonicalizedName=Qi.canonicalize(this.name)};(n["albero.entity.DomainForSort"]=pt).__name__=["albero","entity","DomainForSort"],pt.fromDomain=function(e){return new pt(e)},pt.toDomain=function(e){return e.domain},pt.compare=function(e,t){var n=k.compare(e.canonicalizedName,t.canonicalizedName);return 0!=n?n:k.compare(e.name,t.name)},pt.prototype={__class__:pt};function gt(e){null!=e&&(this.fileId=e.file_id,this.url=e.get_url,this.headers=new vt(e.get_headers))}(n["albero.entity.DownloadAuth"]=gt).__name__=["albero","entity","DownloadAuth"],gt.prototype={__class__:gt};var vt=function(e){this.rawData=e};(n["albero.entity.DownloadAuthHeaders"]=vt).__name__=["albero","entity","DownloadAuthHeaders"],vt.prototype={__class__:vt};function yt(e){null!=e&&(this.domainId=e.domain_id,this.talkId=e.talk_id,this.orderInFavorites=e.order_in_favorites,this.favoriteVersion=e.favorite_version)}(n["albero.entity.FavoriteTalkEvent"]=yt).__name__=["albero","entity","FavoriteTalkEvent"],yt.prototype={__class__:yt};function St(e){this.uploadResult=wt.NONE,this.thumbnailDimension=Ra.None,null!=e&&(this.attachmentId=e.attachment_id,this.messageId=e.message_id,this.talkId=e.talk_id,this.id=e.file_id,this.userId=e.user_id,this.name=e.name,this.contentType=e.content_type,this.contentSize=e.content_size,this.url=e.url,this.thumbUrl=e.thumbnail_url,this.updatedAt=e.updated_at,this.file=e.file,this.localThumbInfo=e.localThumbInfo,this.thumbnailDimension=Ra.None,this.deleted=null!=e.deleted&&e.deleted)}(n["albero.entity.FileInfo"]=St).__name__=["albero","entity","FileInfo"],St.fromMessageAndFile=function(e,t){var n=new St;return n.messageId=e.id,n.talkId=e.talkId,n.userId=e.userId,n.updatedAt=e.createdAt,n.id=t.file_id,n.name=t.name,n.contentType=t.content_type,n.contentSize=t.content_size,n.url=t.url,n.thumbUrl=t.thumbnail_url,n.thumbnailDimension=null==t.thumbnail_dimension?Ra.None:Ra.Some(new Hn(t.thumbnail_dimension)),n.deleted=null!=t.deleted&&t.deleted,n.file=t.file,n.localThumbInfo=t.localThumbInfo,n},St.fromMessageAndFileWithFileId=function(e,t,n){var i=St.fromMessageAndFile(e,t);return i.id=n,i},St.prototype={isRemote:function(){return null==this.file},isUploaded:function(){if(this.isRemote())return!0;switch(this.uploadResult[1]){case 0:return!0;case 1:case 2:return!1}},isUploadFailed:function(){if(this.isRemote())return!1;switch(this.uploadResult[1]){case 1:return!0;case 0:case 2:return!1}},setUploadResult:function(e){this.uploadResult=e},isNotUploaded:function(){return!this.isUploaded()},hasThumb:function(){return null!=this.thumbUrl||this.hasLocalThumbInfo()},hasLocalThumbInfo:function(){return null!=this.localThumbInfo},hasLocalFile:function(){return null!=this.file},hasUrl:function(){return null!=this.url},isImage:function(){return W.startsWith(this.contentType,"image/")},isImageGif:function(){return W.startsWith(this.contentType,"image/gif")},isImageJpeg:function(){return W.startsWith(this.contentType,"image/jpeg")},isPdf:function(){return W.startsWith(this.contentType,"application/pdf")},isVideo:function(){return W.startsWith(this.contentType,"video/")},canDisplayAsThumb:function(){return!!this.hasThumb()||this.isImage()},getNoThumbText:function(){return null!=this.name?this.name:this.url},getUploadedFileData:function(){if(null==this.file){var e={url:this.url,content_type:this.contentType,content_size:this.contentSize,name:this.name,file_id:this.id};return null!=this.thumbUrl&&(e.thumbnail_url=this.thumbUrl),it.isDefined(this.thumbnailDimension)&&(e.thumbnail_dimension=it.get(this.thumbnailDimension)),e}var t=this.uploadResult;switch(t[1]){case 0:return t[2];case 1:case 2:return Gi._e("["+$e.dateStr(new Date)+"] ","file not uploaded.","","","",""),null}},addLocalFile:function(e){this.file=e},addLocalThumbInfo:function(e){this.localThumbInfo=e},getUploadableFilePack:function(){return{file:this.file,thumb:this.localThumbInfo}},__class__:St};var wt=n["albero.entity.UploadResult"]={__ename__:["albero","entity","UploadResult"],__constructs__:["SUCCESS","FAILUER","NONE"]};wt.SUCCESS=function(e){var t=["SUCCESS",0,e];return t.__enum__=wt,t.toString=s,t},wt.FAILUER=["FAILUER",1],wt.FAILUER.toString=s,(wt.FAILUER.__enum__=wt).NONE=["NONE",2],wt.NONE.toString=s,(wt.NONE.__enum__=wt).__empty_constructs__=[wt.FAILUER,wt.NONE];function Tt(e){null!=e&&(this.messageId=e[0],this.talkId=e[1],this.fileId=e[2])}(n["albero.entity.FileInfoDeletion"]=Tt).__name__=["albero","entity","FileInfoDeletion"],Tt.prototype={__class__:Tt};function It(e){null!=e&&(this.domainId=e.domain_id,this.show=e.show,this.version=e.version)}(n["albero.entity.FlowNotificationBadge"]=It).__name__=["albero","entity","FlowNotificationBadge"],It.prototype={__class__:It};function Et(){}(n["albero.entity.FlowNotificationBadgeStore"]=Et).__name__=["albero","entity","FlowNotificationBadgeStore"],Et.prototype={clear:function(){this.badgeMap=new xa},setBadge:function(e,t){null==this.badgeMap&&(this.badgeMap=new xa);var n="_"+e.high+"_"+e.low,i=this.badgeMap;null!=No[n]?i.setReserved(n,t):i.h[n]=t},getBadge:function(e){if(null==this.badgeMap)return null;var t="_"+e.high+"_"+e.low,n=this.badgeMap;return null!=No[t]?n.getReserved(t):n.h[t]},removeBadge:function(e){if(null!=this.badgeMap){var t="_"+e.high+"_"+e.low;this.badgeMap.remove(t)}},isBadgeShownForDomains:function(e){if(null==this.badgeMap)return!1;for(var t=null==e?null:"_"+e.high+"_"+e.low,n=this.badgeMap.keys();n.hasNext();){var i=n.next();if(i!=t&&this.isBadgeShown(i))return!0}return!1},isBadgeShownForOneDomain:function(e){return null!=e&&this.isBadgeShown("_"+e.high+"_"+e.low)},isBadgeShown:function(e){if(null==this.badgeMap)return!1;var t=this.badgeMap,n=null!=No[e]?t.getReserved(e):t.h[e];return null!=n&&n.show},__class__:Et};function Nt(e){null!=e&&(this.talkId=e.talk_id,null!=e.messages&&(this.messages=Va.__cast(e.messages,Array).map(function(e){return new At(e)})))}(n["albero.entity.HitContext"]=Nt).__name__=["albero","entity","HitContext"],Nt.prototype={findHitMessage:function(n){return et.find(this.messages,function(e){var t=e.id;return null!=t&&null!=n&&t.high==n.high&&t.low==n.low})},__class__:Nt};var At=function(e){null!=e&&(this.id=e.message_id,this.talkId=e.talk_id,this.userId=e.user_id,this.type=Ft.typeOf(e.type),this.content=e.content,this.createdAt=e.created_at,this.hit=e.hit)};(n["albero.entity.HitMessage"]=At).__name__=["albero","entity","HitMessage"],At.prototype={__class__:At};function bt(){}(n["albero.entity.IdSpec"]=bt).__name__=["albero","entity","IdSpec"],bt.timestamp=function(e){var t=bt.TIMESTAMP_SHIFT;return 0!=(t&=63)?t<32?new Kn(e.high>>t,e.high<<32-t|e.low>>>t):new Kn(e.high>>31,e.high>>t-32):new Kn(e.high,e.low)},bt.subTimestampPart=function(e,t){var n=bt.timestamp(e),i=bt.timestamp(t),r=n.high-i.high|0,a=n.low-i.low|0;if(Sa.ucompare(n.low,i.low)<0){r--;r|=0}return new Kn(r,a)},bt.createForTest=function(e){var t=bt.TIMESTAMP_SHIFT;return 0!=(t&=63)?t<32?new Kn(e.high<<t|e.low>>>32-t,e.low<<t):new Kn(e.low<<t-32,0):new Kn(e.high,e.low)};function Dt(){}(n["albero.entity.IdValue"]=Dt).__name__=["albero","entity","IdValue"],Dt.prototype={__class__:Dt};function kt(e){null!=e&&(this.conferenceId=e.conference_id,this.roomName=e.room_name,this.credential=e.credential,this.mode=this.parseMode(e.mode),this.timestamp=e.timestamp)}(n["albero.entity.JoinConference"]=kt).__name__=["albero","entity","JoinConference"],kt.prototype={parseMode:function(e){return"sfu"==e?Ct.sfu:"fullMesh"==e?Ct.fullMesh:Ct.unknown},isSfu:function(e){switch(this.mode[1]){case 0:return!0;case 1:return!1;case 2:return e.type==bn.GroupTalk}},getEllaspedSecOnJoin:function(){var e=tt.fromIntOrInt64(this.credential.timestamp),t=tt.fromIntOrInt64(this.timestamp),n=t.high-e.high|0,i=t.low-e.low|0;if(Sa.ucompare(t.low,e.low)<0){n--;n|=0}var r=new Kn(n,i);return r.high<0?0:0<r.high||this.credential.ttl<r.low?this.credential.ttl:r.low},__class__:kt};var Ct=n["albero.entity.JoinConferenceMode"]={__ename__:["albero","entity","JoinConferenceMode"],__constructs__:["sfu","fullMesh","unknown"]};Ct.sfu=["sfu",0],Ct.sfu.toString=s,(Ct.sfu.__enum__=Ct).fullMesh=["fullMesh",1],Ct.fullMesh.toString=s,(Ct.fullMesh.__enum__=Ct).unknown=["unknown",2],Ct.unknown.toString=s,(Ct.unknown.__enum__=Ct).__empty_constructs__=[Ct.sfu,Ct.fullMesh,Ct.unknown];var Ot=n["albero.entity.LocalErrorType"]={__ename__:["albero","entity","LocalErrorType"],__constructs__:["TalksCountOvered","TalkersCountOvered","SendingMessageConflicted","DeletingMessageConflicted","UploadForbidden","UploadSizeOvered","StorageSizeOvered","GeneralFileError","UploadForbiddenForNote","UploadSizeOveredForNote","StorageSizeOveredForNote","GeneralFileErrorForNote","AddingSomeUsersFailure"]};Ot.TalksCountOvered=function(e){var t=["TalksCountOvered",0,e];return t.__enum__=Ot,t.toString=s,t},Ot.TalkersCountOvered=function(e){var t=["TalkersCountOvered",1,e];return t.__enum__=Ot,t.toString=s,t},Ot.SendingMessageConflicted=["SendingMessageConflicted",2],Ot.SendingMessageConflicted.toString=s,(Ot.SendingMessageConflicted.__enum__=Ot).DeletingMessageConflicted=["DeletingMessageConflicted",3],Ot.DeletingMessageConflicted.toString=s,(Ot.DeletingMessageConflicted.__enum__=Ot).UploadForbidden=["UploadForbidden",4],Ot.UploadForbidden.toString=s,(Ot.UploadForbidden.__enum__=Ot).UploadSizeOvered=function(e){var t=["UploadSizeOvered",5,e];return t.__enum__=Ot,t.toString=s,t},Ot.StorageSizeOvered=function(e){var t=["StorageSizeOvered",6,e];return t.__enum__=Ot,t.toString=s,t},Ot.GeneralFileError=["GeneralFileError",7],Ot.GeneralFileError.toString=s,(Ot.GeneralFileError.__enum__=Ot).UploadForbiddenForNote=function(e){var t=["UploadForbiddenForNote",8,e];return t.__enum__=Ot,t.toString=s,t},Ot.UploadSizeOveredForNote=function(e,t){var n=["UploadSizeOveredForNote",9,e,t];return n.__enum__=Ot,n.toString=s,n},Ot.StorageSizeOveredForNote=function(e,t){var n=["StorageSizeOveredForNote",10,e,t];return n.__enum__=Ot,n.toString=s,n},Ot.GeneralFileErrorForNote=function(e){var t=["GeneralFileErrorForNote",11,e];return t.__enum__=Ot,t.toString=s,t},Ot.AddingSomeUsersFailure=["AddingSomeUsersFailure",12],Ot.AddingSomeUsersFailure.toString=s,(Ot.AddingSomeUsersFailure.__enum__=Ot).__empty_constructs__=[Ot.SendingMessageConflicted,Ot.DeletingMessageConflicted,Ot.UploadForbidden,Ot.GeneralFileError,Ot.AddingSomeUsersFailure];function Mt(){}(n["albero.entity.LocalErrorTypeMixin"]=Mt).__name__=["albero","entity","LocalErrorTypeMixin"],Mt.toMessage=function(e){switch(e[1]){case 0:var t=e[2];return Yi.localize("LocalErrorType.number_of_talks",{limitMax:t});case 1:var n=e[2];return Yi.localize("LocalErrorType.number_of_talkers",{limitMax:n});case 2:return Yi.localize("LocalErrorType.retry_sending");case 3:return Yi.localize("LocalErrorType.retry_deletion");case 4:return Yi.localize("LocalErrorType.file_forbidden");case 5:var i=e[2],r=N.createByteSizeStringWithUnit(i);return Yi.localize("LocalErrorType.file_size",{sizeString:r});case 6:var a=e[2],o=N.createByteSizeStringWithUnit(a);return Yi.localize("LocalErrorType.storage_size",{sizeString:o});case 7:case 11:return Yi.localize("LocalErrorType.file");case 8:return Yi.localize("LocalErrorType.file_forbidden_for_note");case 9:var s=e[2],l=N.createByteSizeStringWithUnit(s);return Yi.localize("LocalErrorType.file_size",{sizeString:l});case 10:var u=e[2],c=N.createByteSizeStringWithUnit(u);return Yi.localize("LocalErrorType.storage_size",{sizeString:c});case 12:return Yi.localize("LocalErrorType.adding_users")}},Mt.getNoteId=function(e){switch(e[1]){case 8:var t=e[2];return Ra.Some(t);case 9:var n=e[3];return Ra.Some(n);case 10:var i=e[3];return Ra.Some(i);case 11:var r=e[2];return Ra.Some(r);default:return Ra.None}},Mt.convertFileErrorForNote=function(e,t){if(null==t)return null;if(403==t.code)return Ot.UploadForbiddenForNote(e);if(502==t.code&&null!=t.detail){var n=tt.fromIntOrInt64(t.detail.limit_max);if("file_size"==t.detail.limit_target)return Ot.UploadSizeOveredForNote(n,e);if("storage_size"==t.detail.limit_target)return Ot.UploadSizeOveredForNote(n,e)}return Ot.GeneralFileErrorForNote(e)};function Rt(e){dt.call(this,e),null!=e&&(this.email=e.email,this.signinId=e.signin_id,null!=e.profiles&&(this.profiles=Va.__cast(e.profiles,Array).map(function(e){return new Kt(e)})),null!=e.departments&&(this.departments=Va.__cast(e.departments,Array).map(function(e){return new _t(e)})))}(n["albero.entity.Me"]=Rt).__name__=["albero","entity","Me"],Rt.__super__=dt,Rt.prototype=i(dt.prototype,{toDomainUser:function(e){var t=new ft;if(t.id=this.id,t.status=this.status,t.domainId=e,t.displayName=this.displayName,t.canonicalDisplayName=this.canonicalDisplayName,t.phoneticDisplayName=this.phoneticDisplayName,t.canonicalPhoneticDisplayName=this.canonicalPhoneticDisplayName,t.profileImageUrl=this.profileImageUrl,t.updatedAt=this.updatedAt,t.email=this.email,null!=this.profiles)for(var n=0,i=this.profiles;n<i.length;){var r=i[n];++n;var a=r.domainId;if(null!=a&&null!=e&&a.high==e.high&&a.low==e.low){t.profileContact=r.itemValues;break}}if(null!=this.departments)for(var o=0,s=this.departments;o<s.length;){var l=s[o];++o;var u=l.domainId;if(null!=u&&null!=e&&u.high==e.high&&u.low==e.low){t.departments=l.departments;break}}return t},__class__:Rt});var Ft=function(e){if(null==e)return this.readUserIds=[],void(this.favorite=new vi(null));this.id=e.message_id,this.talkId=e.talk_id,this.userId=e.user_id,this.type=Ft.typeOf(e.type),this.content=e.content,this.createdAt=e.created_at,this.readCount=e.read_count,this.readUserIds=null==e.read_user_ids?[]:e.read_user_ids,this.isUnreadCountTarget=null==e.is_unread_count_target||e.is_unread_count_target,this.isBotMessage=null!=e.bot_message&&e.bot_message,this.favorite=new vi(e.favorite)};(n["albero.entity.Message"]=Ft).__name__=["albero","entity","Message"],Ft.typeOf=function(e){switch(e){case 0:return xt.system;case 1:return xt.text;case 2:return xt.stamp;case 3:return xt.geo;case 4:return xt.file;case 5:return xt.textMultipleFile;case 7:return xt.deleted;case 8:return xt.noteShared;case 9:return xt.noteDeleted;case 10:return xt.noteCreated;case 11:return xt.noteUpdated;case 12:return xt.originalStamp;case 500:return xt.yesOrNo;case 501:return xt.yesOrNoReply;case 502:return xt.selectOne;case 503:return xt.selectOneReply;case 504:return xt.todo;case 505:return xt.todoDone;case 506:return xt.yesOrNoClosed;case 507:return xt.selectOneClosed;case 508:return xt.todoClosed;case 509:return xt.openConference;case 600:return xt.phoneCall;case 601:return xt.phoneReceive;default:return xt.unknown}},Ft.enumIndex=function(e){switch(e[1]){case 0:case 1:case 2:case 3:case 4:case 5:case 7:case 8:case 9:case 10:case 11:case 12:return e[1];case 13:case 14:case 15:case 16:case 17:case 18:case 19:case 20:case 21:return 500+e[1]-13;case 23:case 24:return 600+e[1]-23;default:return-1}},Ft.typeString=function(e){return K.string(e)},Ft.getDisplayTextWithoutEscape=function(e,t){switch(e[1]){case 1:return t;case 7:return Ft.getDeletedText();default:return Gi._e("["+$e.dateStr(new Date)+"] ","Unsupported message.type is detected.",e,"","",""),Ft.getUnsupportText()}},Ft.getDeletedText=function(){return Yi.localize("MessageHelper.deleted")},Ft.getUnsupportText=function(){return Yi.localize("MessageHelper.not_support")},Ft.prototype={isDummy:function(){return null!=this.id&&this.id.high<0},messageStringForKeywordDetection:function(e){switch(this.type[1]){case 0:return"";case 1:return this.content;case 3:case 4:return"";case 5:return null!=this.content.text&&0<this.content.text.length?this.content.text:"";case 7:return"";case 2:case 12:return null!=this.content.text&&0<this.content.text.length?this.content.text:"";case 13:return[this.content.question,Yi.localize("MessageStringMaker.yes"),Yi.localize("MessageStringMaker.no")].join(" ");case 14:return e&&null!=this.content.response?this.content.response?Yi.localize("MessageStringMaker.yes"):Yi.localize("MessageStringMaker.no"):"";case 15:return null!=this.content.options?K.string(this.content.question)+" "+K.string(this.content.options.join(" ")):this.content.question;case 16:return e&&null!=this.content.response&&null!=this.content.options&&this.content.options.length>this.content.response?this.content.options[this.content.response]:"";case 17:return[this.content.title,Yi.localize("MessageStringMaker.achieve"),Yi.localize("MessageStringMaker.remand")].join(" ");case 18:return e&&null!=this.content.done?this.content.done?Yi.localize("MessageStringMaker.achieve"):Yi.localize("MessageStringMaker.remand"):"";case 19:case 20:case 21:default:return""}},messageStringForBookmarkWithEllipsis:function(){var e=this.messageStringForBookmark();return e.length<100?e:e.substring(0,99)+"…"},messageStringForBookmark:function(){switch(this.type[1]){case 1:return this.content;case 5:if(null!=this.content.text&&0<this.content.text.length)return this.content.text;break;case 7:return Yi.localize("Message.bookmark_label_deleted");case 8:return[Yi.localize("Message.bookmark_label_note_shared"),new hi(this.content).title].join(" ");case 10:return[Yi.localize("Message.bookmark_label_note_created"),new hi(this.content).title].join(" ");case 11:return[Yi.localize("Message.bookmark_label_note_updated"),new hi(this.content).title].join(" ");case 2:case 12:if(null!=this.content.text&&0<this.content.text.length)return[Yi.localize("Message.bookmark_label_stamp"),this.content.text].join(" ");break;case 14:case 16:return[Yi.localize("Message.bookmark_label_answer"),this.content.question].join(" ");case 13:case 15:return[Yi.localize("Message.bookmark_label_question"),this.content.question].join(" ");case 17:return[Yi.localize("Message.bookmark_label_task"),this.content.title].join(" ");case 18:return[this.content.done?Yi.localize("Message.bookmark_label_completed"):Yi.localize("Message.bookmark_label_reverted"),this.content.title].join(" ");case 19:case 20:return[Yi.localize("Message.bookmark_label_closed"),this.content.question].join(" ");case 21:return[Yi.localize("Message.bookmark_label_closed"),this.content.title].join(" ")}return""},getContentsForNote:function(){switch(this.type[1]){case 8:case 10:case 11:return new hi(this.content);default:return null}},getContentsForNoteDelete:function(){return 9==this.type[1]?new di(this.content):null},getContentsForOriginalStamp:function(){return 12==this.type[1]?new fi(this.content):null},isAllowedToDelete:function(e){return!!(this.isSentBy(e)&&this.isNotSystemMessage()&&this.isNotActionStampMessage()&&this.isNotNoteMessage())&&this.isNotDeletedMessage()},isAllowedToReply:function(e){return!(!this.isNotSentBy(e)||!this.isNotSystemMessage())&&this.isNotDeletedMessage()},isAllowedToQuote:function(e){return!!(this.isNotSystemMessage()&&this.isNotDeletedMessage()&&this.isNotFileMessage()&&this.isNotStampMessageWithEmptyText())&&this.isNotTextMultipleFileWithEmptyText()},isAllowedToCopy:function(){return!!(this.isNotSystemMessage()&&this.isNotDeletedMessage()&&this.isNotFileMessage()&&this.isNotStampMessageWithEmptyText())&&this.isNotTextMultipleFileWithEmptyText()},isAllowedToForward:function(e){return!!(this.isNotSystemMessage()&&this.isNotDeletedMessage()&&this.isNotActionStampMessage()&&this.isNotDeletedFileMessage(e)&&this.isNotTextMultipleFileAllDeletedWithEmptyText(e)&&this.isNotNoteMessage())&&this.isNotOpenConference()},isAllowedToForwardOnOnlyTextOrStamp:function(){return!(!this.isTextMessage()&&!this.isStampMessage())||this.isTextMultipleFileWithText()},isAllowedToAddToFavorites:function(){return!!(this.isNotSystemMessage()&&this.isNotDeletedMessage()&&this.isNotOpenConference()&&this.isNotStampMessageWithEmptyText()&&this.isNotNoteDeletedMessage())&&this.isNotFavorite()},isAllowedToRemoveFromFavorites:function(){return!!(this.isNotSystemMessage()&&this.isNotDeletedMessage()&&this.isNotOpenConference()&&this.isNotStampMessageWithEmptyText()&&this.isNotNoteDeletedMessage())&&this.isFavorite()},isAllowedToAddToTasks:function(){return!!(this.isTextMessage()||this.isFileMessage()||this.isTextMultipleFile())||this.isStampMessageWithText()},isSentBy:function(e){var t=this.userId;return null!=e&&null!=t&&e.high==t.high&&e.low==t.low},isNotSentBy:function(e){return!this.isSentBy(e)},isSystemMessage:function(){return this.type==xt.system},isNotSystemMessage:function(){return!this.isSystemMessage()},isActionStampMessage:function(){return this.type==xt.yesOrNo||this.type==xt.yesOrNoReply||this.type==xt.selectOne||this.type==xt.selectOneReply||this.type==xt.todo||this.type==xt.todoDone||this.type==xt.yesOrNoClosed||this.type==xt.selectOneClosed||this.type==xt.todoClosed},isNotActionStampMessage:function(){return!this.isActionStampMessage()},isReplyActionStampMessage:function(){return this.type==xt.selectOneReply||this.type==xt.yesOrNoReply||this.type==xt.todoDone},isClosedActionStampMessage:function(){return this.type==xt.yesOrNoClosed||this.type==xt.selectOneClosed||this.type==xt.todoClosed},isSendingActionStampMessage:function(){return this.type==xt.yesOrNo||this.type==xt.selectOne||this.type==xt.todo},isNoteMessage:function(){return this.type==xt.noteShared||this.type==xt.noteDeleted||this.type==xt.noteCreated||this.type==xt.noteUpdated},isNoteDeletedMessage:function(){return this.type==xt.noteDeleted},isNotNoteMessage:function(){return!this.isNoteMessage()},isNotNoteDeletedMessage:function(){return!this.isNoteDeletedMessage()},isDeletedMessage:function(){return this.type==xt.deleted},isNotDeletedMessage:function(){return!this.isDeletedMessage()},isFileMessage:function(){return this.type==xt.file},isNotFileMessage:function(){return!this.isFileMessage()},isStampMessage:function(){return this.type==xt.stamp||this.type==xt.originalStamp},isNotStampMessage:function(){return!this.isStampMessage()},isStampMessageWithText:function(){return!!this.isStampMessage()&&this.isNotObjectWithEmptyText()},isStampMessageWithEmptyText:function(){return!!this.isStampMessage()&&this.isObjectWithEmptyText()},isNotStampMessageWithEmptyText:function(){return!!this.isNotStampMessage()||this.isNotObjectWithEmptyText()},isObjectWithEmptyText:function(){return k.isEmpty(this.content.text)},isNotObjectWithEmptyText:function(){return!this.isObjectWithEmptyText()},isTextMultipleFile:function(){return this.type==xt.textMultipleFile},isNotTextMultipleFile:function(){return!this.isTextMultipleFile()},isTextMultipleFileWithText:function(){return!!this.isTextMultipleFile()&&this.isNotObjectWithEmptyText()},isTextMultipleFileWithEmptyText:function(){return!!this.isTextMultipleFile()&&this.isObjectWithEmptyText()},isNotTextMultipleFileWithEmptyText:function(){return!!this.isNotTextMultipleFile()||this.isNotObjectWithEmptyText()},isNotDeletedFileMessage:function(e){return!!this.isNotFileMessage()||!e},isNotTextMultipleFileAllDeletedWithEmptyText:function(e){return!!this.isNotTextMultipleFileWithEmptyText()||!e},isTextMessage:function(){return this.type==xt.text},isOpenConference:function(){return this.type==xt.openConference},isNotOpenConference:function(){return!this.isOpenConference()},getInReplyTo:function(){var e=this.type;return Gi._i("["+$e.dateStr(new Date)+"] ",e,"","","",""),this.isReplyActionStampMessage()||this.isClosedActionStampMessage()?Ra.Some(this.content.in_reply_to):Ra.None},isNotFavorite:function(){return!this.isFavorite()},isFavorite:function(){return this.favorite.isFavorite()},isNotCalloutHolder:function(){return!(!this.isFileMessage()&&!this.isTextMultipleFileWithEmptyText())||this.isStampMessageWithEmptyText()},close:function(){this.content.closed=!0},updateFavorite:function(e){this.favorite.update(e)},addReadUsersUntillMaxCount:function(e){var t=this;if(!(16<=this.readUserIds.length)){var n=e.filter(function(e){return tt.notContains(t.readUserIds,e)});this.readUserIds=this.readUserIds.concat(n).slice(0,16)}},createReadCountText:function(){return 16<=this.readUserIds.length?"15+":K.string(this.readUserIds.length)},hasNoReadUsers:function(){return 0==this.readUserIds.length},deleteFile:function(i){var e;switch(this.type[1]){case 4:e=[this.content];break;case 5:e=this.content.files;break;default:e=[]}if(0!=e.length){var t=et.find(e,function(e){var t=e.file_id,n=i.fileId;return null!=t&&null!=n&&t.high==n.high&&t.low==n.low});null!=t&&(t.deleted=!0)}},getQuestionTitle:function(){switch(this.type[1]){case 17:case 18:case 21:return null==this.content.title?"":this.content.title;case 13:case 14:case 15:case 16:case 19:case 20:return null==this.content.question?"":this.content.question;default:return""}},getChoiceCloseResponse:function(n){var e=Yi.localize("QuestionHelper.close_answer")+"\n";if(null==this.content.responses)e+="...";else{var t=this.content.responses,i=this.content.last_response;if(0==tn.closingTypeOf(this.content.closing_type)[1])e+=null!=i?Yi.localize("QuestionHelper.last_response",{content:n(t[i].content),interpolation:{escapeValue:!1}}):Yi.localize("QuestionHelper.no_answer");else{e+=null!=i?null==t?"":t.map(function(e){var t=null==e.count?0:e.count;return n(e.content)+": "+t+Yi.localize("QuestionHelper.name")}).join("\n"):Yi.localize("QuestionHelper.no_answer")}}return e},getTodoCloseResponse:function(){var e=Yi.localize("QuestionHelper.close_task")+"\n";if(null==this.content.responses)e+="...";else{var t=this.content.responses,n=this.content.last_response;if(0==tn.closingTypeOf(this.content.closing_type)[1]){e+=null!=n&&"DONE"==t[n].content?Yi.localize("QuestionHelper.achieve_task"):Yi.localize("QuestionHelper.not_achieve_task")}else{var i=0;if(null!=t)for(var r=0;r<t.length;){var a=t[r];if(++r,"DONE"==a.content){i=null==a.count?0:a.count;break}}e+=0!=i?Yi.localize("QuestionHelper.completed")+": "+i+Yi.localize("QuestionHelper.name"):Yi.localize("QuestionHelper.no_achiever")}}return e},__class__:Ft};var xt=n["albero.entity.MessageType"]={__ename__:["albero","entity","MessageType"],__constructs__:["system","text","stamp","geo","file","textMultipleFile","unused","deleted","noteShared","noteDeleted","noteCreated","noteUpdated","originalStamp","yesOrNo","yesOrNoReply","selectOne","selectOneReply","todo","todoDone","yesOrNoClosed","selectOneClosed","todoClosed","openConference","phoneCall","phoneReceive","unknown"]};xt.system=["system",0],xt.system.toString=s,(xt.system.__enum__=xt).text=["text",1],xt.text.toString=s,(xt.text.__enum__=xt).stamp=["stamp",2],xt.stamp.toString=s,(xt.stamp.__enum__=xt).geo=["geo",3],xt.geo.toString=s,(xt.geo.__enum__=xt).file=["file",4],xt.file.toString=s,(xt.file.__enum__=xt).textMultipleFile=["textMultipleFile",5],xt.textMultipleFile.toString=s,(xt.textMultipleFile.__enum__=xt).unused=["unused",6],xt.unused.toString=s,(xt.unused.__enum__=xt).deleted=["deleted",7],xt.deleted.toString=s,(xt.deleted.__enum__=xt).noteShared=["noteShared",8],xt.noteShared.toString=s,(xt.noteShared.__enum__=xt).noteDeleted=["noteDeleted",9],xt.noteDeleted.toString=s,(xt.noteDeleted.__enum__=xt).noteCreated=["noteCreated",10],xt.noteCreated.toString=s,(xt.noteCreated.__enum__=xt).noteUpdated=["noteUpdated",11],xt.noteUpdated.toString=s,(xt.noteUpdated.__enum__=xt).originalStamp=["originalStamp",12],xt.originalStamp.toString=s,(xt.originalStamp.__enum__=xt).yesOrNo=["yesOrNo",13],xt.yesOrNo.toString=s,(xt.yesOrNo.__enum__=xt).yesOrNoReply=["yesOrNoReply",14],xt.yesOrNoReply.toString=s,(xt.yesOrNoReply.__enum__=xt).selectOne=["selectOne",15],xt.selectOne.toString=s,(xt.selectOne.__enum__=xt).selectOneReply=["selectOneReply",16],xt.selectOneReply.toString=s,(xt.selectOneReply.__enum__=xt).todo=["todo",17],xt.todo.toString=s,(xt.todo.__enum__=xt).todoDone=["todoDone",18],xt.todoDone.toString=s,(xt.todoDone.__enum__=xt).yesOrNoClosed=["yesOrNoClosed",19],xt.yesOrNoClosed.toString=s,(xt.yesOrNoClosed.__enum__=xt).selectOneClosed=["selectOneClosed",20],xt.selectOneClosed.toString=s,(xt.selectOneClosed.__enum__=xt).todoClosed=["todoClosed",21],xt.todoClosed.toString=s,(xt.todoClosed.__enum__=xt).openConference=["openConference",22],xt.openConference.toString=s,(xt.openConference.__enum__=xt).phoneCall=["phoneCall",23],xt.phoneCall.toString=s,(xt.phoneCall.__enum__=xt).phoneReceive=["phoneReceive",24],xt.phoneReceive.toString=s,(xt.phoneReceive.__enum__=xt).unknown=["unknown",25],xt.unknown.toString=s,(xt.unknown.__enum__=xt).__empty_constructs__=[xt.system,xt.text,xt.stamp,xt.geo,xt.file,xt.textMultipleFile,xt.unused,xt.deleted,xt.noteShared,xt.noteDeleted,xt.noteCreated,xt.noteUpdated,xt.originalStamp,xt.yesOrNo,xt.yesOrNoReply,xt.selectOne,xt.selectOneReply,xt.todo,xt.todoDone,xt.yesOrNoClosed,xt.selectOneClosed,xt.todoClosed,xt.openConference,xt.phoneCall,xt.phoneReceive,xt.unknown];function Ut(e){null!=e&&(this.talkId=e[0],this.messageId=e[1])}(n["albero.entity.MessageDeletion"]=Ut).__name__=["albero","entity","MessageDeletion"],Ut.prototype={__class__:Ut};function Pt(e){this.id=e.message_id,this.talkId=e.talk_id,this.readUserIds=null==e.read_user_ids?[]:e.read_user_ids,this.unreadUserIds=null==e.unread_user_ids?[]:e.unread_user_ids}(n["albero.entity.MessageReadStatus"]=Pt).__name__=["albero","entity","MessageReadStatus"],Pt.prototype={__class__:Pt};function Lt(e){this.talkId=e.talk_id,this.messageIds=e.message_ids,this.readUserIds=null==e.read_user_ids?[]:e.read_user_ids,this.messageIdsExcludingUnreadCountTargets=e.message_ids_excluding_unread_count_targets,null==this.messageIdsExcludingUnreadCountTargets&&(this.messageIdsExcludingUnreadCountTargets=[])}(n["albero.entity.MessageReadStatusesUpdate"]=Lt).__name__=["albero","entity","MessageReadStatusesUpdate"],Lt.prototype={__class__:Lt};var Bt=n["albero.entity.MessagesOrder"]={__ename__:["albero","entity","MessagesOrder"],__constructs__:["asc","desc"]};Bt.asc=["asc",0],Bt.asc.toString=s,(Bt.asc.__enum__=Bt).desc=["desc",1],Bt.desc.toString=s,(Bt.desc.__enum__=Bt).__empty_constructs__=[Bt.asc,Bt.desc];function Ht(){}(n["albero.entity.MessagesOrderProc"]=Ht).__name__=["albero","entity","MessagesOrderProc"],Ht.orderToInt=function(e){switch(e[1]){case 0:return 1;case 1:return 2}};var jt=n["albero.entity.PaneType"]={__ename__:["albero","entity","PaneType"],__constructs__:["SingleTalkPane","MultiTalkPane1","MultiTalkPane2","MultiTalkPane3"]};jt.SingleTalkPane=["SingleTalkPane",0],jt.SingleTalkPane.toString=s,(jt.SingleTalkPane.__enum__=jt).MultiTalkPane1=["MultiTalkPane1",1],jt.MultiTalkPane1.toString=s,(jt.MultiTalkPane1.__enum__=jt).MultiTalkPane2=["MultiTalkPane2",2],jt.MultiTalkPane2.toString=s,(jt.MultiTalkPane2.__enum__=jt).MultiTalkPane3=["MultiTalkPane3",3],jt.MultiTalkPane3.toString=s,(jt.MultiTalkPane3.__enum__=jt).__empty_constructs__=[jt.SingleTalkPane,jt.MultiTalkPane1,jt.MultiTalkPane2,jt.MultiTalkPane3];function Yt(){}(n["albero.entity.PaneTypeHelper"]=Yt).__name__=["albero","entity","PaneTypeHelper"],Yt.toPanePrefix=function(e){switch(e[1]){case 0:return"";case 1:return"multi1-";case 2:return"multi2-";case 3:return"multi3-"}},Yt.getPaneType=function(e){switch(e){case 0:return jt.SingleTalkPane;case 1:return jt.MultiTalkPane1;case 2:return jt.MultiTalkPane2;case 3:return jt.MultiTalkPane3;default:return null}},Yt.getMultiPaneType=function(e){switch(e){case 0:return jt.MultiTalkPane1;case 1:return jt.MultiTalkPane2;case 2:return jt.MultiTalkPane3;default:return jt.MultiTalkPane1}},Yt.getMultiPaneTypes=function(){return[jt.MultiTalkPane1,jt.MultiTalkPane2,jt.MultiTalkPane3]},Yt.fromString=function(e){switch(e){case"multi1":return jt.MultiTalkPane1;case"multi2":return jt.MultiTalkPane2;case"multi3":return jt.MultiTalkPane3;default:return jt.SingleTalkPane}},Yt.toString=function(e){switch(e[1]){case 0:return"single";case 1:return"multi1";case 2:return"multi2";case 3:return"multi3"}};function Gt(e){null!=e&&(this.expiration=e.expiration,this.warning=e.warning)}(n["albero.entity.PasswordExpiration"]=Gt).__name__=["albero","entity","PasswordExpiration"],Gt.prototype={isExpired:function(e){return this.timeOvered(this.expiration,e)},needWarning:function(e,t){return!!this.timeOveredOrNotExist(t,e)&&this.timeOvered(this.warning,e)},timeOvered:function(e,t){if(null==e)return!1;var n=t.high-e.high|0;return n=0!=n?n:Sa.ucompare(t.low,e.low),0<(t.high<0?e.high<0?n:-1:0<=e.high?n:1)},timeOveredOrNotExist:function(e,t){return null==e||this.timeOvered(e,t)},__class__:Gt};var zt=function(e){null!=e&&(this.name=e.plan_name,this.trial=!!e.trial,this.free=!!e.free)};(n["albero.entity.Plan"]=zt).__name__=["albero","entity","Plan"],zt.prototype={__class__:zt};var Kt=function(e){null!=e&&(this.domainId=e.domain_id,this.userId=e.user_id,(this.itemValues=null)!=e.item_values&&(this.itemValues=Va.__cast(e.item_values,Array).map(function(e){return new qt(e)})))};(n["albero.entity.Profile"]=Kt).__name__=["albero","entity","Profile"],Kt.prototype={__class__:Kt};var Wt=function(e){if(null!=e&&(this.domainId=e.domain_id,null!=e.item_definitions)){this.itemDefinitions=[];for(var t=0,n=Va.__cast(e.item_definitions,Array);t<n.length;){var i=n[t];++t,this.itemDefinitions.push(new Vt(i))}}};(n["albero.entity.ProfileDefinition"]=Wt).__name__=["albero","entity","ProfileDefinition"],Wt.isSameProfileItemDefinitions=function(e,t){if(t.length!=e.length)return!1;for(var n=0,i=t.length;n<i;){var r=n++;if(t[r].profileItemId!=e[r].profileItemId)return!1}return!0},Wt.prototype={getVisibleItemDefinitions:function(t,n){return null==n&&(n=!1),null==t&&(t=!1),null==this.itemDefinitions?[]:this.itemDefinitions.filter(function(e){return!!e.visible&&(!(!t&&10!=e.group)&&(!n||1!=e.profileItemId&&2!=e.profileItemId))})},__class__:Wt};var Vt=function(e){this.locked=!1,this.visible=!0,null!=e&&(this.profileItemId=e.profile_item_id,this.group=e.group,this.name=e.name,this.valueType=e.value_type,null!=e.visible&&(this.visible=e.visible),null!=e.locked&&(this.locked=e.locked))};(n["albero.entity.ProfileItemDefinition"]=Vt).__name__=["albero","entity","ProfileItemDefinition"],Vt.findById=function(e,t){for(var n=0;n<e.length;){var i=e[n];if(++n,i.profileItemId==t)return i}return null},Vt.prototype={__class__:Vt};var qt=function(e){null!=e&&(this.profileItemId=e.profile_item_id,this.value=e.value,this.canonicalValue=e.canonical_value)};(n["albero.entity.ProfileItemValue"]=qt).__name__=["albero","entity","ProfileItemValue"],qt.findById=function(e,t){for(var n=0;n<e.length;){var i=e[n];if(++n,i.profileItemId==t)return i}return null},qt.prototype={__class__:qt};var Qt=function(e,t){this.domainId=e,this.profileItemValues=t};(n["albero.entity.ProfileItemValuesPerDomain"]=Qt).__name__=["albero","entity","ProfileItemValuesPerDomain"],Qt.convertToApiParams=function(e){return e.map(function(e){return e.convertToApiParamsPerDomain()})},Qt.prototype={convertToApiParamsPerDomain:function(){return[this.domainId,this.profileItemValues.map(function(e){return{profile_item_id:e.profileItemId,value:e.value}})]},__class__:Qt};function Jt(e){if(null==e)return this.enabled=!0,void(this.version=0);this.enabled=null==e.enabled||e.enabled,this.version=e.version}(n["albero.entity.PushNotificationSetting"]=Jt).__name__=["albero","entity","PushNotificationSetting"],Jt.createWithParams=function(e,t){var n=new Jt;return n.enabled=e,n.version=t,n},Jt.prototype={__class__:Jt};var Xt=function(e){null!=e&&(this.id=e.message_id,this.talkId=e.talk_id,this.type=Ft.typeOf(e.type),this.content=e.content,this.userId=e.user_id,this.recipientIds=e.assigned_user_ids,this.responses=Xt.createResponses(e.responses),this.listing=e.listing,this.closingType=tn.closingTypeOf(e.closing_type),this.maxResponseId=e.max_response_id,this.lastResponse=e.last_response,this.lastResponseUserId=e.last_response_user_id,this.createdAt=e.created_at,this.updatedAt=e.updated_at,this.responded=e.responded,this.closed=e.closed)};(n["albero.entity.Question"]=Xt).__name__=["albero","entity","Question"],Xt.createResponses=function(e){var t,n=it.option(e);switch(n[1]){case 0:t=n[2];break;case 1:t=[]}return t.map(function(e){return new nn(e)})},Xt.createResponsesFromStrings=function(e){var t,n=it.option(e);switch(n[1]){case 0:t=n[2];break;case 1:t=[]}return t.map(function(e){return new nn({content:e,count:0,user_ids:[]})})},Xt.createResponseTexts=function(e,t){switch(e[1]){case 13:return["YES","NO"];case 15:return t;case 17:return["DONE","UNDONE"];default:return[]}},Xt.fromMessageAndTalk=function(e,t){var n=new Xt;n.id=e.id,n.talkId=e.talkId,n.type=e.type;var i,r=it.option(e.content.title);switch(r[1]){case 0:i=r[2];break;case 1:i=e.content.question}n.content=i,n.userId=e.userId,n.recipientIds=t.userIds,n.responses=Xt.createResponsesFromStrings(Xt.createResponseTexts(e.type,e.content.options));var a,o=it.option(e.content.listing);switch(o[1]){case 0:a=o[2];break;case 1:a=!0}n.listing=a,n.closingType=tn.closingTypeOf(e.content.closing_type),n.maxResponseId=null,n.lastResponse=null,n.lastResponseUserId=null,n.updatedAt=n.createdAt=e.createdAt,n.responded=!1;var s,l=it.option(e.content.closed);switch(l[1]){case 0:s=l[2];break;case 1:s=!1}return n.closed=s,n},Xt.createTodoDoneMessageWithParams=function(e,t,n){var i=new Ft;return i.talkId=e,i.type=xt.todoDone,i.content={in_reply_to:t,done:n},i},Xt.createYesOrNoReplyMessageWithParams=function(e,t,n){var i=new Ft;return i.talkId=e,i.content={in_reply_to:t,response:n},i.type=xt.yesOrNoReply,i},Xt.createSelectOneReplyMessageWithParams=function(e,t,n){var i=new Ft;return i.talkId=e,i.content={in_reply_to:t,response:n},i.type=xt.selectOneReply,i},Xt.fromTypeToInt=function(e){switch(e[1]){case 0:return 0;case 1:return 1}},Xt.filterToOpBool=function(e){switch(e[1]){case 0:return Ra.Some(!0);case 1:return Ra.Some(!1);case 2:return Ra.None}},Xt.isDoneResponse=function(e){return"DONE"==e.content},Xt.prototype={isCompleted:function(e){if(ee.enumEq(this.type,xt.todo)){if(ee.enumEq(this.closingType,en.any)){if(null!=this.lastResponse&&"DONE"==this.responses[this.lastResponse].content)return!0}else{if(!this.responded)return!1;for(var t=0,n=this.responses;t<n.length;){var i=n[t];if(++t,i.contains(e))return"DONE"==i.content}}return!1}return ee.enumEq(this.closingType,en.any)?null!=this.lastResponse:this.responded},createTodoDoneMessage:function(e){return Xt.createTodoDoneMessageWithParams(this.talkId,this.id,e)},createYesOrNoReplyMessage:function(e){return Xt.createYesOrNoReplyMessageWithParams(this.talkId,this.id,e)},createSelectOneReplyMessage:function(e){return Xt.createSelectOneReplyMessageWithParams(this.talkId,this.id,e)},createActionCloseMessage:function(){var e=new Ft;switch(e.talkId=this.talkId,e.content={in_reply_to:this.id},this.type[1]){case 13:e.type=xt.yesOrNoClosed;break;case 15:e.type=xt.selectOneClosed;break;case 17:e.type=xt.todoClosed;break;default:Gi._e("["+$e.dateStr(new Date)+"] ","message type is not action.","","","","")}return e},getLastResponse:function(){var t=this;return it.map(it.option(this.lastResponse),function(e){return t.responses[e]})},getLastDoneResponse:function(){return it.filter(this.getLastResponse(),Xt.isDoneResponse)},getDoneResponse:function(){return it.option(et.find(this.responses,Xt.isDoneResponse))},isSendingQuestion:function(){return this.type==xt.yesOrNo||this.type==xt.selectOne||this.type==xt.todo},isNotSendingQuestion:function(){return!this.isSendingQuestion()},updateByMessage:function(e,t){switch(e.type[1]){case 14:var n=new gi(e.content).getResponseIndex();this.updateByReply(n,e,t);break;case 16:var i=new mi(e.content).getResponseIndex();this.updateByReply(i,e,t);break;case 18:var r=new pi(e.content).getResponseIndex();this.updateByReply(r,e,t);break;case 19:case 20:case 21:this.updateByClose()}},updateByClose:function(){this.closed=!0},updateByReply:function(e,t,n){this.updateByReplySub(e,t.id,t.userId,t.createdAt,n)},updateByReplySub:function(e,t,n,i,r){et.iter(this.responses,function(e){e.sub(n)}),this.responses[e].add(n),r&&(this.responded=!0);var a=this.updatedAt,o=i.high-a.high|0;o=0!=o?o:Sa.ucompare(i.low,a.low),0<(i.high<0?a.high<0?o:-1:0<=a.high?o:1)&&(this.updatedAt=i,this.maxResponseId=t,this.lastResponse=e,this.lastResponseUserId=n)},__class__:Xt};var Zt=n["albero.entity.QuestionFromType"]={__ename__:["albero","entity","QuestionFromType"],__constructs__:["fromSelf","fromOther"]};Zt.fromSelf=["fromSelf",0],Zt.fromSelf.toString=s,(Zt.fromSelf.__enum__=Zt).fromOther=["fromOther",1],Zt.fromOther.toString=s,(Zt.fromOther.__enum__=Zt).__empty_constructs__=[Zt.fromSelf,Zt.fromOther];var $t=n["albero.entity.QuestionFilter"]={__ename__:["albero","entity","QuestionFilter"],__constructs__:["onlyClosed","onlyUnclosed","noFilter"]};$t.onlyClosed=["onlyClosed",0],$t.onlyClosed.toString=s,($t.onlyClosed.__enum__=$t).onlyUnclosed=["onlyUnclosed",1],$t.onlyUnclosed.toString=s,($t.onlyUnclosed.__enum__=$t).noFilter=["noFilter",2],$t.noFilter.toString=s,($t.noFilter.__enum__=$t).__empty_constructs__=[$t.onlyClosed,$t.onlyUnclosed,$t.noFilter];var en=n["albero.entity.QuestionClosingType"]={__ename__:["albero","entity","QuestionClosingType"],__constructs__:["any","all","unknown"]};en.any=["any",0],en.any.toString=s,(en.any.__enum__=en).all=["all",1],en.all.toString=s,(en.all.__enum__=en).unknown=["unknown",2],en.unknown.toString=s,(en.unknown.__enum__=en).__empty_constructs__=[en.any,en.all,en.unknown];var tn=function(){};(n["albero.entity.QuestionClosingTypeHelper"]=tn).__name__=["albero","entity","QuestionClosingTypeHelper"],tn.closingTypeOf=function(e){switch(e){case 0:return en.any;case 1:return en.all;default:return en.unknown}};var nn=function(e){this.content=e.content,this.count=null==e.count?0:e.count,this.userIds=null==e.user_ids?[]:e.user_ids};(n["albero.entity.QuestionResponse"]=nn).__name__=["albero","entity","QuestionResponse"],nn.prototype={add:function(e){this.contains(e)||(this.count+=1,this.userIds=this.userIds.concat([e]))},sub:function(t){this.contains(t)&&(this.count-=1,this.userIds=this.userIds.filter(function(e){return!(t.high==e.high&&t.low==e.low)}))},contains:function(e){return tt.contains(this.userIds,e)},__class__:nn};var rn=function(e){null!=e&&(this.msgRetentionPeriod=e.msg_retention_period,this.msgFileSize=e.msg_file_size,this.maxMessageContentLength=e.max_message_content_length,this.maxTalkers=e.max_talkers,this.maxTalks=e.max_talks,this.withAd=!!e.with_ad)};(n["albero.entity.Quota"]=rn).__name__=["albero","entity","Quota"],rn.prototype={__class__:rn};function an(e){if(null!=e&&(this.total=e.total,this.marker=e.marker,this.nextMarker=e.next_marker,this.contents=[],null!=e.contents))for(var t=0,n=Va.__cast(e.contents,Array);t<n.length;){var i=n[t];++t,this.contents.push(new St(i))}}(n["albero.entity.SearchAttachmentsResult"]=an).__name__=["albero","entity","SearchAttachmentsResult"],an.prototype={__class__:an};function on(e){null!=e&&(this.total=e.total,this.marker=e.marker,this.nextMarker=e.next_marker,this.contents=[],null!=e.contents&&(this.contents=Va.__cast(e.contents,Array).map(function(e){return new Nt(e)})))}(n["albero.entity.SearchMessagesResult"]=on).__name__=["albero","entity","SearchMessagesResult"],on.prototype={__class__:on};function sn(e){null!=e&&(null!=e.domain_id_str&&(this.domainId=tt.makeFromIdStr(e.domain_id_str)),null!=e.talk_id_str&&(this.talkId=tt.makeFromIdStr(e.talk_id_str)),this.keyword=e.keyword,null==e.search_type||e.search_type==un.toLocalizeText(ln.MESSAGES)?this.searchType=ln.MESSAGES:this.searchType=ln.ATTACHMENTS,this.sinceText=e.since,this.untilText=e.until,null!=e.from_id_str&&(this.fromUserId=tt.makeFromIdStr(e.from_id_str)))}(n["albero.entity.SearchParams"]=sn).__name__=["albero","entity","SearchParams"],sn.dateQueryToText=function(e,t){if(null==e)return t;switch(e){case"-1d":return Yi.localize("SearchParams.text_date_yesterday");case"-3d":return Yi.localize("SearchParams.text_date_three_days_before");case"t":return Yi.localize("SearchParams.text_date_today");default:return W.replace(e,"-","/")}},sn.prototype={toProps:function(){var e={};if(null!=this.domainId){var t=this.domainId;e.domain_id_str="_"+t.high+"_"+t.low}if(null!=this.talkId){var n=this.talkId;e.talk_id_str="_"+n.high+"_"+n.low}if(e.keyword=this.keyword,e.search_type=un.toLocalizeText(this.searchType),e.since=this.sinceText,e.until=this.untilText,null!=this.fromUserId){var i=this.fromUserId;e.from_id_str="_"+i.high+"_"+i.low}return e},copy:function(){return new sn(this.toProps())},eq:function(e){return!!this.isSameInt64(this.domainId,e.domainId)&&(!!this.isSameInt64(this.talkId,e.talkId)&&(this.keyword==e.keyword&&(!!ee.enumEq(this.searchType,e.searchType)&&(this.sinceText==e.sinceText&&(this.untilText==e.untilText&&!!this.isSameInt64(this.fromUserId,e.fromUserId))))))},isSameInt64:function(e,t){return null==e&&null==t||null!=e&&null!=t&&e.high==t.high&&e.low==t.low},getQueryText:function(){var e=[];return null!=this.keyword&&0!=this.keyword.length&&e.push(this.keyword),null!=this.sinceText&&e.push("since:"+this.sinceText),null!=this.untilText&&e.push("until:"+this.untilText),null!=this.fromUserId&&e.push("from:"+wa.toString(this.fromUserId)),e.join(" ")},getPeriodText:function(){return sn.dateQueryToText(this.sinceText,"")+"~"+sn.dateQueryToText(this.untilText,"")},__class__:sn};var ln=n["albero.entity.SearchType"]={__ename__:["albero","entity","SearchType"],__constructs__:["MESSAGES","ATTACHMENTS"]};ln.MESSAGES=["MESSAGES",0],ln.MESSAGES.toString=s,(ln.MESSAGES.__enum__=ln).ATTACHMENTS=["ATTACHMENTS",1],ln.ATTACHMENTS.toString=s,(ln.ATTACHMENTS.__enum__=ln).__empty_constructs__=[ln.MESSAGES,ln.ATTACHMENTS];var un=function(){};(n["albero.entity.SearchTypeUtil"]=un).__name__=["albero","entity","SearchTypeUtil"],un.toLocalizeText=function(e){switch(e[1]){case 0:return Yi.localize("SearchParams.text_type_messages");case 1:return Yi.localize("SearchParams.text_type_attachments")}};var cn=n["albero.entity.SearchDate"]={__ename__:["albero","entity","SearchDate"],__constructs__:["DATE_NONE","DATE_TODAY","DATE_YESTERDAY","DATE_THREE_DAYS_BEFORE","DATE_CALENDAR"]};cn.DATE_NONE=["DATE_NONE",0],cn.DATE_NONE.toString=s,(cn.DATE_NONE.__enum__=cn).DATE_TODAY=["DATE_TODAY",1],cn.DATE_TODAY.toString=s,(cn.DATE_TODAY.__enum__=cn).DATE_YESTERDAY=["DATE_YESTERDAY",2],cn.DATE_YESTERDAY.toString=s,(cn.DATE_YESTERDAY.__enum__=cn).DATE_THREE_DAYS_BEFORE=["DATE_THREE_DAYS_BEFORE",3],cn.DATE_THREE_DAYS_BEFORE.toString=s,(cn.DATE_THREE_DAYS_BEFORE.__enum__=cn).DATE_CALENDAR=["DATE_CALENDAR",4],cn.DATE_CALENDAR.toString=s,(cn.DATE_CALENDAR.__enum__=cn).__empty_constructs__=[cn.DATE_NONE,cn.DATE_TODAY,cn.DATE_YESTERDAY,cn.DATE_THREE_DAYS_BEFORE,cn.DATE_CALENDAR];function _n(){}(n["albero.entity.SearchDateUtil"]=_n).__name__=["albero","entity","SearchDateUtil"],_n.createSearchDateArray=function(e){return e?[cn.DATE_TODAY,cn.DATE_YESTERDAY,cn.DATE_THREE_DAYS_BEFORE,cn.DATE_CALENDAR]:[cn.DATE_YESTERDAY,cn.DATE_THREE_DAYS_BEFORE,cn.DATE_CALENDAR]},_n.toLocalizeText=function(e){switch(e[1]){case 0:return Yi.localize("SearchParams.text_date_none");case 1:return Yi.localize("SearchParams.text_date_today");case 2:return Yi.localize("SearchParams.text_date_yesterday");case 3:return Yi.localize("SearchParams.text_date_three_days_before");case 4:return Yi.localize("SearchParams.text_date_calendar")}};function hn(e){null!=e&&(this.user=new Rt(e.user),this.device=e.device,this.notification=e.notification,this.passwordExpiration=new Gt(e.password_expiration),this.configuration=new Le(e.configuration))}(n["albero.entity.Session"]=hn).__name__=["albero","entity","Session"],hn.prototype={__class__:hn};function dn(e){null!=e&&(this.solutionId=e.solution_id,this.name=e.name,null!=e.link&&(this.link=new fn(e.link)),null!=e.plugin&&(this.plugin=new mn(e.plugin)))}(n["albero.entity.Solution"]=dn).__name__=["albero","entity","Solution"],dn.getSolutionType=function(e){switch(e){case 1:return pn.PhotoViewTrial;case 2:return pn.PhotoView;case 3:return pn.MultiView;case 4:return pn.KeywordWatching;case 26:return pn.Flow;default:return pn.Unknown}},dn.getSolutionIdFromType=function(e){switch(e[1]){case 0:return 1;case 1:return 2;case 2:return 3;case 3:return 4;case 4:return 26;default:return null}},dn.prototype={__class__:dn};var fn=function(e){null!=e&&(this.iconUrl=e.icon_url,this.url=e.url)};(n["albero.entity.SolutionLink"]=fn).__name__=["albero","entity","SolutionLink"],fn.prototype={__class__:fn};var mn=function(e){null!=e&&(this.url=e.url,this.loaded=!1)};(n["albero.entity.SolutionPlugin"]=mn).__name__=["albero","entity","SolutionPlugin"],mn.prototype={__class__:mn};var pn=n["albero.entity.SolutionType"]={__ename__:["albero","entity","SolutionType"],__constructs__:["PhotoViewTrial","PhotoView","MultiView","KeywordWatching","Flow","Unknown"]};pn.PhotoViewTrial=["PhotoViewTrial",0],pn.PhotoViewTrial.toString=s,(pn.PhotoViewTrial.__enum__=pn).PhotoView=["PhotoView",1],pn.PhotoView.toString=s,(pn.PhotoView.__enum__=pn).MultiView=["MultiView",2],pn.MultiView.toString=s,(pn.MultiView.__enum__=pn).KeywordWatching=["KeywordWatching",3],pn.KeywordWatching.toString=s,(pn.KeywordWatching.__enum__=pn).Flow=["Flow",4],pn.Flow.toString=s,(pn.Flow.__enum__=pn).Unknown=["Unknown",5],pn.Unknown.toString=s,(pn.Unknown.__enum__=pn).__empty_constructs__=[pn.PhotoViewTrial,pn.PhotoView,pn.MultiView,pn.KeywordWatching,pn.Flow,pn.Unknown];function gn(){}(n["albero.entity.Stamp"]=gn).__name__=["albero","entity","Stamp"],gn.prototype={__class__:gn};function vn(e){this.commonStampId=e}(n["albero.entity.CommonStamp"]=vn).__name__=["albero","entity","CommonStamp"],vn.__interfaces__=[gn],vn.fromCommonStampId=function(e){return new vn(e)},vn.fromJson=function(e){return null==e.commonStampId?null:vn.fromCommonStampId(e.commonStampId)},vn.prototype={getImageUrl:function(){return"./images/stamp/3/"+this.commonStampId+".png"},getKey:function(){return"common_"+this.commonStampId},toJson:function(){return{commonStampId:this.commonStampId}},createMessage:function(e,t){var n=new Ft;return n.talkId=e,n.type=xt.stamp,n.content={stamp_set:3,stamp_index:this.createStampIndex()},null!=t&&0!=t.length&&(n.content.text=t),n},createStampIndex:function(){for(var e=new Kn(0,0),t=new Kn(0,10),n=0,i=this.commonStampId.length;n<i;){var r=n++,a=65535&e.low,o=e.low>>>16,s=65535&t.low,l=t.low>>>16,u=Sa._mul(a,s),c=Sa._mul(o,s),_=Sa._mul(a,l),h=u,d=(Sa._mul(o,l)+(_>>>16)|0)+(c>>>16)|0;if(h=h+(_<<=16)|0,Sa.ucompare(h,_)<0){d++;d|=0}if(h=h+(c<<=16)|0,Sa.ucompare(h,c)<0){d++;d|=0}d=d+(Sa._mul(e.low,t.high)+Sa._mul(e.high,t.low)|0)|0;var f=new Kn(d,h),m=new Kn(0,K.parseInt(this.commonStampId.charAt(r))),p=f.high+m.high|0,g=f.low+m.low|0;if(Sa.ucompare(g,f.low)<0){p++;p|=0}e=new Kn(p,g)}return e},__class__:vn};function yn(e,t,n){this.stampsetId=e,this.id=t,this.illust=n}(n["albero.entity.OriginalStamp"]=yn).__name__=["albero","entity","OriginalStamp"],yn.__interfaces__=[gn],yn.fromJson=function(e){if(null==e.originalStamp)return null;var t=e.originalStamp;if(null==t.stampsetIdStr||null==t.stampIdStr)return null;var n=tt.makeFromIdStr(t.stampsetIdStr),i=tt.makeFromIdStr(t.stampIdStr);return new yn(n,i,t.illust)},yn.fromPropsAndStampsetId=function(e,t){return new yn(t,tt.fromIntOrInt64(e.id),e.illust)},yn.createKey=function(e){return"original__"+e.high+"_"+e.low},yn.prototype={getImageUrl:function(){return this.illust},getKey:function(){return yn.createKey(this.id)},toJson:function(){var e=this.stampsetId,t=this.id;return{originalStamp:{stampsetIdStr:"_"+e.high+"_"+e.low,stampIdStr:"_"+t.high+"_"+t.low,illust:this.illust}}},createMessage:function(e,t){var n=new Ft;return n.talkId=e,n.type=xt.originalStamp,n.content={stampset_id:this.stampsetId,stamp_id:this.id},null!=t&&0!=t.length&&(n.content.text=t),n},__class__:yn};function Sn(e,t,n,i){this.stampsetType=e,this.name=t,this.icon=n,this.version=i,this.stamps=[]}(n["albero.entity.Stampset"]=Sn).__name__=["albero","entity","Stampset"],Sn.historyStampset=function(){return new Sn(En.getHistoryStampsetType(),"stamp-history",null,0)},Sn.commonStampset=function(e,t,n){return new Sn(En.fromCommonStampCategoryIndex(e),t,"./images/stamp/3/"+n,0)},Sn.originalStampset=function(e){var t=tt.fromIntOrInt64(e.stampset_id),n=En.fromStampsetId(t),i=new Sn(n,e.name,e.icon,e.version);if(null!=e.stamps){var r=Va.__cast(e.stamps,Array).map(function(e){return yn.fromPropsAndStampsetId(e,t)});i.setStamps(r)}return i},Sn.fromStampsetInfo=function(e){var t=En.fromStampsetId(e.stampsetId);return new Sn(t,e.name,e.icon,e.version)},Sn.prototype={toTabId:function(){return this.stampsetType.toTabId()},getIconUrl:function(){return this.icon},isStampHistory:function(){return"stamp-history"==this.name},isOriginalStampset:function(){return this.stampsetType.isOriginalStampset()},isEmpty:function(){return 0==this.stamps.length},setStamps:function(e){this.stamps=e},getStamps:function(){return this.stamps},isOlderThan:function(e){return this.version<e.version},__class__:Sn};function wn(e){null!=e&&(this.stampsetId=tt.fromIntOrInt64(e.stampset_id),this.name=e.name,this.icon=e.icon,this.version=e.version)}(n["albero.entity.StampsetInfo"]=wn).__name__=["albero","entity","StampsetInfo"],wn.prototype={toTabId:function(){var e=this.stampsetId;return"_"+e.high+"_"+e.low},eqStampsetId:function(e){var t=this.stampsetId,n=e.stampsetId;return null!=t&&null!=n&&t.high==n.high&&t.low==n.low},isNewerThan:function(e){return this.version>e.version},__class__:wn};var Tn=function(e){this.stampsetInfos=[],this.allowCreateMessageStampsetIds=[],this.version=0,null!=e&&(this.version=e.version,this.allowCreateMessageStampsetIds=e.allow_create_message_stampset_ids.map(tt.fromIntOrInt64),this.stampsetInfos=this.getStampsetInfos(e.stampset_infos))};(n["albero.entity.StampsetSetting"]=Tn).__name__=["albero","entity","StampsetSetting"],Tn.prototype={getStampsetInfos:function(e){return null==e?[]:e.map(function(e){return new wn(e)})},isForwardForbidden:function(e){var t=e.getContentsForOriginalStamp(),n=null==t?null:t.stampsetId;return null!=n&&!this.containSendableStampset(n)},containSendableStampset:function(t){return null!=this.allowCreateMessageStampsetIds&&et.exists(this.allowCreateMessageStampsetIds,function(e){return null!=t&&null!=e&&t.high==e.high&&t.low==e.low})},containVisibleStampset:function(n){return et.exists(this.stampsetInfos,function(e){var t=e.stampsetId;return null!=n&&null!=t&&n.high==t.high&&n.low==t.low})},getSendableStampsetInfos:function(){var t=this;return null==this.stampsetInfos?[]:null==this.allowCreateMessageStampsetIds?[]:this.stampsetInfos.filter(function(e){return t.containSendableStampset(e.stampsetId)})},isNewerThan:function(e){return this.version>e.version},updateStampsetInfo:function(t){this.stampsetInfos=this.stampsetInfos.map(function(e){return t.eqStampsetId(e)&&t.isNewerThan(e)?t:e})},deleteStampsetInfo:function(n){this.stampsetInfos=this.stampsetInfos.filter(function(e){var t=e.stampsetId;return!(null!=t&&null!=n&&t.high==n.high&&t.low==n.low)}),this.allowCreateMessageStampsetIds=this.allowCreateMessageStampsetIds.filter(function(e){return!(null!=e&&null!=n&&e.high==n.high&&e.low==n.low)})},getStampsetIdsDiff:function(e){for(var t=new xa,n=e.stampsetInfos.concat(this.stampsetInfos),i=0;i<n.length;){var r=n[i];++i;var a=r.stampsetId,o="_"+a.high+"_"+a.low,s=((null!=No[o]?t.existsReserved(o):t.h.hasOwnProperty(o))?null!=No[o]?t.getReserved(o):t.h[o]:0)+1;null!=No[o]?t.setReserved(o,s):t.h[o]=s}for(var l=[],u=t.keys();u.hasNext();){var c=u.next();1==(null!=No[c]?t.getReserved(c):t.h[c])&&l.push(tt.makeFromIdStr(c))}return l},__class__:Tn};var In=n["albero.entity.StampsetTypeValue"]={__ename__:["albero","entity","StampsetTypeValue"],__constructs__:["HISTORY","COMMON_CIMMON","COMMON_BUSINESS","COMMON_BUSINESS_TEXT","COMMON_LARGE_TEXT","COMMON_EFFECT","COMMON_EFFECT2","COMMON_HANKO","COMMON_YUZU","COMMON_YUZU2","COMMON_YUZU3","ORIGINAL"]};In.HISTORY=["HISTORY",0],In.HISTORY.toString=s,(In.HISTORY.__enum__=In).COMMON_CIMMON=["COMMON_CIMMON",1],In.COMMON_CIMMON.toString=s,(In.COMMON_CIMMON.__enum__=In).COMMON_BUSINESS=["COMMON_BUSINESS",2],In.COMMON_BUSINESS.toString=s,(In.COMMON_BUSINESS.__enum__=In).COMMON_BUSINESS_TEXT=["COMMON_BUSINESS_TEXT",3],In.COMMON_BUSINESS_TEXT.toString=s,(In.COMMON_BUSINESS_TEXT.__enum__=In).COMMON_LARGE_TEXT=["COMMON_LARGE_TEXT",4],In.COMMON_LARGE_TEXT.toString=s,(In.COMMON_LARGE_TEXT.__enum__=In).COMMON_EFFECT=["COMMON_EFFECT",5],In.COMMON_EFFECT.toString=s,(In.COMMON_EFFECT.__enum__=In).COMMON_EFFECT2=["COMMON_EFFECT2",6],In.COMMON_EFFECT2.toString=s,(In.COMMON_EFFECT2.__enum__=In).COMMON_HANKO=["COMMON_HANKO",7],In.COMMON_HANKO.toString=s,(In.COMMON_HANKO.__enum__=In).COMMON_YUZU=["COMMON_YUZU",8],In.COMMON_YUZU.toString=s,(In.COMMON_YUZU.__enum__=In).COMMON_YUZU2=["COMMON_YUZU2",9],In.COMMON_YUZU2.toString=s,(In.COMMON_YUZU2.__enum__=In).COMMON_YUZU3=["COMMON_YUZU3",10],In.COMMON_YUZU3.toString=s,(In.COMMON_YUZU3.__enum__=In).ORIGINAL=function(e){var t=["ORIGINAL",11,e];return t.__enum__=In,t.toString=s,t},In.__empty_constructs__=[In.HISTORY,In.COMMON_CIMMON,In.COMMON_BUSINESS,In.COMMON_BUSINESS_TEXT,In.COMMON_LARGE_TEXT,In.COMMON_EFFECT,In.COMMON_EFFECT2,In.COMMON_HANKO,In.COMMON_YUZU,In.COMMON_YUZU2,In.COMMON_YUZU3];var En=function(e){this.value=e};(n["albero.entity.StampsetType"]=En).__name__=["albero","entity","StampsetType"],En.fromStampsetId=function(e){return new En(In.ORIGINAL(e))},En.fromCommonStampCategoryIndex=function(e){switch(e){case 0:return new En(In.COMMON_CIMMON);case 1:return new En(In.COMMON_BUSINESS);case 2:return new En(In.COMMON_BUSINESS_TEXT);case 3:return new En(In.COMMON_LARGE_TEXT);case 4:return new En(In.COMMON_EFFECT);case 5:return new En(In.COMMON_EFFECT2);case 6:return new En(In.COMMON_HANKO);case 7:return new En(In.COMMON_YUZU);case 8:return new En(In.COMMON_YUZU2);case 9:return new En(In.COMMON_YUZU3);default:return null}},En.fromTabId=function(e){var t=K.parseInt(e);if(null!=t)if(null==t){var n=En.fromCommonStampCategoryIndex(t-1);if(null!=n)return n}else{if(0==t)return En.getHistoryStampsetType();var i=En.fromCommonStampCategoryIndex(t-1);if(null!=i)return i}var r=tt.makeFromIdStr(e);if(null!=r)return new En(In.ORIGINAL(r));try{return new En(ee.createEnum(In,e))}catch(e){return En.getDefaultStampsetType()}},En.getHistoryStampsetType=function(){return new En(In.HISTORY)},En.getDefaultStampsetType=function(){return new En(In.COMMON_CIMMON)},En.prototype={toTabId:function(){var e=this.value;if(11!=e[1])return K.string(this.value);var t=e[2];return"_"+t.high+"_"+t.low},getStampsetId:function(){var e=this.value;return 11!=e[1]?null:e[2]},isOriginalStampset:function(){var e=this.value;if(11!=e[1])return null;e[2];return!0},fallbackIfInvalid:function(e){return this.isValid(e)?this:En.getDefaultStampsetType()},isValid:function(e){var t=this.value;if(11!=t[1])return!0;var n=t[2];return null!=e&&null!=e.stampsetSetting&&e.stampsetSetting.containSendableStampset(n)},__class__:En};var Nn=function(e){null!=e&&(this.id=e.talk_id,this.domainId=e.domain_id,this.type=this.typeOf(e.type),this.name=e.talk_name,this.iconUrl=e.icon_url,this.userIds=e.user_ids,this.updatedAt=e.updated_at,this.leftUsers=this.getUsers(e.left_users),this.groupTalkSettings=this.getGroupTalkSetting(e.settings))};(n["albero.entity.Talk"]=Nn).__name__=["albero","entity","Talk"],Nn.prototype={typeOf:function(e){switch(e){case 1:return bn.PairTalk;case 2:return bn.GroupTalk;default:return bn.Unknown}},getUsers:function(e){return null==e?null:e.map(function(e){return new ft(e)})},getGroupTalkSetting:function(e){return null==e?Ra.None:Ra.Some(new An(e))},isSystemMessageVisibled:function(){var e=it.map(this.groupTalkSettings,function(e){return e.systemMessageVisible});switch(e[1]){case 0:return e[2];case 1:return!0}},isAllowDisplayPastMessages:function(){var e=it.map(this.groupTalkSettings,function(e){return e.allowDisplayPastMessages});switch(e[1]){case 0:return e[2];case 1:return!1}},__class__:Nn};var An=function(e){null!=e&&(this.allowDisplayPastMessages=!!e.allow_display_past_messages,this.systemMessageVisible=null==e.system_message_visible||e.system_message_visible)};(n["albero.entity.GroupTalkSettings"]=An).__name__=["albero","entity","GroupTalkSettings"],An.createDefault=function(){var e=new An;return e.allowDisplayPastMessages=!0,e.systemMessageVisible=!0,e},An.prototype={__class__:An};var bn=n["albero.entity.TalkType"]={__ename__:["albero","entity","TalkType"],__constructs__:["Unknown","PairTalk","GroupTalk"]};bn.Unknown=["Unknown",0],bn.Unknown.toString=s,(bn.Unknown.__enum__=bn).PairTalk=["PairTalk",1],bn.PairTalk.toString=s,(bn.PairTalk.__enum__=bn).GroupTalk=["GroupTalk",2],bn.GroupTalk.toString=s,(bn.GroupTalk.__enum__=bn).__empty_constructs__=[bn.Unknown,bn.PairTalk,bn.GroupTalk];var Dn=n["albero.entity.TalkOrAnnoucements"]={__ename__:["albero","entity","TalkOrAnnoucements"],__constructs__:["talk","annoucements"]};Dn.talk=function(e){var t=["talk",0,e];return t.__enum__=Dn,t.toString=s,t},Dn.annoucements=["annoucements",1],Dn.annoucements.toString=s,(Dn.annoucements.__enum__=Dn).__empty_constructs__=[Dn.annoucements];function kn(){}(n["albero.entity.TalkOrAnncounementsHelper"]=kn).__name__=["albero","entity","TalkOrAnncounementsHelper"],kn.getTalkId=function(e){switch(e[1]){case 0:var t=e[2];return Ra.Some(t);case 1:return Ra.None}};function Cn(e,t){this.talk=e,this.status=t}(n["albero.entity.TalkPack"]=Cn).__name__=["albero","entity","TalkPack"],Cn.compareTalkOrderingTimestamp=function(e,t){var n=e.getTalkOrderingTimestamp(),i=t.getTalkOrderingTimestamp(),r=n.high-i.high|0;return r=0!=r?r:Sa.ucompare(n.low,i.low),n.high<0?i.high<0?r:-1:0<=i.high?r:1},Cn.compareTalkConsideredFavorite=function(e,t){var n=e.getTalkOrderInFavorites(),i=t.getTalkOrderInFavorites();return null!=n&&null!=i?Cn.compareTalkOrderingTimestamp(e,t):null!=n?1:null!=i?-1:Cn.compareTalkOrderingTimestamp(e,t)},Cn.prototype={getTalkOrderingTimestamp:function(){return null!=this.status&&null!=this.status.talkOrderingTimestamp?this.status.talkOrderingTimestamp:this.talk.updatedAt},getTalkOrderInFavorites:function(){return null!=this.status?this.status.orderInFavorites:null},__class__:Cn};var On=function(e,t){this.paneType=e,this.talkSelection=t};(n["albero.entity.TalkPaneSelection"]=On).__name__=["albero","entity","TalkPaneSelection"],On.createArrayForMultiPanes=function(e){return et.mapi(e,function(e,t){return new On(Yt.getMultiPaneType(e),t)})},On.prototype={createUrls:function(e,t){switch(this.paneType[1]){case 0:return V.talks(e,C.single(this.talkSelection));case 1:var n=go(t,t.getTalkSelection),i=e,r=Yt.getMultiPaneTypes().map(function(e){return n(i,e)});return r[0]=this.talkSelection,V.talks(e,C.multi(r));case 2:var a=go(t,t.getTalkSelection),o=e,s=Yt.getMultiPaneTypes().map(function(e){return a(o,e)});return s[1]=this.talkSelection,V.talks(e,C.multi(s));case 3:var l=go(t,t.getTalkSelection),u=e,c=Yt.getMultiPaneTypes().map(function(e){return l(u,e)});return c[2]=this.talkSelection,V.talks(e,C.multi(c))}},getTalkIdOrNull:function(){return xn.getTalkIdOrNull(this.talkSelection)},__class__:On};function Mn(){}(n["albero.entity.ITalkSelectionGetter"]=Mn).__name__=["albero","entity","ITalkSelectionGetter"],Mn.prototype={__class__:Mn};function Rn(e){null!=e&&(this.domainId=e.domain_id,this.talkId=e.talk_id,this.version=e.version)}(n["albero.entity.TalkPushNotificationEvent"]=Rn).__name__=["albero","entity","TalkPushNotificationEvent"],Rn.prototype={__class__:Rn};var Fn=n["albero.entity.TalkSelection"]={__ename__:["albero","entity","TalkSelection"],__constructs__:["NotSelected","TalkSelected","AnnouncementsSelected"]};Fn.NotSelected=["NotSelected",0],Fn.NotSelected.toString=s,(Fn.NotSelected.__enum__=Fn).TalkSelected=function(e,t){var n=["TalkSelected",1,e,t];return n.__enum__=Fn,n.toString=s,n},Fn.AnnouncementsSelected=["AnnouncementsSelected",2],Fn.AnnouncementsSelected.toString=s,(Fn.AnnouncementsSelected.__enum__=Fn).__empty_constructs__=[Fn.NotSelected,Fn.AnnouncementsSelected];var xn=function(){};(n["albero.entity.TalkSelectionHelper"]=xn).__name__=["albero","entity","TalkSelectionHelper"],xn.eqTalkSelection=function(e,t){var n;if(e[0]==t[0]){var i=xn.getTalkIdOrNull(e),r=xn.getTalkIdOrNull(t);n=null==i&&null==r||null!=i&&null!=r&&i.high==r.high&&i.low==r.low}else n=!1;if(n){var a=xn.getMessageIdOrNull(e),o=xn.getMessageIdOrNull(t);return null==a&&null==o||null!=a&&null!=o&&a.high==o.high&&a.low==o.low}return!1},xn.isSelected=function(e,t){switch(e[1]){case 0:return!1;case 1:e[3];var n=e[2],i=it.orNull(kn.getTalkId(t));return null!=n&&null!=i&&n.high==i.high&&n.low==i.low;case 2:return t==Dn.annoucements}},xn.getTalkIdOrNull=function(e){switch(e[1]){case 0:return null;case 1:return e[2];case 2:return null}},xn.getMessageIdOrNull=function(e){switch(e[1]){case 0:return null;case 1:var t=e[3];return it.orNull(t);case 2:return null}};function Un(e){this.unreadCount=0,null!=e&&(this.id=e.talk_id,this.unreadCount=null!=e.unread_count?e.unread_count:0,this.maxMessageId=e.max_message_id,null!=e.max_message?this.maxMessage=new Ft(e.max_message):this.maxMessage=null,this.maxReadMessageId=e.max_read_message_id,this.maxEveryoneReadMessageId=e.max_everyone_read_message_id,this.talkOrderingTimestamp=e.talk_ordering_timestamp,this.orderInFavorites=e.order_in_favorites,this.favoriteVersion=e.favorite_version,this.pushNotificationSetting=new Jt(e.push_notification))}(n["albero.entity.TalkStatus"]=Un).__name__=["albero","entity","TalkStatus"],Un.prototype={update:function(e){var t=this,n=!1;return this.needIdUpdate(this.maxEveryoneReadMessageId,e.maxEveryoneReadMessageId)&&(this.maxEveryoneReadMessageId=e.maxEveryoneReadMessageId,n=!0),it.foreach(e.maxReadMessageId,function(e){t.needIdUpdate(t.maxReadMessageId,e)&&(t.maxReadMessageId=e,n=!0)}),n},updateByMessageDeletion:function(e){var t=!1;return this.isUnread(e.messageId)&&(this.unreadCount-=1,this.unreadCount<0&&(this.unreadCount=0),t=!0),this.isMax(e.messageId)&&(null!=this.maxMessage&&(this.maxMessage.type=xt.deleted),t=!0),t},updateByMessageReadStatusesUpdate:function(e){var t=e.messageIds.filter(go(this,this.isUnread));if(0==t.length)return!1;for(var n=t[0],i=0;i<t.length;){var r=t[i];++i;var a=n.high-r.high|0;a=0!=a?a:Sa.ucompare(n.low,r.low),(n.high<0?r.high<0?a:-1:0<=r.high?a:1)<0&&(n=r),tt.notContains(e.messageIdsExcludingUnreadCountTargets,r)&&this.unreadCount--}return this.maxReadMessageId=n,!0},needIdUpdate:function(e,t){if(null==t)return!1;if(null==e)return!0;var n=e.high-t.high|0;return n=0!=n?n:Sa.ucompare(e.low,t.low),(e.high<0?t.high<0?n:-1:0<=t.high?n:1)<0},read:function(e,t){this.maxReadMessageId=e,this.unreadCount-=t,this.unreadCount<0&&(this.unreadCount=0)},readAll:function(){this.maxReadMessageId=this.maxMessageId,this.unreadCount=0},updateByMessage:function(e,t){this.isNewMax(e.id)&&(this.maxMessageId=e.id,this.maxMessage=e),e.isUnreadCountTarget&&(t?this.isUnread(e.id)&&this.readAll():this.unreadCount++,this.talkOrderingTimestamp=e.createdAt)},updateByReadingMessages:function(e,n){var t=this;if(null==e||this.canRegardTalkReadCountZero(e)){if(!Pn.isUnreadMesasgeExisted(this))return!1;if(null==this.maxMessageId)return!1;this.readAll()}else{var i=e.filter(function(e){return t.isUnread(e.id)});if(0==i.length)return!1;var r=i.filter(function(e){if(e.isUnreadCountTarget){var t=e.userId;return!(null!=t&&null!=n&&t.high==n.high&&t.low==n.low)}return!1}).length;this.read(i[i.length-1].id,r)}return!0},canRegardTalkReadCountZero:function(e){var t=this.maxMessageId,n=it.orNull(nt.lastOption(e.map(function(e){return e.id})));return null!=t&&null!=n&&t.high==n.high&&t.low==n.low},isMessageAcceptable:function(e,t){if(this.isUnread(e.id))return!0;var n=bt.subTimestampPart(this.maxReadMessageId,e.id),i=n.high-t.high|0;return i=0!=i?i:Sa.ucompare(n.low,t.low),(n.high<0?t.high<0?i:-1:0<=t.high?i:1)<=0},isUnread:function(e){if(null==this.maxReadMessageId)return!0;var t=this.maxReadMessageId,n=t.high-e.high|0;return n=0!=n?n:Sa.ucompare(t.low,e.low),(t.high<0?e.high<0?n:-1:0<=e.high?n:1)<0},isMax:function(e){if(null==this.maxMessageId)return!1;var t=this.maxMessageId;return null!=t&&null!=e&&t.high==e.high&&t.low==e.low},isNewMax:function(e){if(null==this.maxMessageId)return!0;var t=this.maxMessageId,n=t.high-e.high|0;return n=0!=n?n:Sa.ucompare(t.low,e.low),(t.high<0?e.high<0?n:-1:0<=e.high?n:1)<0},__class__:Un};var Pn=function(){};(n["albero.entity.TalkStatusHelper"]=Pn).__name__=["albero","entity","TalkStatusHelper"],Pn.isNotificationDisabled=function(e){return null!=e&&null!=e.pushNotificationSetting&&!e.pushNotificationSetting.enabled},Pn.isFavoriteTalk=function(e){return null!=e&&null!=e.orderInFavorites},Pn.isUnreadMesasgeExisted=function(e){return null!=e&&(null!=e.maxMessage&&e.isUnread(e.maxMessage.id))};function Ln(e){null!=e&&(this.talkId=e.talk_id,this.maxEveryoneReadMessageId=e.max_everyone_read_message_id,this.maxReadMessageId=it.option(e.max_read_message_id))}(n["albero.entity.TalkStatusUpdate"]=Ln).__name__=["albero","entity","TalkStatusUpdate"],Ln.prototype={__class__:Ln};function Bn(e,t,n){this.file=e,this.dimension=Hn.createWithSize(t,n),this.auth=null}(n["albero.entity.ThumbInfo"]=Bn).__name__=["albero","entity","ThumbInfo"],Bn.prototype={setAuth:function(e){this.auth=e},__class__:Bn};var Hn=function(e){null!=e&&(this.width=e.width,this.height=e.height)};(n["albero.entity.ThumbDimension"]=Hn).__name__=["albero","entity","ThumbDimension"],Hn.createWithSize=function(e,t){var n=new Hn;return n.width=e,n.height=t,n},Hn.prototype={toObject:function(){return{width:this.width,height:this.height}},__class__:Hn};function jn(e,t,n){var i=new Kn(0,0);this.domainId=i,this.domainId=e,this.oldSetting=t,this.newSetting=n}(n["albero.entity.UpdateDomainStampSettingEvent"]=jn).__name__=["albero","entity","UpdateDomainStampSettingEvent"],jn.prototype={isValid:function(){return this.newSetting.isNewerThan(this.oldSetting)},getStampsetIdsDiff:function(){return this.oldSetting.getStampsetIdsDiff(this.newSetting)},__class__:jn};var Yn=n["albero.entity.UploadUseType"]={__ename__:["albero","entity","UploadUseType"],__constructs__:["PROFILE_IMAGE","MESSAGE","TALK_ICON","THUMBNAIL","NOTE_ATTACHMENT","NOTE_THUMBNAIL"]};Yn.PROFILE_IMAGE=["PROFILE_IMAGE",0],Yn.PROFILE_IMAGE.toString=s,(Yn.PROFILE_IMAGE.__enum__=Yn).MESSAGE=["MESSAGE",1],Yn.MESSAGE.toString=s,(Yn.MESSAGE.__enum__=Yn).TALK_ICON=["TALK_ICON",2],Yn.TALK_ICON.toString=s,(Yn.TALK_ICON.__enum__=Yn).THUMBNAIL=["THUMBNAIL",3],Yn.THUMBNAIL.toString=s,(Yn.THUMBNAIL.__enum__=Yn).NOTE_ATTACHMENT=["NOTE_ATTACHMENT",4],Yn.NOTE_ATTACHMENT.toString=s,(Yn.NOTE_ATTACHMENT.__enum__=Yn).NOTE_THUMBNAIL=["NOTE_THUMBNAIL",5],Yn.NOTE_THUMBNAIL.toString=s,(Yn.NOTE_THUMBNAIL.__enum__=Yn).__empty_constructs__=[Yn.PROFILE_IMAGE,Yn.MESSAGE,Yn.TALK_ICON,Yn.THUMBNAIL,Yn.NOTE_ATTACHMENT,Yn.NOTE_THUMBNAIL];function Gn(){}(n["albero.entity.UploadUseTypeHelper"]=Gn).__name__=["albero","entity","UploadUseTypeHelper"],Gn.getUseTypeInt=function(e){switch(e[1]){case 0:return 0;case 1:return 1;case 2:return 2;case 3:return 4;case 4:return 5;case 5:return 6}};function zn(e){null!=e&&(null!=e.user_id&&(this.userId=e.user_id),null!=e.email&&(this.email=e.email),null!=e.sub_email&&(this.subEmail=e.sub_email),null!=e.group_alias&&(this.groupAlias=e.group_alias),null!=e.signin_id&&(this.signinId=e.signin_id))}(n["albero.entity.UserIdentifier"]=zn).__name__=["albero","entity","UserIdentifier"],zn.prototype={__class__:zn};var Kn=function(e,t){this.high=e,this.low=t};(n["haxe._Int64.___Int64"]=Kn).__name__=["haxe","_Int64","___Int64"],Kn.prototype={__class__:Kn};function Wn(e,t){this.lastUpdatedAt=t,null!=e&&(this.userId=e.user_id,this.lastUsedAtOpt=it.option(e.last_used_at))}(n["albero.entity.UserPresence"]=Wn).__name__=["albero","entity","UserPresence"],Wn.createUserPresenceState=function(e,t){var n=t.high-e.high|0,i=t.low-e.low|0;if(Sa.ucompare(t.low,e.low)<0){n--;n|=0}var r=new Kn(n,i),a=Wn.SIXTY_MINUTES,o=r.high-a.high|0;if(o=0!=o?o:Sa.ucompare(r.low,a.low),0<(r.high<0?a.high<0?o:-1:0<=a.high?o:1))return Vn.GT_60;var s=Wn.FIFTEEN_MINUTES,l=r.high-s.high|0;return l=0!=l?l:Sa.ucompare(r.low,s.low),0<(r.high<0?s.high<0?l:-1:0<=s.high?l:1)?Vn.LT_OR_EQ_60:Vn.LT_OR_EQ_15},Wn.prototype={toState:function(e){var t=e,n=it.map(this.lastUsedAtOpt,function(e){return Wn.createUserPresenceState(e,t)});switch(n[1]){case 0:return n[2];case 1:return Vn.GT_60}},isExpired:function(e,t){var n=this.lastUpdatedAt,i=e.high-n.high|0,r=e.low-n.low|0;if(Sa.ucompare(e.low,n.low)<0){i--;i|=0}var a=new Kn(i,r),o=a.high-t.high|0;return o=0!=o?o:Sa.ucompare(a.low,t.low),0<(a.high<0?t.high<0?o:-1:0<=t.high?o:1)},__class__:Wn};var Vn=n["albero.entity.UserPresenceState"]={__ename__:["albero","entity","UserPresenceState"],__constructs__:["LT_OR_EQ_15","LT_OR_EQ_60","GT_60"]};Vn.LT_OR_EQ_15=["LT_OR_EQ_15",0],Vn.LT_OR_EQ_15.toString=s,(Vn.LT_OR_EQ_15.__enum__=Vn).LT_OR_EQ_60=["LT_OR_EQ_60",1],Vn.LT_OR_EQ_60.toString=s,(Vn.LT_OR_EQ_60.__enum__=Vn).GT_60=["GT_60",2],Vn.GT_60.toString=s,(Vn.GT_60.__enum__=Vn).__empty_constructs__=[Vn.LT_OR_EQ_15,Vn.LT_OR_EQ_60,Vn.GT_60];function qn(e){this.success=e}(n["albero.entity.api.message.AddFavoriteMessageResult"]=qn).__name__=["albero","entity","api","message","AddFavoriteMessageResult"],qn.prototype={__class__:qn};function Qn(e){this.success=e}(n["albero.entity.api.message.DeleteFavoriteMessageResult"]=Qn).__name__=["albero","entity","api","message","DeleteFavoriteMessageResult"],Qn.prototype={__class__:Qn};function Jn(e,t,n,i,r){this.domainId=e,this.talkId=t,this.marker=n,this.nextMarker=i,this.messages=r}(n["albero.entity.api.message.GetFavoriteMessagesResultWithParams"]=Jn).__name__=["albero","entity","api","message","GetFavoriteMessagesResultWithParams"],Jn.prototype={getNextMarker:function(){return this.nextMarker},getMessages:function(){return this.messages},__class__:Jn};function Xn(e,t,n){this.callerId=e,this.error=t,this.emitterKey=n}(n["albero.entity.api.note.CreateNoteError"]=Xn).__name__=["albero","entity","api","note","CreateNoteError"],Xn.prototype={__class__:Xn};function Zn(e){this.note=new yi(e),this.emitterKey=null}(n["albero.entity.api.note.CreateNoteResult"]=Zn).__name__=["albero","entity","api","note","CreateNoteResult"],Zn.prototype={updateWithEmitterKey:function(e){var t=new Zn;return t.note=this.note,t.emitterKey=e,t},__class__:Zn};function $n(e){this.result=e}(n["albero.entity.api.note.DeleteNoteResult"]=$n).__name__=["albero","entity","api","note","DeleteNoteResult"],$n.prototype={__class__:$n};function ei(e){this.note=new yi(e)}(n["albero.entity.api.note.GetNoteResult"]=ei).__name__=["albero","entity","api","note","GetNoteResult"],ei.prototype={getNoteId:function(){return this.note.noteId},getNoteCreateUserId:function(){return this.note.createdBy},getRevisionCreateUserId:function(){return this.note.getRevisionCreateUserId()},getNoteCreateDate:function(){return this.note.createdAt},getRevisionCreateDate:function(){return this.note.getRevisionCreateDate()},getLockedUserIdWithoutSelf:function(e){return this.note.getLockedUserIdWithoutSelf(e)},__class__:ei};function ti(e){null!=e&&(this.marker=e.marker,this.nextMarker=e.next_marker,this.noteStatuses=nt.asArray(e.contents).map(function(e){return new xi(e)}))}(n["albero.entity.api.note.GetNoteStatusesResult"]=ti).__name__=["albero","entity","api","note","GetNoteStatusesResult"],ti.prototype={isNotEmptyNoteStatuses:function(){return 0<this.noteStatuses.length},__class__:ti};function ni(e){this.note=new yi(e)}(n["albero.entity.api.note.UpdateNoteResult"]=ni).__name__=["albero","entity","api","note","UpdateNoteResult"],ni.prototype={__class__:ni};function ii(e){this.note=new yi(e)}(n["albero.entity.api.note.UpdateNoteSettingResult"]=ii).__name__=["albero","entity","api","note","UpdateNoteSettingResult"],ii.prototype={__class__:ii};function ri(){}(n["albero.entity.file.DummyFileUtil"]=ri).__name__=["albero","entity","file","DummyFileUtil"],ri.getBlobFromUpdatableFile=function(e){return null==e.blob?e:e.blob};function ai(){}(n["albero.entity.file.StageType"]=ai).__name__=["albero","entity","file","StageType"],ai.prototype={__class__:ai};function oi(e,t){this.talkId=e,this.paneType=t}(n["albero.entity.file.StageTypeTalk"]=oi).__name__=["albero","entity","file","StageTypeTalk"],oi.__interfaces__=[ai],oi.prototype={toString:function(){var e=this.talkId;return"staged__"+e.high+"_"+e.low+Yt.toPanePrefix(this.paneType)},isForPane:function(e){return this.paneType==e},isForNote:function(){return!1},isForPreview:function(){return!1},__class__:oi};function si(){}(n["albero.entity.file.StageTypeNote"]=si).__name__=["albero","entity","file","StageTypeNote"],si.__interfaces__=[ai],si.prototype={toString:function(){return"staged_note_"},isForPane:function(e){return!1},isForNote:function(){return!0},isForPreview:function(){return!1},__class__:si};function li(){}(n["albero.entity.message.IFavoriteMessageEvent"]=li).__name__=["albero","entity","message","IFavoriteMessageEvent"],li.prototype={__class__:li};function ui(e){this.message=new Ft(e.message),this.domainId=e.domain_id,this.talkId=e.talk_id}(n["albero.entity.message.AddFavoriteMessageEvent"]=ui).__name__=["albero","entity","message","AddFavoriteMessageEvent"],ui.__interfaces__=[li],ui.prototype={getMessage:function(){return this.message},getMessageId:function(){return this.message.id},isFavorite:function(){return!0},getDomainId:function(){return this.domainId},getTalkId:function(){return this.talkId},__class__:ui};function ci(e){this.messageId=e.message_id,this.domainId=e.domain_id,this.talkId=e.talk_id}(n["albero.entity.message.DeleteFavoriteMessageEvent"]=ci).__name__=["albero","entity","message","DeleteFavoriteMessageEvent"],ci.__interfaces__=[li],ci.prototype={getMessageId:function(){return this.messageId},isFavorite:function(){return!1},__class__:ci};function _i(){}(n["albero.entity.message.IMessageContentForActionReply"]=_i).__name__=["albero","entity","message","IMessageContentForActionReply"],_i.prototype={__class__:_i};var hi=function(e){null!=e&&(this.noteId=new Ti(e.note_id),this.title=e.title,this.revision=e.revision,this.deleted=e.deleted,this.hasAttachments=!!e.has_attachments)};(n["albero.entity.message.MessageContentForNote"]=hi).__name__=["albero","entity","message","MessageContentForNote"],hi.prototype={__class__:hi};var di=function(e){null!=e&&(this.noteId=new Ti(e.note_id),this.title=e.title)};(n["albero.entity.message.MessageContentForNoteDeleted"]=di).__name__=["albero","entity","message","MessageContentForNoteDeleted"],di.prototype={__class__:di};var fi=function(e){this.text=Ra.None,this.stampsetId=tt.fromIntOrInt64(e.stampset_id),this.stampId=tt.fromIntOrInt64(e.stamp_id),null!=e.text&&(this.text=Ra.Some(e.text))};(n["albero.entity.message.MessageContentForOriginalStamp"]=fi).__name__=["albero","entity","message","MessageContentForOriginalStamp"],fi.prototype={hasValidText:function(){return it.isDefined(this.getValidText())},getValidText:function(){return it.filter(this.text,k.isNotEmpty)},__class__:fi};var mi=function(e){this.inReplyTo=e.in_reply_to,this.response=e.response,this.options=e.options,this.listing=null==e.listing||e.listing,this.closingType=null==e.closing_type?1:e.closing_type,this.closed=null!=e.closed&&e.closed};(n["albero.entity.message.MessageContentForSelectOneReply"]=mi).__name__=["albero","entity","message","MessageContentForSelectOneReply"],mi.__interfaces__=[_i],mi.prototype={getResponseIndex:function(){return this.response},__class__:mi};var pi=function(e){this.inReplyTo=e.in_reply_to,this.title=e.title,this.listing=null==e.listing||e.listing,this.closingType=null==e.closing_type?1:e.closing_type,this.done=e.done,this.closed=null!=e.closed&&e.closed};(n["albero.entity.message.MessageContentForTodoReply"]=pi).__name__=["albero","entity","message","MessageContentForTodoReply"],pi.__interfaces__=[_i],pi.prototype={getResponseIndex:function(){return this.done?0:1},__class__:pi};var gi=function(e){this.inReplyTo=e.in_reply_to,this.response=e.response,this.question=e.question,this.listing=null==e.listing||e.listing,this.closingType=null==e.closing_type?1:e.closing_type,this.closed=null!=e.closed&&e.closed};(n["albero.entity.message.MessageContentForYesNoReply"]=gi).__name__=["albero","entity","message","MessageContentForYesNoReply"],gi.__interfaces__=[_i],gi.prototype={getResponseIndex:function(){return this.response?0:1},__class__:gi};var vi=function(e){if(null==e)return this.favorite=!1,this.createdAt=null,void(this.tags=[]);this.favorite=!0,this.createdAt=e.created_at,this.tags=e.tags};(n["albero.entity.message.MessageFavorite"]=vi).__name__=["albero","entity","message","MessageFavorite"],vi.prototype={isFavorite:function(){return this.favorite},update:function(e){this.favorite=e.isFavorite()},__class__:vi};var yi=function(e){null!=e&&(this.noteId=new Ti(e.note_id),this.talkId=e.talk_id,this.createdBy=e.created_by,this.createdAt=e.created_at,this.setting=new Fi(e.setting),this.noteRevision=new Mi(e.note_revision),this.noteLocked=new ki(e.locked))};(n["albero.entity.note.Note"]=yi).__name__=["albero","entity","note","Note"],yi.prototype={isSameNoteId:function(e){return this.noteId.equals(e)},getRevisionCreateUserId:function(){return this.noteRevision.createdBy},getRevisionCreateDate:function(){return this.noteRevision.createdAt},compareRevision:function(e){return this.noteRevision.compareRevision(e)},lock:function(e,t,n,i){this.noteRevision.revision==e&&this.noteLocked.lock(t,n,i)},unlock:function(e,t){this.noteRevision.revision==e&&this.noteLocked.unlock(t)},getLockedUserIdWithoutSelf:function(e){return this.noteLocked.getLockedUserIdWithoutSelf(e)},__class__:yi};var Si=n["albero.entity.note.NoteContentType"]={__ename__:["albero","entity","note","NoteContentType"],__constructs__:["TEXT","FILES"]};Si.TEXT=["TEXT",0],Si.TEXT.toString=s,(Si.TEXT.__enum__=Si).FILES=["FILES",1],Si.FILES.toString=s,(Si.FILES.__enum__=Si).__empty_constructs__=[Si.TEXT,Si.FILES];function wi(){}(n["albero.entity.note.NoteContentTypeHelper"]=wi).__name__=["albero","entity","note","NoteContentTypeHelper"],wi.createNoteContentType=function(e){if(null==e)return Gi._e("["+$e.dateStr(new Date)+"] ","no value.","","","",""),null;switch(e){case 1:return Si.TEXT;case 5:return Si.FILES;default:return Gi._e("["+$e.dateStr(new Date)+"] ","value is not expected.","","","",""),null}},wi.getValue=function(e){if(null==e)return Gi._e("["+$e.dateStr(new Date)+"] ","no content type.","","","",""),null;switch(e[1]){case 0:return 1;case 1:return 5}};var Ti=function(e){this.value=e};(n["albero.entity.note.NoteId"]=Ti).__name__=["albero","entity","note","NoteId"],Ti.__interfaces__=[Dt],Ti.createDummyId=function(){var e,t=Ti.nextDummyId,n=Ti.nextDummyId;if(null==n)e=null;else{var i=new Kn(0,1),r=n.high-i.high|0,a=n.low-i.low|0;if(Sa.ucompare(n.low,i.low)<0){r--;r|=0}e=new Kn(r,a)}return Ti.nextDummyId=e,new Ti(t)},Ti.prototype={toString:function(){var e=this.value;return"_"+e.high+"_"+e.low},equals:function(e){if(null==e)return!1;var t=this.value,n=e.value;return null!=t&&null!=n&&t.high==n.high&&t.low==n.low},getHtmlAttributeId:function(){return"note-"+this.toString()},isDummy:function(){return this.value.high<0},__class__:Ti};var Ii=function(e,t,n,i,r,a){this.state=Ei.SENDING,this.talkId=e,this.noteId=t,this.title=n,this.text=i,this.fileInfos=r,this.emitterKey=a};(n["albero.entity.note.NoteLocalEdit"]=Ii).__name__=["albero","entity","note","NoteLocalEdit"],Ii.prototype={hasEmitterKey:function(){return null!=this.emitterKey},getEmitterKey:function(){return this.emitterKey},setState:function(e){this.state=e},getTalkId:function(){return this.talkId},getNoteId:function(){return this.noteId},getTitle:function(){return this.title},getText:function(){return this.text},getContent:function(){switch(this.getContentType()[1]){case 0:return this.text;case 1:return{files:this.getUploadedFilesData(),text:null==this.text?"":this.text}}},getFileInfos:function(){return this.fileInfos},getState:function(){return this.state},isSending:function(){return this.state==Ei.SENDING},isFailed:function(){switch(this.state[1]){case 0:case 5:return!1;case 1:case 2:case 3:case 4:return!0}},isForCreate:function(){return this.noteId.isDummy()},canNotSend:function(){return 0!=this.getUnuploadedFileInfos().length},getContentType:function(){return 0<this.fileInfos.length?Si.FILES:Si.TEXT},getUnuploadedFileInfos:function(){return this.fileInfos.filter(function(e){return e.isNotUploaded()})},getUploadedFilesData:function(){return this.fileInfos.map(function(e){return e.getUploadedFileData()}).filter(function(e){return null!=e})},createNoteRevisionSummary:function(e){var t=new Ri;return t.revision=0,t.contentType=this.getContentType(),t.title=this.title,t.contentSummary=this.text,t.createdBy=e,t.createdAt=I.nowAsInt64(),t.contentFiles=this.fileInfos,t},conflict:function(){this.state=Ei.FAILED_BY_CONFLICT},deleted:function(){this.state=Ei.FAILED_BY_NOT_FOUND},__class__:Ii};var Ei=n["albero.entity.note.NoteLocalEditState"]={__ename__:["albero","entity","note","NoteLocalEditState"],__constructs__:["SENDING","FAILED_BY_CONFLICT","FAILED_BY_NOT_FOUND","FAILED_BY_FILE","FAILED_BY_UNKNOWN","COMPLETED"]};Ei.SENDING=["SENDING",0],Ei.SENDING.toString=s,(Ei.SENDING.__enum__=Ei).FAILED_BY_CONFLICT=["FAILED_BY_CONFLICT",1],Ei.FAILED_BY_CONFLICT.toString=s,(Ei.FAILED_BY_CONFLICT.__enum__=Ei).FAILED_BY_NOT_FOUND=["FAILED_BY_NOT_FOUND",2],Ei.FAILED_BY_NOT_FOUND.toString=s,(Ei.FAILED_BY_NOT_FOUND.__enum__=Ei).FAILED_BY_FILE=function(e,t){var n=["FAILED_BY_FILE",3,e,t];return n.__enum__=Ei,n.toString=s,n},Ei.FAILED_BY_UNKNOWN=["FAILED_BY_UNKNOWN",4],Ei.FAILED_BY_UNKNOWN.toString=s,(Ei.FAILED_BY_UNKNOWN.__enum__=Ei).COMPLETED=["COMPLETED",5],Ei.COMPLETED.toString=s,(Ei.COMPLETED.__enum__=Ei).__empty_constructs__=[Ei.SENDING,Ei.FAILED_BY_CONFLICT,Ei.FAILED_BY_NOT_FOUND,Ei.FAILED_BY_UNKNOWN,Ei.COMPLETED];function Ni(e){null!=e&&(this.noteId=new Ti(e.note_id),this.revision=e.revision,this.userId=e.user_id,this.deviceId=e.device_id,this.expiredAt=e.expired_at)}(n["albero.entity.note.NoteLockEvent"]=Ni).__name__=["albero","entity","note","NoteLockEvent"],Ni.prototype={__class__:Ni};function Ai(e){this.value=e}(n["albero.entity.note.NoteLockExpiredAt"]=Ai).__name__=["albero","entity","note","NoteLockExpiredAt"],Ai.prototype={fromNow:function(){var e=this.value,t=4294967296,n=e.high,i=e.low;return n*t+(0<=i?i:i+t)-(new Date).getTime()|0},calcRelockDelay:function(){return.9*this.fromNow()|0},__class__:Ai};var bi=n["albero.entity.note.NoteLockStateValue"]={__ename__:["albero","entity","note","NoteLockStateValue"],__constructs__:["FAILED_BY_CONFLICT","FAILED_BY_LOCKED","FAILED_BY_NOT_FOUND","FAILED_BY_UNKNOWN","COMPLETED","RELEASED"]};bi.FAILED_BY_CONFLICT=["FAILED_BY_CONFLICT",0],bi.FAILED_BY_CONFLICT.toString=s,(bi.FAILED_BY_CONFLICT.__enum__=bi).FAILED_BY_LOCKED=function(e){var t=["FAILED_BY_LOCKED",1,e];return t.__enum__=bi,t.toString=s,t},bi.FAILED_BY_NOT_FOUND=["FAILED_BY_NOT_FOUND",2],bi.FAILED_BY_NOT_FOUND.toString=s,(bi.FAILED_BY_NOT_FOUND.__enum__=bi).FAILED_BY_UNKNOWN=["FAILED_BY_UNKNOWN",3],bi.FAILED_BY_UNKNOWN.toString=s,(bi.FAILED_BY_UNKNOWN.__enum__=bi).COMPLETED=function(e){var t=["COMPLETED",4,e];return t.__enum__=bi,t.toString=s,t},bi.RELEASED=["RELEASED",5],bi.RELEASED.toString=s,(bi.RELEASED.__enum__=bi).__empty_constructs__=[bi.FAILED_BY_CONFLICT,bi.FAILED_BY_NOT_FOUND,bi.FAILED_BY_UNKNOWN,bi.RELEASED];function Di(e){this.value=e}(n["albero.entity.note.NoteLockState"]=Di).__name__=["albero","entity","note","NoteLockState"],Di.prototype={isCompleted:function(){return 4==this.value[1]},getExpiredAtOrNull:function(){var e=this.value;return 4!=e[1]?null:e[2]},isLockedByOther:function(){return 1==this.value[1]},getLockedUser:function(){var e=this.value;return 1!=e[1]?null:e[2]},__class__:Di};var ki=function(e){null!=e&&(this.userId=e.user_id,this.deviceId=e.device_id,this.expiredAt=e.expired_at)};(n["albero.entity.note.NoteLocked"]=ki).__name__=["albero","entity","note","NoteLocked"],ki.prototype={lock:function(e,t,n){this.expiredAt=n,this.deviceId=t,this.userId=e},unlock:function(e){var t=this.userId;null!=t&&null!=e&&t.high==e.high&&t.low==e.low&&(this.expiredAt=null,this.userId=null,this.deviceId=null)},getLockedUserIdWithoutSelf:function(e){var t,n=this.deviceId;if(null!=n&&null!=e&&n.high==e.high&&n.low==e.low)return null;if(null!=this.expiredAt){var i=this.expiredAt,r=4294967296,a=i.high,o=i.low;t=a*r+(0<=o?o:o+r)<=(new Date).getTime()}else t=!0;return t?null:this.userId},__class__:ki};function Ci(e){null!=e&&(this.noteId=new Ti(e.note_id),this.talkId=e.talk_id,this.setting=new Fi(e.setting))}(n["albero.entity.note.NotePartialUpdateForSetting"]=Ci).__name__=["albero","entity","note","NotePartialUpdateForSetting"],Ci.prototype={__class__:Ci};function Oi(e){null!=e&&(this.noteId=new Ti(e.note_id),this.talkId=e.talk_id,this.noteRevisionSummary=new Ri(e.note_revision_summary))}(n["albero.entity.note.NotePartialUpdateForSummary"]=Oi).__name__=["albero","entity","note","NotePartialUpdateForSummary"],Oi.prototype={getRevision:function(){return this.noteRevisionSummary.revision},getUpdatedBy:function(){return this.noteRevisionSummary.createdBy},getUpdatedAt:function(){return this.noteRevisionSummary.createdAt},__class__:Oi};var Mi=function(e){if(this.contentFiles=[],null!=e){switch(this.revision=e.revision,this.title=e.title,this.contentType=wi.createNoteContentType(e.content_type),this.contentType[1]){case 0:this.contentText=e.content;break;case 1:if(this.contentText=null==e.content.text?"":e.content.text,null!=e.content.files)for(var t=0,n=Va.__cast(e.content.files,Array);t<n.length;){var i=n[t];++t,this.contentFiles.push(new St(i))}}this.createdBy=e.created_by,this.createdAt=e.created_at}};(n["albero.entity.note.NoteRevision"]=Mi).__name__=["albero","entity","note","NoteRevision"],Mi.prototype={isEmptyTitle:function(){return""==this.title||null==this.title},compareRevision:function(e){return this.revision==e?0:this.revision<e?-1:1},__class__:Mi};var Ri=function(e){if(null!=e&&(this.revision=e.revision,this.title=e.title,this.contentType=wi.createNoteContentType(e.content_type),this.contentSummary=e.content_summary,this.createdBy=e.created_by,this.createdAt=e.created_at,this.contentFiles=[],null!=e.content_files))for(var t=0,n=Va.__cast(e.content_files,Array);t<n.length;){var i=n[t];++t,this.contentFiles.push(new St(i))}};(n["albero.entity.note.NoteRevisionSummary"]=Ri).__name__=["albero","entity","note","NoteRevisionSummary"],Ri.prototype={isEmptyTitle:function(){return""==this.title||null==this.title},compareRevision:function(e){return this.revision==e?0:this.revision<e?-1:1},getContentSummaryWithEllipsis:function(){var e=W.replace(W.replace(this.contentSummary,"- [x] ",""),"- [ ] ","");return e.length<100?e:e.substring(0,99)+"…"},__class__:Ri};var Fi=function(e){null!=e&&(this.collaborativeEditing=e.collaborative_editing,this.version=e.version)};(n["albero.entity.note.NoteSetting"]=Fi).__name__=["albero","entity","note","NoteSetting"],Fi.prototype={__class__:Fi};var xi=function(e){null!=e&&(this.noteId=new Ti(e.note_id),this.noteSummary=new Ui(e.note_summary),this.commentIds=e.comment_ids,this.readUserIds=e.read_user_ids)};(n["albero.entity.note.NoteStatus"]=xi).__name__=["albero","entity","note","NoteStatus"],xi.prototype={getNoteRevisionSummary:function(){return this.noteSummary.noteRevisionSummary},__class__:xi};var Ui=function(e){null!=e&&(this.noteId=new Ti(e.note_id),this.talkId=e.talk_id,this.createdBy=e.created_by,this.createdAt=e.created_at,this.setting=new Fi(e.setting),this.noteRevisionSummary=new Ri(e.note_revision_summary),this.noteLocked=new ki(e.locked))};(n["albero.entity.note.NoteSummary"]=Ui).__name__=["albero","entity","note","NoteSummary"],Ui.prototype={getNoteIdByString:function(){return this.noteId.toString()},getRevisionCreatedAt:function(){return this.noteRevisionSummary.createdAt},getRevisionContentSummary:function(){return this.noteRevisionSummary.contentSummary},getRevisionTitle:function(){return this.noteRevisionSummary.isEmptyTitle()?"":this.noteRevisionSummary.title},getNoteIdJQueryId:function(){return this.noteId.getHtmlAttributeId()},lock:function(e,t,n,i){this.noteRevisionSummary.revision==e&&this.noteLocked.lock(t,n,i)},unlock:function(e,t){this.noteRevisionSummary.revision==e&&this.noteLocked.unlock(t)},__class__:Ui};function Pi(){}(n["albero.entity.note.NoteTextParts"]=Pi).__name__=["albero","entity","note","NoteTextParts"],Pi.isUncheckedCheckBox=function(e){return W.startsWith(e,"- [ ] ")},Pi.isCheckedCheckBox=function(e){return!!W.startsWith(e,"- [x] ")||W.startsWith(e,"- [x] ".toUpperCase())};function Li(e){null!=e&&(this.noteId=new Ti(e.note_id),this.revision=e.revision,this.userId=e.user_id)}(n["albero.entity.note.NoteUnlockEvent"]=Li).__name__=["albero","entity","note","NoteUnlockEvent"],Li.prototype={__class__:Li};function Bi(){}(n["albero.js.KatakanaToRoman"]=Bi).__name__=["albero","js","KatakanaToRoman"],Bi.assureConvertTable=function(){return null!=Bi.convertTable||(Bi.convertTable=new xa,et.iter([["ア","A"],["イ","I"],["ウ","U"],["エ","E"],["オ","O"],["カ","KA"],["キ","KI"],["ク","KU"],["ケ","KE"],["コ","KO"],["キャ","KYA"],["キュ","KYU"],["キョ","KYO"],["サ","SA"],["シ","SI"],["ス","SU"],["セ","SE"],["ソ","SO"],["シャ","SHA"],["シュ","SHU"],["ショ","SHO"],["タ","TA"],["チ","TI"],["ツ","TU"],["テ","TE"],["ト","TO"],["チャ","THA"],["チュ","THU"],["チョ","THO"],["ナ","NA"],["ニ","NI"],["ヌ","NU"],["ネ","NE"],["ノ","NO"],["ニャ","NYA"],["ニュ","NYU"],["ニョ","NYO"],["ハ","HA"],["ヒ","HI"],["フ","FU"],["ヘ","HE"],["ホ","HO"],["ヒャ","HYA"],["ヒュ","HYU"],["ヒョ","HYO"],["マ","MA"],["ミ","MI"],["ム","MU"],["メ","ME"],["モ","MO"],["ミャ","MYA"],["ミュ","MYU"],["ミョ","MYO"],["ヤ","YA"],["ユ","YU"],["ヨ","YO"],["ラ","RA"],["リ","RI"],["ル","RU"],["レ","RE"],["ロ","RO"],["リャ","RYA"],["リュ","RYU"],["リョ","RYO"],["ワ","WA"],["ヲ","O"],["ン","N"],["ガ","GA"],["ギ","GI"],["グ","GU"],["ゲ","GE"],["ゴ","GO"],["ギャ","GYA"],["ギュ","GYU"],["ギョ","GYO"],["ザ","ZA"],["ジ","JI"],["ズ","ZU"],["ゼ","ZE"],["ゾ","ZO"],["ジャ","ZYA"],["ジュ","ZYU"],["ジョ","ZYO"],["ダ","DA"],["ヂ","JI"],["ヅ","ZU"],["デ","DE"],["ド","DO"],["バ","BA"],["ビ","BI"],["ブ","BU"],["ベ","BE"],["ボ","BO"],["ビャ","BYA"],["ビュ","BYU"],["ビョ","BYO"],["パ","PA"],["ピ","PI"],["プ","PU"],["ペ","PE"],["ポ","PO"],["ピャ","PYA"],["ピュ","PYU"],["ピョ","PYO"],["ー",""],["ッ","ッ"]],function(e){var t=Bi.convertTable,n=e[0],i=e[1];null!=No[n]?t.setReserved(n,i):t.h[n]=i})),Bi.convertTable},Bi.matchNext=function(e,t){var n=Bi.assureConvertTable();if(t+1<e.length){var i=e.substring(t,t+2),r=null!=No[i]?n.getReserved(i):n.h[i];if(null!=r)return Hi.MatchedToTwoCharsKey(r)}if(t<e.length){var a=e.substring(t,t+1),o=null!=No[a]?n.getReserved(a):n.h[a];if(null!=o)return Hi.MatchedToOneCharKey(o)}var s=t<e.length?e.substring(t,t+1):"";return Hi.NotMatched(s)},Bi.prototype={convert:function(e){for(var t=0,n="";t<e.length;){var i=Bi.matchNext(e,t);switch(i[1]){case 0:t+=2,n+=i[2];break;case 1:++t,n+=i[2];break;case 2:++t,n+=i[2]}}return n=(n=n.replace(Bi.TU_REG.r,"$1$1")).replace(Bi.XTU_REG.r,"XTU")},__class__:Bi};var Hi=n["albero.js.ResultOfMatchNext"]={__ename__:["albero","js","ResultOfMatchNext"],__constructs__:["MatchedToTwoCharsKey","MatchedToOneCharKey","NotMatched"]};Hi.MatchedToTwoCharsKey=function(e){var t=["MatchedToTwoCharsKey",0,e];return t.__enum__=Hi,t.toString=s,t},Hi.MatchedToOneCharKey=function(e){var t=["MatchedToOneCharKey",1,e];return t.__enum__=Hi,t.toString=s,t},Hi.NotMatched=function(e){var t=["NotMatched",2,e];return t.__enum__=Hi,t.toString=s,t},Hi.__empty_constructs__=[];var ji=function(e){this.isDirty=!1,this.key=e};(n["albero.js.LocalStorage"]=ji).__name__=["albero","js","LocalStorage"],ji.getLocalStorage=function(){return new(require("node-localstorage").LocalStorage)(null!=Eo.storagePath?Eo.storagePath:"./storage.local",null!=Eo.storageQuota?K.parseInt(Eo.storageQuota):null)},ji.prototype={load:function(){var e=this.val();if(null==e||""==e)return null;var t=null;try{t=Aa.run(e),this.isDirty=!1}catch(e){e instanceof Wa&&(e=e.val),Gi._w("["+$e.dateStr(new Date)+"] ",e,"","","","")}return t},save:function(e){try{this.val(Ia.run(e)),this.isDirty=!1}catch(e){e instanceof Wa&&(e=e.val),Gi._w("["+$e.dateStr(new Date)+"] ",e,"","","","")}},setDirtyFlag:function(){if(!this.isDirty)try{this.val(""),this.isDirty=!0}catch(e){e instanceof Wa&&(e=e.val),Gi._w("["+$e.dateStr(new Date)+"] ",e,"","","","")}},val:function(e){var t=ji.getLocalStorage();return null!=t&&(null==e?e=t.getItem(this.key):""==e?t.removeItem(this.key):t.setItem(this.key,e)),e},__class__:ji};var Yi=function(){};(n["albero.js.Localizer"]=Yi).__name__=["albero","js","Localizer"],Yi.setLocalizeForMock=function(e,t){null==Yi.mock&&(Yi.mock=new xa);var n=Yi.mock;null!=No[e]?n.setReserved(e,t):n.h[e]=t},Yi.setLocalizeValueForMock=function(e,t){Yi.setLocalizeForMock(e,function(e){return t})},Yi.localizeForMock=function(e,t){if(null==Yi.mock)return null;var n=Yi.mock,i=null!=No[e]?n.getReserved(e):n.h[e];return null==i?null:i(t)},Yi.runOrReserve=function(e){e()},Yi.localize=function(e,t){return""},Yi.asyncPrepare=function(){return Promise.resolve()};var Gi=e.AlberoLog=function(){};(n.AlberoLog=Gi).__name__=["AlberoLog"],Gi.getLogLevel=function(e){switch(e=null!=e?e.toUpperCase():"INFO"){case"ALERT":return 1;case"CRITICAL":return 2;case"EMERGENCY":return 0;case"ERROR":return 3;case"INFO":return 6;case"NOTICE":return 5;case"WARNING":return 4;default:return 7}},Gi._nop=function(){},Gi.dateStr=function(){return"["+$e.dateStr(new Date)+"] "};function zi(e,t,n){this.ignoreCase=t,this.normalizeFunc=n,t&&(e=e.toUpperCase()),this.normalizedPattern=n(e)}(n["albero.js.NFKCTextSearch"]=zi).__name__=["albero","js","NFKCTextSearch"],zi.prototype={search:function(e){var t=new T,n=[];this.ignoreCase&&(e=e.toUpperCase()),this.normalize(e,t,n);for(var i,r=0,a=[],o=t.b;-1!=(i=o.indexOf(this.normalizedPattern,r));){r=i+this.normalizedPattern.length;for(var s=n[i],l=n[r-1],u=null,c=r,_=n.length;c<_;){if(l!=(u=n[c++]))break;u=null}null==u&&(u=e.length),a.push(new Ki(s,u))}return a},normalize:function(e,t,n){for(var i=e.length,r=new T,a=0,o=0,s=i;o<s;){var l=o++,u=r.b.length,c=r.b,_=c+e.charAt(l),h=this.normalizeFunc(_);if(_!=h)if(W.startsWith(h,c)){var d=c.substring(0,u);t.b+=K.string(d),r=new T;var f=h.substring(u,h.length);r.b+=K.string(f);for(var m=0,p=u;m<p;){m++;n.push(a)}a=l}else(r=new T).b+=null==h?"null":""+h;else{t.b+=K.string(r),r=new T;var g=e.charAt(l);r.b+=K.string(g);for(var v=0,y=u;v<y;){v++;n.push(a)}a=l}}t.b+=K.string(r.b);for(var S=0,w=r.b.length;S<w;){S++;n.push(a)}},__class__:zi};var Ki=function(e,t){this.start=e,this.end=t};(n["albero.js.HitSpan"]=Ki).__name__=["albero","js","HitSpan"],Ki.prototype={__class__:Ki};function Wi(){}(n["albero.js.PromiseHelper"]=Wi).__name__=["albero","js","PromiseHelper"],Wi.resolveVoid=function(e){e()},Wi.delay=function(n){return new Promise(function(e,t){Ea.delay(function(){Wi.resolveVoid(e)},n)})};function Vi(){}(n["albero.js.ProxyHelper"]=Vi).__name__=["albero","js","ProxyHelper"],Vi.createAgent=function(e){var t=Za.parse(e),n={host:t.hostname};null!=t.port&&(n.port=K.parseInt(t.port)),null!=t.auth&&(n.proxyAuth=t.auth);var i=require("tunnel-agent");return("https:"==t.protocol?i.httpsOverHttps:i.httpsOverHttp)({proxy:n})};function qi(){}(n["albero.js.SettingsResolver"]=qi).__name__=["albero","js","SettingsResolver"],qi.get=function(e,t){return null!=e?e:t},qi.getAcceptableEventTimeDiff=function(){return Ta.parseString(qi.get(Eo.acceptableEventTimeDiff,"10000"))};var Qi=function(){};(n["albero.js.TextCanonicalizer"]=Qi).__name__=["albero","js","TextCanonicalizer"],Qi.canonicalize=function(e){return Qi.basicLatinAlphabetToUpperCase(Qi.hiraganaToKatakana(Qi.normalize(Qi.eraseInvisible(e))))},Qi.canonicalizeForRoman=function(e){return Qi.basicLatinAlphabetToUpperCase(Qi.katakanaToRoman(Qi.hiraganaToKatakana(Qi.normalize(Qi.eraseInvisible(e)))))},Qi.basicLatinAlphabetToUpperCase=function(e){return e.toUpperCase()},Qi.hiraganaToKatakana=function(e){for(var t=0,n="",i=0,r=e.length;i<r;){var a=i++,o=$e.cca(e,a);o>=Qi.HIRAGANA_SMALL_A&&o<=Qi.HIRAGANA_NN&&(n+=e.substring(t,a),n+=String.fromCharCode(o+(Qi.KATAKANA_SMALL_A-Qi.HIRAGANA_SMALL_A)),t=1+a)}return n+=e.substring(t,e.length)},Qi.katakanaToRoman=function(e){return(new Bi).convert(e)},Qi.normalize=function(e){return new Ji(null).normalize(e)},Qi.normalizeForFile=function(e){return new Ji(null).normalizeForFile(e)},Qi.asyncAssureNormalize=function(){return Promise.resolve()},Qi.eraseInvisible=function(e){var t=new RegExp("[\\u0000-\\u0020 ]","g".split("u").join(""));return e.replace(t,"")};var Ji=function(e){this.beforeTask=null,this.beforeTask=e};(n["albero.js.Normalizer"]=Ji).__name__=["albero","js","Normalizer"],Ji.prototype={normalize:function(e){try{return null!=this.beforeTask&&this.beforeTask(),e.normalize("NFKC")}catch(e){return e instanceof Wa&&(e=e.val),Gi._e("["+$e.dateStr(new Date)+"] ","invalid character:",e,"","",""),Yi.localize("TextCanonicalizer.invalid")}},normalizeForFile:function(e){try{return null!=this.beforeTask&&this.beforeTask(),e.normalize("NFC")}catch(e){return e instanceof Wa&&(e=e.val),Gi._e("["+$e.dateStr(new Date)+"] ","invalid character:",e,"","",""),Yi.localize("TextCanonicalizer.invalid")}},__class__:Ji};function Xi(){}(n["albero.js.WebSocket"]=Xi).__name__=["albero","js","WebSocket"],Xi.prototype={__class__:Xi};function Zi(){}(n["albero.js.WebSocketFactory"]=Zi).__name__=["albero","js","WebSocketFactory"],Zi.newInstance=function(e,t){return new $i(e,t)};var $i=function(e,t){var n=this;this.onopen=t.onopen,this.onmessage=t.onmessage,this.onerror=null,this.onclose=t.onclose,this.onpong=t.onpong;var i=Eo.wsConfig,r=require("websocket").client;this.ws=new r(i),this.ws.on("connectFailed",go(this,this.onError)),this.ws.on("connect",function(e){(n.connection=e).on("error",go(n,n.onError)),e.on("close",go(n,n.onConnectionClose)),e.on("message",go(n,n.onMessage)),e.on("pong",go(n,n.onPong)),n.onOpen(null)});var a=null;null!=Eo.proxyURL&&(a={agent:Vi.createAgent(Eo.proxyURL)}),this.ws.connect(e,null,null,null,a)};(n["albero.js.WebSocketForNodeJs"]=$i).__name__=["albero","js","WebSocketForNodeJs"],$i.__interfaces__=[Xi],$i.prototype={onOpen:function(e){Gi._i("["+$e.dateStr(new Date)+"] ","WebSocket opened.","","","",""),null!=this.onopen&&this.onopen()},onMessage:function(e){if(null!=this.onmessage){var t;t=this.getBinaryDataForHubot(e),this.onmessage(t)}},getBinaryDataForHubot:function(e){return Ua.ofData(e.binaryData)},onPong:function(e){null!=this.onpong&&this.onpong(e)},onError:function(e){Gi._e("["+$e.dateStr(new Date)+"] ","WebSocket error. event:",e,"","",""),null!=this.onerror&&this.onerror()},onClose:function(e){this.removeAllEventListenersForHubot();var t="WebSocket closed. "+K.string(e.code)+" "+K.string(e.reason)+" "+K.string(e.wasClean);Gi._i("["+$e.dateStr(new Date)+"] ",t,"","","",""),null!=this.onclose&&this.onclose(e.code,e.reason,e.wasClean)},removeAllEventListenersForHubot:function(){null!=this.ws&&(this.ws.removeAllListeners(),this.ws=null),null!=this.connection&&(this.connection.removeAllListeners(),this.connection=null)},onConnectionClose:function(e,t){this.onClose({code:e,reason:t})},close:function(){if(this.onopen=null,this.onmessage=null,this.onerror=null,this.onclose=null,this.onpong=null,!this.isClosed()){var e=this.connection;this.onConnectionClose(1e3,"Normal connection closure"),e.close()}},send:function(e){this.isClosed()||this.connection.sendBytes(new $a(e.b.bufferValue))},ping:function(e){this.connection.ping(e)},isClosed:function(){return null==this.ws||null==this.connection||!this.connection.connected},__class__:$i};function er(){}(n["puremvc.interfaces.IProxy"]=er).__name__=["puremvc","interfaces","IProxy"],er.prototype={__class__:er};function tr(){}(n["albero.proxy.AccessTokenResolverProxy"]=tr).__name__=["albero","proxy","AccessTokenResolverProxy"],tr.__interfaces__=[er],tr.prototype={__class__:tr};var nr=function(){};(n["albero.proxy.AccessTokenResolverProxyFactory"]=nr).__name__=["albero","proxy","AccessTokenResolverProxyFactory"],nr.newInstance=function(){return new rr("accessTokenResolver")};var ir=function(e,t){x.call(this),this.proxyName=null!=e?e:ir.NAME,null!=t&&this.setData(t)};(n["puremvc.patterns.proxy.Proxy"]=ir).__name__=["puremvc","patterns","proxy","Proxy"],ir.__interfaces__=[er],ir.__super__=x,ir.prototype=i(x.prototype,{getProxyName:function(){return this.proxyName},setData:function(e){this.data=e},getData:function(){return this.data},onRegister:function(){},onRemove:function(){},__class__:ir});var rr=function(e){ir.call(this,e)};(n["albero.proxy.AccessTokenResolverProxyForDirectJsHubot"]=rr).__name__=["albero","proxy","AccessTokenResolverProxyForDirectJsHubot"],rr.__interfaces__=[tr],rr.__super__=ir,rr.prototype=i(ir.prototype,{asyncGetAccessToken:function(e,t){var n=this.settings.getAccessToken();if(null==n){var i=null!=Eo.account?Eo.account.split(":"):null;null==i||2!=i.length?null!=(e=null==e?this.accountLoader.load():e)&&(null!=e.accessToken?(this.settings.setAccessToken(e.accessToken),t(e.accessToken)):this.api.createAccessToken(e.email,e.pass,t)):this.api.createAccessToken(i[0],i[1],t)}else t(n)},__class__:rr});function ar(){}(n["albero.proxy.AccountLoaderProxy"]=ar).__name__=["albero","proxy","AccountLoaderProxy"],ar.__interfaces__=[er],ar.prototype={__class__:ar};var or=function(){};(n["albero.proxy.AccountLoaderProxyFactory"]=or).__name__=["albero","proxy","AccountLoaderProxyFactory"],or.newInstance=function(){var e=ee.resolveClass("albero.debug.proxy.AccountLoaderProxyImpl");return null!=e?ee.createInstance(e,["accountLoader"]):new sr("accountLoader")};var sr=function(e){ir.call(this,e)};(n["albero.proxy.AccountLoaderProxyForHubot"]=sr).__name__=["albero","proxy","AccountLoaderProxyForHubot"],sr.__interfaces__=[ar],sr.__super__=ir,sr.prototype=i(ir.prototype,{load:function(){var i=this,t=require("read");return t({prompt:"Email: "},function(e,n){t({prompt:"Password: ",silent:!0},function(e,t){i.sendNotification("SignIn",new De(n,t))})}),null},__class__:sr});var lr=function(){ir.call(this,"broadcast")};(n["albero.proxy.AlberoBroadcastProxy"]=lr).__name__=["albero","proxy","AlberoBroadcastProxy"],lr.__super__=ir,lr.prototype=i(ir.prototype,{handleNotification:function(e,t,n){var i=this;switch(Gi._d("["+$e.dateStr(new Date)+"] ","Receive request from server. name:",e," body:",t,""),e){case"notify_add_account_control_request":var r=new ot(t);this.dataStore.setAccountControlRequest(r),this.sendNotification(e,r),n();break;case"notify_add_acquaintance":this.sendNotification(e,this.dataFactory.newAcquaintance(t[1])),n();break;case"notify_add_acquaintances":for(var a=t[1].map(go(mo=this.dataFactory,mo.newAcquaintance)),o=0;o<a.length;){var s=a[o];++o,this.sendNotification("notify_add_acquaintance",s)}this.sendNotification(e,a),n();break;case"notify_add_domain_invite":var l=new ht(t);this.dataStore.setDomainInvite(l),this.sendNotification(e,l),n();break;case"notify_add_favorite_message":var u=new ui(t);this.messageStore.onAddFavoriteMessage(u),this.sendNotification(e,u),n();break;case"notify_add_favorite_talk":var c=new yt(t);this.updateTalkStatusByFavoriteTalkEvent(c),this.sendNotification(e,c),n();break;case"notify_add_friend":this.sendNotification(e,this.dataFactory.newFriend(t[1])),n();break;case"notify_add_talkers":var _=new Nn(t);null==this.dataStore.getTalk(_.id)&&this.sendNotification("notify_add_talkers_including_me",_),this.dataStore.setTalk(_),this.sendNotification(e,_),n();break;case"notify_close_conference":var h=new ut(t);this.conferenceStore.removeConference(h),this.updateTalkStatusByConferenceClosedEvent(h),this.sendNotification(e,h),n();break;case"notify_conference_participant_join":var d,f=t[3],m=t[4],p=this.dataStore;if(null!=p.me){var g=p.me.id;d=null!=g&&null!=m&&g.high==m.high&&g.low==m.low}else d=!1;d&&this.dataStore.addReactedConfereceId(f),this.sendNotification(e,t),n();break;case"notify_conference_participant_reject":var v=t[3];this.dataStore.addReactedConfereceId(v),this.sendNotification(e,t),n();break;case"notify_create_announcement":var y=new st(t);this.keywordWatcher.onAnnouncementCreated(y),this.sendNotification("notify_update_announcement_status",this.newAnnouncementStatus(y)),this.sendNotification(e,y),n();break;case"notify_create_message":var S=new Ft(t);this.messageStore.setMessage(S),this.keywordWatcher.onMessageCreated(S);var w=this.newTalkStatusByMessage(S);switch(null!=w&&this.sendNotification("notify_update_local_talk_status",w),S.type[1]){case 0:var T=S.content,I=null;switch(T.type){case"delete_talker":I=T.deleted_user_id;break;case"hide_pair_talk":I=T.user_id}if(null==I)return this.sendNotification(e,S),void n();for(var E=S.talkId,N=this.dataStore.getQuestions(E,I),A=0;A<N.length;){var b=N[A];++A,b.closed=!0,this.sendNotification("notify_update_question",b)}this.sendNotification(e,S),n();break;case 4:if(null!=S.content.file_id){var D=[St.fromMessageAndFile(S,S.content)];this.fileInfoStore.setMessageFileInfos(S.id,D),et.iter(D,function(e){i.fileInfoStore.setTalkFileInfo(e,!1),i.sendNotification("notify_create_attachment",e)})}this.sendNotification(e,S),n();break;case 5:var k=S,C=nt.asArray(S.content.files).map(function(e){return St.fromMessageAndFile(k,e)});this.fileInfoStore.setMessageFileInfos(S.id,C),et.iter(C,function(e){i.fileInfoStore.setTalkFileInfo(e,!1),i.sendNotification("notify_create_attachment",e)}),this.sendNotification(e,S),n();break;case 13:case 15:case 17:var O=this.dataStore.getTalk(S.talkId);null!=O&&this.sendNotification("notify_update_question",this.dataStore.setQuestion(Xt.fromMessageAndTalk(S,O))),this.sendNotification(e,S),n();break;case 14:case 16:case 18:case 19:case 20:case 21:var M=S.content.in_reply_to,R=this.dataStore.getTalk(S.talkId),F=this.dataStore.getQuestion(M);if(null!=R&&null!=F){var x,U=this.dataStore,P=S.userId;if(null!=U.me){var L=U.me.id;x=null!=L&&null!=P&&L.high==P.high&&L.low==P.low}else x=!1;F.updateByMessage(S,x),this.sendNotification("notify_update_question",F),S.isClosedActionStampMessage()&&this.messageStore.onActionStampClose(M),this.sendNotification(e,S),n()}else this.sendNotification(e,S),n();break;default:this.sendNotification(e,S),n()}break;case"notify_create_note":var B=new Ui(t);this.dataStore.setNoteRevisionSummary(B.noteId,B.noteRevisionSummary),this.sendNotification(e,B),n();break;case"notify_create_group_talk":case"notify_create_pair_talk":var H=new Nn(t);this.dataStore.setTalk(H),this.newTalkStatusByTalk(H),this.sendNotification(e,H),n();break;case"notify_delete_account_control_request":var j=tt.fromIntOrInt64(t);this.dataStore.removeAccountControlRequest(j),this.sendNotification(e,j),n();break;case"notify_delete_acquaintance":this.dataStore.removeAcquaintance(t[0],t[1]),this.sendNotification(e,t),n();break;case"notify_delete_acquaintances":for(var Y=t[0],G=t[1],z=0;z<G.length;){var K=G[z];++z,this.dataStore.removeAcquaintance(Y,K),this.sendNotification("notify_delete_acquaintance",[Y,K])}this.sendNotification(e,t),n();break;case"notify_delete_announcement":var W=t[0],V=t[1],q=this.dataStore.getAnnouncementStatus(W);null!=q&&q.updateByAnnouncementDeletion(V)&&this.dataStore.setAnnouncementStatus(q),this.sendNotification(e,t),n();break;case"notify_delete_attachment":var Q=new Tt(t);this.messageStore.onFileDeleted(Q),this.fileInfoStore.onFileDeleted(Q),this.sendNotification(e,Q),n();break;case"notify_delete_domain_invite":var J=t;this.dataStore.removeDomainInvite(J),this.sendNotification(e,J),n();break;case"notify_delete_favorite_message":var X=new ci(t);this.messageStore.onDeleteFavoriteMessage(X),this.sendNotification(e,X),n();break;case"notify_delete_favorite_talk":var Z=new yt(t);this.updateTalkStatusByFavoriteTalkEvent(Z),this.sendNotification(e,Z),n();break;case"notify_delete_friend":this.dataStore.removeFriend(t[0],t[1]),this.sendNotification(e,t),n();break;case"notify_delete_message":var $=new Ut(t);it.foreach(this.messageStore.getMessage($.messageId),function(e){e.type=xt.deleted,e.content=""});var ee=this.updateTalkStatusOnMessageDelete($);null!=ee&&this.sendNotification("notify_update_local_talk_status",ee),this.sendNotification(e,$),n();break;case"notify_delete_note":var te=new Ti(t);this.dataStore.setNote(te,null),this.dataStore.setNoteRevisionSummary(te,null);var ne=this.dataStore.getNoteLocalEdit(te);null!=ne&&ne.deleted(),this.sendNotification(e,te),n();break;case"notify_delete_stampset":var ie=t;et.iter(this.dataStore.getDomains(),function(e){e.deleteStampsetInfo(ie)}),this.stampsStore.removeStampsetInfo(ie),this.sendNotification(e,ie),n();break;case"notify_delete_talk":var re=t;this.dataStore.removeTalk(re),this.dataStore.removeTalkStatus(re),this.conferenceStore.removeConferencesOnLeaveTalk(re),this.sendNotification("brand_badge_changed"),this.sendNotification(e,t),n();break;case"notify_disable_push_notification":var ae=new Rn(t);this.updateTalkStatusByTalkPushNotificationEvent(!1,ae),this.sendNotification(e,ae),n();break;case"notify_enable_push_notification":var oe=new Rn(t);this.updateTalkStatusByTalkPushNotificationEvent(!0,oe),this.sendNotification(e,oe),n();break;case"notify_flow_notification_badge":var se=new It(t);this.dataStore.setFlowNotificationBadge(se.domainId,se),this.sendNotification(e,se),n();break;case"notify_join_account_control_group":var le=new rt(t);this.dataStore.setAccountControlGroup(le),this.dataStore.removeAccountControlRequests(),this.sendNotification("brand_badge_changed"),this.sendNotification(e,le),n();break;case"notify_join_domain":var ue=this.dataStore.setDomainIfLatest(new ct(t));ct.isAllowReadAnnouncement(ue)&&Ea.delay(function(){i.api.getAnnouncementStatus(ue.id)},500),this.sendNotification(e,[null,ue]),n();break;case"notify_leave_account_control_group":var ce=t;this.dataStore.removeAccountControlGroup(ce),this.sendNotification(e,ce),n();break;case"notify_leave_domain":var _e=t;this.dataStore.removeDomain(_e),this.conferenceStore.removeConferencesOnLeaveDomain(_e),this.sendNotification(e,_e),n();break;case"notify_lock_note":var he=new Ni(t),de=this.dataStore.getNote(he.noteId);null!=de&&de.lock(he.revision,he.userId,he.deviceId,he.expiredAt),this.sendNotification(e,he),n();break;case"notify_open_conference":var fe=this.dataFactory.newConference(t);this.sendNotification(e,fe),n();break;case"notify_unlock_note":var me=new Li(t),pe=this.dataStore.getNote(me.noteId);null!=pe&&pe.unlock(me.revision,me.userId),this.sendNotification(e,me),n();break;case"notify_update_account_control_group_partially":var ge=new at(t);this.dataStore.updateAccountControlGroup(ge),this.sendNotification(e,ge),n();break;case"notify_update_announcement_status":var ve=new lt(t),ye=this.dataStore.getAnnouncementStatus(ve.domainId);null==ye&&(ye=this.assureAnnouncementStatus(ve.domainId)),ye.updateReadWithStatusUpdate(ve),this.dataStore.setAnnouncementStatus(ye),this.sendNotification(e,ve),n();break;case"notify_update_department_tree":var Se=t;this.departmentStore.clearDomainDepartment(Se),this.api.getDepartmentTree(Se),this.sendNotification(e,Se),n();break;case"notify_update_department_users":var we=t;this.departmentStore.clearDomainDepartmentUsers(we),this.api.getUsers(we,this.dataStore.getFriendsOrAcquaintances(we).map(function(e){return e.id})),this.api.getMe(),this.sendNotification(e,we),n();break;case"notify_update_domain":var Te=new ct(t),Ie=this.dataStore.getDomain(Te.id),Ee=this.dataStore.setDomainIfLatest(Te);if(null!=Ie&&ct.isAllowReadAnnouncement(Ie)&&!ct.isAllowReadAnnouncement(Ee)){this.dataStore.removeAnnouncementStatus(Ie.id);var Ne=new lt;Ne.domainId=Ee.id,this.sendNotification("notify_update_announcement_status",Ne)}if(!ct.isAllowReadAnnouncement(Ie)&&ct.isAllowReadAnnouncement(Ee)&&this.api.getAnnouncementStatus(Ee.id),ct.isChangedContractTreeEnabled(Ie,Ee)&&!ct.isDepartmentEnabled(Ee)){var Ae=Ee.id;this.departmentStore.clearDomainDepartment(Ae),this.dataStore.clearUsersDepartments(Ae)}this.sendNotification(e,[Ie,Ee]),n();break;case"notify_update_domain_stampsetting":var be=t[0],De=this.dataStore.getDomain(be);if(null!=De){var ke=De.stampsetSetting;De.updateStampsetSetting(new Tn(t[1]));var Ce=De.stampsetSetting,Oe=new jn(be,ke,Ce);Oe.isValid()&&this.sendNotification(e,Oe)}n();break;case"notify_update_domain_users":for(var Me=t,Re=0;Re<Me.length;){var Fe=Me[Re];++Re;var xe=this.dataStore.getDomain(Fe);null!=xe&&xe.setting.contactTreeEnabled&&this.departmentStore.clearDomainDepartmentUsers(Fe)}this.sendNotification(e,t),n();break;case"notify_delete_talker":case"notify_update_group_talk":var Ue=new Nn(t);this.dataStore.setTalk(Ue),this.sendNotification(e,Ue),n();break;case"notify_update_note_partially":if(null==t)return void Gi._e("["+$e.dateStr(new Date)+"] ","notePartiallyUpdate is null.","","","","");if(null==t.note_id)return void Gi._e("["+$e.dateStr(new Date)+"] ","noteId is null.","","","","");var Pe=new Ti(t.note_id),Le=this.dataStore.getNote(Pe);if(null!=Le&&null!=t.note_revision_summary&&Le.compareRevision(t.note_revision_summary.revision)<=-1&&this.dataStore.setNote(Pe,null),null==t.note_revision_summary&&null==t.setting)return void Gi._e("["+$e.dateStr(new Date)+"] ","noteSetting and noteRevisionSummary are null.","","","","");if(null!=t.setting&&this.sendNotification("notify_update_note_for_setting",new Ci(t)),null!=t.note_revision_summary){var Be=new Oi(t),He=this.dataStore.getNoteRevisionSummary(Pe);if(null!=He&&He.compareRevision(Be.getRevision())<0){var je=this.dataStore.getNoteLocalEdit(Pe);null!=je&&je.conflict(),this.dataStore.setNoteRevisionSummary(Pe,Be.noteRevisionSummary),this.sendNotification("notify_update_note_for_revision",new Oi(t))}}n();break;case"notify_update_read_statuses":var Ye=new Lt(t),Ge=this.updateTalkStatus(Ye);null!=Ge&&this.sendNotification("notify_update_local_talk_status",Ge),this.sendNotification(e,Ye),n();break;case"notify_update_stampset":var ze=new wn(t);et.iter(this.dataStore.getDomains(),function(e){e.updateStampsetInfo(ze)}),this.stampsStore.updateStampsetInfo(ze),this.sendNotification(e,ze),n();break;case"notify_update_talk_status":var Ke=new Ln(t),We=this.dataStore.getTalkStatus(Ke.talkId);null!=We&&We.update(Ke)&&(this.dataStore.setTalkStatus(We),this.sendNotification("notify_update_local_talk_status",We)),this.sendNotification(e,Ke),n();break;case"notify_update_user":if(t instanceof Array&&null==t.__enum__){var Ve=this.dataFactory.newDomainUser(t[1]);this.dataStore.setUserIfLatest(null,Ve)}else{var qe=new Rt(t);Gi._d("["+$e.dateStr(new Date)+"] ","Current user updated. user:",qe,"","","");var Qe=this.dataStore;Qe.me=qe;for(var Je=0,Xe=Qe.getDomains();Je<Xe.length;){var Ze=Xe[Je];++Je,Qe.sendNotification("notify_update_user",Qe.me.toDomainUser(Ze.id))}Qe.sendNotification("current_user_changed",qe),Qe.storage.setDirtyFlag()}n();break;default:this.sendNotification(e,t),n()}},updateTalkStatusByFavoriteTalkEvent:function(e){var t=this.dataStore.getTalkStatus(e.talkId);if(null==t){var n=this.dataStore.getTalk(e.talkId);if(null==n)return void Gi._e("["+$e.dateStr(new Date)+"] ","talk not found on change favorite talk.","","","","");(t=new Un).id=e.talkId,t.talkOrderingTimestamp=n.updatedAt}(null==t.favoriteVersion||e.favoriteVersion>t.favoriteVersion)&&(t.favoriteVersion=e.favoriteVersion,t.orderInFavorites=e.orderInFavorites,this.dataStore.setTalkStatus(t))},updateTalkStatusByConferenceClosedEvent:function(e){var t=this.dataStore.getTalkStatus(e.talkId);if(null!=t&&null!=t.maxMessage){var n=t.maxMessage.id,i=e.messageId;null!=n&&null!=i&&n.high==i.high&&n.low==i.low&&(t.maxMessage.content.closed=!0,this.dataStore.setTalkStatus(t))}},updateTalkStatusByTalkPushNotificationEvent:function(e,t){var n=this.dataStore.getTalkStatus(t.talkId);if(null==n){var i=this.dataStore.getTalk(t.talkId);if(null==i)return void Gi._e("["+$e.dateStr(new Date)+"] ","talk not found on change favorite talk.","","","","");(n=new Un).id=t.talkId,n.talkOrderingTimestamp=i.updatedAt}(null==n.pushNotificationSetting||t.version>n.pushNotificationSetting.version)&&(n.pushNotificationSetting=Jt.createWithParams(e,t.version),this.dataStore.setTalkStatus(n))},newTalkStatusByTalk:function(e){var t=this.dataStore.getTalkStatus(e.id);return null==t&&((t=new Un).id=e.id),null==t.talkOrderingTimestamp&&(t.talkOrderingTimestamp=e.updatedAt),this.dataStore.setTalkStatus(t),t},newTalkStatusByMessage:function(e){var t=this.dataStore.getTalkStatus(e.talkId);null==t&&((t=new Un).id=e.talkId);var n,i=this.dataStore,r=e.userId;if(null!=i.me){var a=i.me.id;n=null!=a&&null!=r&&a.high==r.high&&a.low==r.low}else n=!1;return t.updateByMessage(e,n),this.dataStore.setTalkStatus(t),t},updateTalkStatusOnMessageDelete:function(e){var t=this.dataStore.getTalkStatus(e.talkId);return null!=t&&t.updateByMessageDeletion(e)&&this.dataStore.setTalkStatus(t),t},updateTalkStatus:function(e){var i=this;if(!et.exists(e.readUserIds,function(e){var t=i.dataStore;if(null==t.me)return!1;var n=t.me.id;return null!=n&&null!=e&&n.high==e.high&&n.low==e.low}))return null;var t=this.dataStore.getTalkStatus(e.talkId);return null==t?(Gi._e("["+$e.dateStr(new Date)+"] ","talkStatus is not found.","","","",""),null):(t.updateByMessageReadStatusesUpdate(e)&&this.dataStore.setTalkStatus(t),t)},newAnnouncementStatus:function(e){var t=this.dataStore.getAnnouncementStatus(e.domainId);return null==t&&((t=new Re).domainId=e.domainId),t.updateByAnnouncement(e),this.dataStore.setAnnouncementStatus(t),t},assureAnnouncementStatus:function(e){var t=this.dataStore.getAnnouncementStatus(e);return null==t&&(t=this.dataFactory.newAnnouncementStatusForDomain(e)),t},__class__:lr});var ur=function(){ir.call(this,"api")};(n["albero.proxy.AlberoServiceProxy"]=ur).__name__=["albero","proxy","AlberoServiceProxy"],ur.__super__=ir,ur.prototype=i(ir.prototype,{getOSString:function(){return"bot"},createAccessToken:function(e,t,n){var i,r,a=this,o=this.settings.getOs(),s=this.settings.getIDFV(),l=e.split("$");r=-1==e.indexOf("@")&&2==l.length?(i="create_access_token_by_id",[l[1],l[0],t,s,o,""]):(i="create_access_token",[e,t,s,o,""]),this.apiCaller.callImmediately(i,r,function(e){Gi._d("["+$e.dateStr(new Date)+"] ","access token:",e,"","",""),a.settings.setAccessToken(e),n(e)},function(e){a.sendNotification("Url",be.FORWARD(V.error))})},authorizeDevice:function(e,t){var n=this.settings.getIDFV();this.apiCaller.call("authorize_device",[e,n],function(e){t()})},createSession:function(e,i){var r=this,t=[e,"1.114",this.getOSString()];this.apiCaller.onSessionClear(),this.apiCaller.callImmediatelyReliable("create_session",t,function(e){var t=new hn(e),n=I.nowAsInt64();t.passwordExpiration.isExpired(n)?r.sendNotification("password_expiration_overed"):(t.passwordExpiration.needWarning(n,r.settings.getPasswordWarningSkipUntil())&&(r.settings.setPasswordWarningSkipUntil(I.oneDayAfterAsInt64()),r.sendNotification("password_expiration_warned")),r.apiCaller.onSessionCreated(),i(t),r.apiCaller.fireCallbacksWaitingForSession())},function(e){if(null!=e){if(401==e.code&&"expired password"==e.message)return void r.sendNotification("password_expiration_overed");if(401==e.code&&"deleted account"==e.message)return void r.sendNotification("SignOut");if(401==e.code&&"unauthorized device"==e.message)return void r.sendNotification("Device",q.AUTHORIZE);r.apiCaller.handleServerErrorDefault(e)}r.settings.clearAccessToken(),r.sendNotification("Url",be.FORWARD(V.error))},function(e){return r.shouldRetryCreateSession(e)?Ra.Some(r.apiCaller.retryTimeForReplicationLag()):Ra.None})},shouldRetryCreateSession:function(e){return 401==e.code&&"invalid token"==e.message},startNotification:function(){var t=this;this.apiCaller.call("start_notification",[],function(e){e||(t.dataStore.clear(!0),t.sendNotification("start_notification_failed"))})},resetNotification:function(e){this.apiCaller.call("reset_notification",[],e)},sendDomainNotifications:function(e){for(var t=0;t<e.length;){var n=e[t];++t,this.sendNotification("notify_update_domain",[null,n])}},sendAnnouncementStatusNotification:function(e){var t=new lt;t.domainId=e.domainId,this.sendNotification("notify_update_announcement_status",t)},sendTalkNotification:function(e){var t=e.type==bn.PairTalk?"notify_create_pair_talk":"notify_create_group_talk";this.sendNotification(t,e)},sendTalkNotifications:function(e){et.iter(e,go(this,this.sendTalkNotification))},sendTalkStatusNotifications:function(e){for(var t=0;t<e.length;){var n=e[t];++t,this.sendNotification("notify_update_local_talk_status",n)}},deleteSession:function(){this.settings.clearSelectedStampsetType(),this.settings.clearDomainSelection(),this.settings.clearAccessToken(),this.apiCaller.restart()},updateUser:function(t,e,n,i,r){function a(e){s.sendNotification("update_user_errored",s.dataStore.me)}function o(e){s.apiCaller.call("update_user",[t,e,i,r],function(e){var t=s.dataStore,n=new Rt(e);t.me=n;for(var i=0,r=t.getDomains();i<r.length;){var a=r[i];++i,t.sendNotification("notify_update_user",t.me.toDomainUser(a.id))}t.sendNotification("current_user_changed",n),t.storage.setDirtyFlag(),s.sendNotification("update_user_responsed",s.dataStore.me)},function(e){a(),s.apiCaller.handleServerErrorDefault(e)})}var s=this;null!=n?o(n):null!=e?this.uploadFile(e,null,Yn.PROFILE_IMAGE,function(e){o(e.get_url)},a):o()},updateProfile:function(e){var o=this,t=Qt.convertToApiParams(e);this.apiCaller.call("update_profile",[t],function(e){Gi._d("["+$e.dateStr(new Date)+"] ","update_profile_succeed",e,"","","");var t=o.dataStore,n=new Rt(e);t.me=n;for(var i=0,r=t.getDomains();i<r.length;){var a=r[i];++i,t.sendNotification("notify_update_user",t.me.toDomainUser(a.id))}t.sendNotification("current_user_changed",n),t.storage.setDirtyFlag(),o.sendNotification("update_profile_responsed",o.dataStore.me)},function(e){o.sendNotification("update_profile_errored",o.dataStore.me),o.apiCaller.handleServerErrorDefault(e)})},addFriend:function(e){var t=this.settings.getSelectedDomainId();this.apiCaller.call("add_friend",[t,e.id])},deleteFriend:function(e){var t=this.settings.getSelectedDomainId();this.apiCaller.call("delete_friend",[t,e.id])},getFriends:function(r){var a=this;this.apiCaller.call("get_friends",[],function(e){for(var t=0;t<e.length;){var n=e[t];++t;n[0];var i=n[1];et.iter(i,function(e){var t=a.dataFactory.newFriend(e);a.sendNotification("notify_add_friend",t)})}null!=r&&r()})},getAcquaintances:function(r){var a=this;this.apiCaller.call("get_acquaintances",[],function(e){for(var t=0;t<e.length;){var n=e[t];++t;var i=n[1];et.iter(i,function(e){var t=a.dataFactory.newAcquaintance(e);a.sendNotification("notify_add_acquaintance",t)})}null!=r&&r()})},getAllUsers:function(e,n){var i=this;null==n&&(n=this.settings.getSelectedDomainId());this.apiCaller.call("get_domain_users",[n,14,40,e],function(e){var t=nt.asArray(e.contents).map(go(mo=i.dataFactory,mo.newDomainUser));i.dataStore.setUsersIfLatest(n,t),i.sendNotification("get_domain_users_responsed",[n,e.marker,e.next_marker,t])})},getUsers:function(e,t){this._getUsers(e,t.slice())},_getUsers:function(n,i){var r=this,e=i.splice(0,100);0!=e.length&&this.apiCaller.call("get_users",[n,e],function(e){var t=e.map(go(mo=r.dataFactory,mo.newDomainUser));r.dataStore.setUsersIfLatest(n,t),r.sendNotification("get_users_responsed",[n,t]),r._getUsers(n,i)})},getProfile:function(e,t){var n=this;this.apiCaller.call("get_profile",[e,t],function(e){var t=new Kt(e);n.sendNotification("get_profile_responsed",t)},function(e){403==e.code&&"invalid user"==e.message?null!=e.detail&&null!=e.detail.invalid_user_ids&&n.sendNotification("get_profile_errored",e.detail.invalid_user_ids):n.apiCaller.handleServerErrorDefault(e)})},searchDomainUsers:function(n,e){var i=this,r=this.settings.getSelectedDomainId();this.apiCaller.call("search_domain_users",[r,n,14,40,e],function(e){var t=nt.asArray(e.contents).map(go(mo=i.dataFactory,mo.newDomainUser));i.dataStore.setUsersIfLatest(r,t),i.sendNotification("get_domain_users_responsed",[r,e.marker,e.next_marker,t,n])})},getUserIdentifiers:function(t,n,i){var r=this;if(0==n.length)null!=i&&i();else{var e=n.slice(0,100);this._getUserIdentifiers(t,e,function(){var e=n.slice(100);r.getUserIdentifiers(t,e,i)})}},_getUserIdentifiers:function(p,g,v){var y=this;this.apiCaller.call("get_user_identifiers",[p,g],function(e){for(var t=e.contents,n=new xa,i=0,r=t.length;i<r;){var a=i++,o=new zn(t[a]),s=o.userId,l="_"+s.high+"_"+s.low;null!=No[l]?n.setReserved(l,o):n.h[l]=o}for(var u=0,c=g.length;u<c;){var _=u++,h=y.dataStore.getUser(p,g[_]);if(null!=h){var d=h.id,f="_"+d.high+"_"+d.low,m=null!=No[f]?n.getReserved(f):n.h[f];null!=m&&(h.email=m.email,h.subEmail=m.subEmail,h.groupAlias=m.groupAlias,h.signinId=m.signinId),h.__uid_caching=!0}}null!=v&&v()},function(e){for(var t=0,n=g.length;t<n;){var i=t++,r=y.dataStore.getUser(p,g[i]);null!=r&&(r.__uid_caching=null)}null!=v&&v()})},getAllUserIdentifiers:function(i){var r=this,a=null,e=this.dataStore.getUsers();null==e&&(e=[]);for(var t=0;t<e.length;){var n=e[t];if(++t,null==n.__uid_caching){n.__uid_caching=!1;var o=n.domainId,s="_"+o.high+"_"+o.low;null==a&&(a=new xa);var l=null!=No[s]?a.getReserved(s):a.h[s];null==l&&(l=[],null!=No[s]?a.setReserved(s,l):a.h[s]=l),l.push(n.id)}}if(null==a)i();else{var u=a.keys(),c=null;(c=function(){if(u.hasNext()){var e=u.next(),t=tt.makeFromIdStr(e),n=null!=No[e]?a.getReserved(e):a.h[e];r.getUserIdentifiers(t,n,c)}else i()})()}},getAllUserEmails:function(e){Gi._w("["+$e.dateStr(new Date)+"] ","'getAllUserEmails' is deprecated, please use 'getAllUserIdentifiers' instead","","","",""),this.getAllUserIdentifiers(e)},getDepartmentTree:function(n){var i=this;this.apiCaller.call("get_department_tree",[n],function(e){et.iter(new ze(e).departments,function(e){e.isRoot()&&i.departmentStore.setRootDepartmentId(n,e.id),i.departmentStore.setDepartment(e)});var t=i.settings.getSelectedDepartmentId(n);null!=t&&null==i.departmentStore.getDepartment(t)&&i.settings.setSelectedDepartmentId(n,null),i.sendNotification("get_department_tree_responsed",[n])},function(e){403!=e.code||"forbidden"!=e.message?i.apiCaller.handleServerErrorDefault(e):i.sendNotification("get_department_tree_canceled",[n])})},getDepartmentUsers:function(e,t){this._getDepartmentUsers(e,t,null)},getDepartmentAllUsers:function(l){var u=this,e=this.departmentStore.getDepartment(l);if(null==e||null==e.userIds){var c=new xa,_=null;_=function(e,t,n){if(et.iter(n,function(e){var t=e.id,n="_"+t.high+"_"+t.low,i=e.id;null!=No[n]?c.setReserved(n,i):c.h[n]=i}),null==t){for(var i=[],r=c.arrayKeys(),a=new Fa(c,r);a.hasNext();){var o=a.next();i.push(o)}var s=i.length;Gi._d("["+$e.dateStr(new Date)+"] ","department all users prepared. [departmentId, users_count]:",l,s,"",""),u.departmentStore.setDepartmentUsers(l,i),u.sendNotification("department_user_ids_prepared",i)}else u._getDepartmentUsers(l,t,_)},this._getDepartmentUsers(l,null,_)}else this.sendNotification("department_user_ids_prepared",e.userIds)},_getDepartmentUsers:function(n,e,i){var r=this,a=this.settings.getSelectedDomainId(),t=this.departmentStore.getDepartment(n),o=null!=t&&null!=t.childrenIds;this.apiCaller.call("get_department_users",[a,n,o,100,e],function(e){var t=nt.asArray(e.contents).map(go(mo=r.dataFactory,mo.newDomainUser));r.dataStore.setUsersIfLatest(a,t),r.sendNotification("get_department_users_responsed",[a,e.marker,e.next_marker,t,n]),null!=i&&i(e.marker,e.next_marker,t)},function(e){403!=e.code||"forbidden"!=e.message?r.apiCaller.handleServerErrorDefault(e):r.sendNotification("get_department_users_canceled",[a])})},getMe:function(){var o=this;this.apiCaller.call("get_me",[],function(e){var t=o.dataStore,n=new Rt(e);t.me=n;for(var i=0,r=t.getDomains();i<r.length;){var a=r[i];++i,t.sendNotification("notify_update_user",t.me.toDomainUser(a.id))}t.sendNotification("current_user_changed",n),t.storage.setDirtyFlag(),o.sendNotification("get_me_responsed")},function(e){o.apiCaller.handleServerErrorDefault(e)})},getDepartmentUserCount:function(e,t){var n=t.filter(go(mo=this.departmentStore,mo.needUserCountLoading));this._getDepartmentUserCount(e,n)},_getDepartmentUserCount:function(n,i){var r=this,a=i.splice(0,100);0!=a.length&&(et.iter(a,function(e){r.departmentStore.setUserCountLoading(e,!0)}),this.apiCaller.call("get_department_user_count",[n,a],function(e){var t=new We(e);et.iter(t.departments,go(mo=r.departmentStore,mo.setDepartmentUserCount)),r.sendNotification("get_department_user_count_responsed",{completed:a,remaining:i}),r._getDepartmentUserCount(n,i)},function(e){et.iter(a,function(e){r.departmentStore.setUserCountLoading(e,!1)}),r.apiCaller.handleServerErrorDefault(e)}))},getDomains:function(n){var i=this;this.apiCaller.call("get_domains",[],function(e){et.iter(e,go(mo=i.dataFactory,mo.newDomain));var t=i.dataStore.getDomains();i.sendDomainNotifications(t),null!=n&&n()})},leaveDomain:function(e){var t=this;this.apiCaller.call("leave_domain",[e.id],function(e){t.dataStore.removeDomain(e)})},getDomainInvites:function(t){var e;e=null==t?function(e){}:function(e){t()},this._getDomainInvites(e)},_getDomainInvites:function(n){var i=this;this.apiCaller.call("get_domain_invites",[],function(e){var t=e.map(go(mo=i.dataFactory,mo.newDomainInvite));et.iter(t,function(e){i.sendNotification("notify_add_domain_invite",e)}),n(t)})},acceptDomainInvite:function(e){this.apiCaller.callApiReliable("accept_domain_invite",[e],function(e){})},deleteDomainInvite:function(e){this.apiCaller.callApiReliable("delete_domain_invite",[e],function(e){})},getAccountControlRequests:function(t){var n=this;this.apiCaller.call("get_account_control_requests",[],function(e){et.iter(e.map(go(mo=n.dataFactory,mo.newAccountControlRequest)),function(e){n.sendNotification("notify_add_account_control_request",e)}),null!=t&&t()})},acceptAccountControlRequest:function(e){if(null!=e){var t=this.dataStore.getAccountControlRequest(e);null!=t&&this.apiCaller.call("accept_account_control_request",[t.id,t.version],function(e){})}},rejectAccountControlRequest:function(e){if(null!=e){var t=this.dataStore.getAccountControlRequest(e);null!=t&&this.apiCaller.call("reject_account_control_request",[t.id,t.version],function(e){})}},getJoinedAccountControlGroup:function(t){var n=this;this.apiCaller.call("get_joined_account_control_group",[],function(e){et.iter(e.map(go(mo=n.dataFactory,mo.newAccountControlGroup)),function(e){n.sendNotification("notify_join_account_control_group",e)}),null!=t&&t()})},getTalks:function(i){var r=this;this.apiCaller.call("get_talks",[],function(e){et.iter(e,go(mo=r.dataFactory,mo.newTalk)),r.apiCaller.call("get_talk_statuses",[],function(e){et.iter(e,go(mo=r.dataFactory,mo.newTalkStatus));var t=r.dataStore.getTalks();r.sendTalkNotifications(t);var n=r.dataStore.getTalkStatuses();r.sendTalkStatusNotifications(n),null!=i&&i()})})},getReadStatus:function(e,t){var n=this;this.apiCaller.call("get_read_status",[e,t],function(e){n.sendNotification("notify_get_message_status",new Pt(e))})},createGroupTalk:function(e,t,n,i){var o=this;null==e&&(e=this.settings.getSelectedDomainId()),0!=t.length&&this.apiCaller.call("create_group_talk",[e,t,n.allowDisplayPastMessages,!0],function(e){var t=o.dataFactory.newTalk(e);o.sendNotification("create_group_talk_complete",t),null!=i&&o.sendNotification("SelectTalk",ge.SelectTalk(i,t))},function(e){if(o.sendNotification("create_group_talk_fail"),null!=e&&500==e.code&&null!=e.detail&&"failure in adding some users"==e.message){var t=Fr.toLocalError(Ot.AddingSomeUsersFailure,e);o.sendNotification("error_occurred",t)}else if(null!=e&&502==e.code&&null!=e.detail&&"talks"==e.detail.limit_target){var n=e.detail.limit_max,i=Fr.toLocalError(Ot.TalksCountOvered(n),e);o.sendNotification("error_occurred",i)}else if(null!=e&&502==e.code&&null!=e.detail&&"talkers"==e.detail.limit_target){var r=e.detail.limit_max,a=Fr.toLocalError(Ot.TalkersCountOvered(r),e);o.sendNotification("error_occurred",a)}else o.apiCaller.handleServerErrorDefault(e)})},createPairTalk:function(e,t,n){var i=this;null==e&&(e=this.settings.getSelectedDomainId()),this.apiCaller.call("create_pair_talk",[e,t],function(e){var t=i.dataFactory.newTalk(e);i.sendNotification("create_pair_talk_complete",t),null!=n&&i.sendNotification("SelectTalk",ge.SelectTalk(n,t))},function(e){if(i.sendNotification("create_pair_talk_fail"),null!=e&&502==e.code&&null!=e.detail&&"talks"==e.detail.limit_target){var t=e.detail.limit_max,n=Fr.toLocalError(Ot.TalksCountOvered(t),e);i.sendNotification("error_occurred",n)}else i.apiCaller.handleServerErrorDefault(e)})},updateGroupTalk:function(e,t,n,i){var r=this;this.apiCaller.call("update_group_talk",[e.id,t,n,i],function(e){var t=r.dataFactory.newTalk(e);r.sendNotification("notify_update_group_talk",t)},function(e){r.sendNotification("notify_update_group_talk_ERRORED"),r.apiCaller.handleServerErrorDefault(e)})},addTalkers:function(e,t,n){var r=this;if(e.type!=bn.PairTalk)0!=t.length&&this.apiCaller.call("add_talkers",[e.id,t,!0],function(e){var t=r.dataFactory.newTalk(e);r.sendNotification("notify_add_talkers",t),r.sendNotification("add_talkers_succeeded",t)},function(e){if(r.sendNotification("add_talkers_failed",e),null!=e&&500==e.code&&null!=e.detail&&"failure in adding some users"==e.message){var t=Fr.toLocalError(Ot.AddingSomeUsersFailure,e);r.sendNotification("error_occurred",t)}else if(null!=e&&502==e.code&&null!=e.detail&&"talkers"==e.detail.limit_target){var n=e.detail.limit_max,i=Fr.toLocalError(Ot.TalkersCountOvered(n),e);r.sendNotification("error_occurred",i)}else r.apiCaller.handleServerErrorDefault(e)});else{var i=e.userIds.concat(t);tt.remove(i,this.dataStore.me.id);var a=this.settings.getSelectedDomainId();this.createGroupTalk(a,i,An.createDefault(),n)}},deleteTalker:function(t,n){var i,r=this,a=null,o=null,e=this.dataStore;if(null!=e.me){var s=e.me.id;i=null!=s&&null!=n&&s.high==n.high&&s.low==n.low}else i=!1;i&&(a=t,o=this.dataStore.getTalkStatus(t.id),this.dataStore.removeTalk(t.id),this.dataStore.removeTalkStatus(t.id)),this.apiCaller.call("delete_talker",[t.id,n],function(e){tt.remove(t.userIds,n),i||r.dataStore.setTalk(t),i&&r.conferenceStore.removeConferencesOnLeaveTalk(t.id),r.sendNotification("notify_delete_talker",t)},function(e){null!=a&&r.dataStore.setTalk(a),null!=o&&r.dataStore.setTalkStatus(o),r.sendNotification("error_occurred",e)})},getMessages:function(n,e,i,r){var a=this;e=null==e?{sinceId:null,maxId:null}:e,null==i&&(i=Bt.desc);var t=this.apiCaller,o=e.sinceId,s=e.maxId,l=Ht.orderToInt(i);t.call("get_messages",[n,20,o,s,l],function(e){var t=e.map(go(mo=a.dataFactory,mo.newMessage));a.sendNotification("notify_get_messages",{talkId:n,messages:t,sortOrder:i,callerKey:r})})},createMessage:function(e,t,n,i){var r=this,a=this.dataFactory.newDummyMessage(e,t,n);if(null==this.dataStore.getTalk(e)){var o={code:400,message:"invalid talk_id (deleted talk)"};return Gi._w("["+$e.dateStr(new Date)+"] ","WARNING method: create_message",o,"","",""),void this.sendNotification("create_message_fail",[o,a],i)}this.sendNotification("create_message_start",a),this.apiCaller.call("create_message",[e,Ft.enumIndex(t),n],function(e){r.fileInfoStore.removeMessageFileInfos(a.id),r.messageStore.removeMessage(a.id);var t=r.dataFactory.newMessage(e);r.sendNotification("create_message_complete",[t,a.id],i)},function(e){if(r.sendNotification("create_message_fail",[e,a],i),null!=e&&409==e.code){var t=Fr.toLocalError(Ot.SendingMessageConflicted,e);r.sendNotification("error_occurred",t)}else r.sendNotification("error_occurred",e)})},forwardMessages:function(n,i,r){null==r&&(r=0);var a=this;if(!(r>=i.length)){var e=i[r],t=n.id,o=this.dataFactory.newDummyMessage(t,e.type,e.content);this.sendNotification("create_message_start",o),this.apiCaller.call("create_message",[t,Ft.enumIndex(e.type),e.content],function(e){var t=a.dataFactory.newMessage(e);a.sendNotification("create_message_complete",[t,o.id]),a.forwardMessages(n,i,r+1),a.fileInfoStore.removeMessageFileInfos(o.id),a.messageStore.removeMessage(o.id)},function(e){if(a.sendNotification("create_message_fail",[e,o]),null!=e&&409==e.code){var t=Fr.toLocalError(Ot.SendingMessageConflicted,e);a.sendNotification("error_occurred",t)}else a.sendNotification("error_occurred",e)})}},deleteMessage:function(n,i){var r=this;this.apiCaller.call("delete_message",[n,i],function(e){var t=new Ut;t.talkId=n,t.messageId=i,r.sendNotification("notify_delete_message",t)},function(e){if(null!=e){if(403==e.code&&"frozen domain"==e.message)return void r.sendNotification("error_occurred",e);if(409==e.code&&"conflict"==e.message){var t=Fr.toLocalError(Ot.DeletingMessageConflicted,e);return void r.sendNotification("error_occurred",t)}r.sendNotification("error_occurred",e)}})},updateReadStatuses:function(r,a){var o=this;this.apiCaller.callApiReliable("update_read_statuses",[r,a],function(e){var t,n=o.dataStore.getTalkStatus(r);if(null!=n){var i=n.maxReadMessageId;t=null!=i&&null!=a&&i.high==a.high&&i.low==a.low}else t=!1;t&&o.sendNotification("notify_update_local_talk_status",n)},null,function(e){return 429==e.code&&"too many requests"==e.message?Ra.Some(1e3*o.asInt(e.detail.retry_after)):Ra.None})},upload:function(t,n,i,r){var a=this,e=ri.getBlobFromUpdatableFile(i);this.fileService.asyncCreateThumbnail(e).catch(function(e){return null}).then(function(e){return{file:i,thumb:e}}).then(function(e){a.uploadV2(t,n,e,r)})},uploadV2:function(e,t,n,i){var r=this,a=this.dataFactory.newDummyFileMessage(t,n);this.sendNotification("create_message_start",a);var o=this.prepareMessageFileAsync(n.file,n.thumb,e);o.then(function(e){r.createMessageReliable(t,xt.file,e,a,i)}),o.catch(function(e){r.sendNotification("create_message_fail",[e,a],i)})},uploadForHubot:function(e,t,n){var i=this.dataStore.getTalk(e),r={file:t,thumb:null};if(null==i){var a=this.dataFactory.newDummyFileMessage(e,r),o={code:400,message:"invalid talk_id (deleted talk)"};return Gi._w("["+$e.dateStr(new Date)+"] ","WARNING method: upload",o,"","",""),void this.sendNotification("create_message_fail",[o,a],n)}this.uploadV2(i.domainId,i.id,r,n)},uploadMulti:function(n,i,r,e,a){var o=this,t=e.map(function(t){var e=ri.getBlobFromUpdatableFile(t);return o.fileService.asyncCreateThumbnail(e).catch(function(e){return null}).then(function(e){return{file:t,thumb:e}})});Promise.all(t).then(function(e){var t=e.map(function(e){return e});o.uploadMultiV2(n,i,r,t,a)})},uploadMultiV2:function(n,i,r,a,o){var s=this,l=this.dataFactory.newDummyMultipleFileMessage(i,r,a);this.sendNotification("create_message_start",l);for(var e=Promise.resolve([]),t=0;t<a.length;){var u=[a[t]];++t,e=e.then(function(e){return function(t){return s.prepareMessageFileAsync(e[0].file,e[0].thumb,n).then(function(e){return t.push(e),t})}}(u))}e.then(function(e){if(e.length==a.length){var t={files:e};null!=r&&0<r.length&&(t.text=r),s.createMessageReliable(i,xt.textMultipleFile,t,l,o)}}),e.catch(function(e){s.sendNotification("create_message_fail",[e,l],o)})},uploadMultiForHubot:function(e,t,n,i){var r=this.dataStore.getTalk(e),a=n.map(function(e){return{file:e,thumb:null}});if(null==r){var o=this.dataFactory.newDummyMultipleFileMessage(e,t,a),s={code:400,message:"invalid talk_id (deleted talk)"};return Gi._w("["+$e.dateStr(new Date)+"] ","WARNING method: uploadMulti",s,"","",""),void this.sendNotification("create_message_fail",[s,o],i)}this.uploadMultiV2(r.domainId,r.id,t,a,i)},prepareMessageFileAsync:function(a,n,o){var s=this;return new Promise(function(t,e){null!=n?s.uploadFile(n.file,o,Yn.THUMBNAIL,function(e){n.setAuth(e),t(Ra.Some(n))},function(e){t(Ra.None)}):t(Ra.None)}).then(function(r){return new Promise(function(i,e){s.uploadFile(a,o,Yn.MESSAGE,function(e){var t=Qi.normalizeForFile(a.name),n=E.createFileInfoDynamic(a,t,r,e);i(n)},e)})})},prepareNoteFileAsync:function(a,n,o){var s=this;return new Promise(function(t,e){null!=n?s.uploadFile(n.file,o,Yn.NOTE_THUMBNAIL,function(e){n.setAuth(e),t(Ra.Some(n))},function(e){t(Ra.None)}):t(Ra.None)}).then(function(r){return new Promise(function(i,e){s.uploadFile(a,o,Yn.NOTE_ATTACHMENT,function(e){var t=Qi.normalizeForFile(a.name),n=E.createFileInfoDynamic(a,t,r,e);i(n)},e)})})},createMessageReliable:function(e,t,n,i,r){var a=this;this.apiCaller.callApiReliable("create_message",[e,Ft.enumIndex(t),n],function(e){a.fileInfoStore.removeMessageFileInfos(i.id),a.messageStore.removeMessage(i.id);var t=a.dataFactory.newMessage(e);a.sendNotification("create_message_complete",[t,i.id],r)},function(e){if(a.sendNotification("create_message_fail",[e,i],r),null!=e&&409==e.code){var t=Fr.toLocalError(Ot.SendingMessageConflicted,e);a.sendNotification("error_occurred",t)}else a.sendNotification("error_occurred",e)},function(e){return a.shouldRetryCreateMessage(e)?Ra.Some(a.apiCaller.retryTimeForReplicationLag()):Ra.None})},shouldRetryCreateMessage:function(e){return null!=e.code&&(500==e.code?"Internal Error (IllegalStateException)"==e.message:400==e.code&&"invalid file_id"==e.message)},uploadFile:function(e,t,r,n,a){var o=this,i=e,s=Qi.normalizeForFile(i.name),l=i.type,u=i.size,c=this.apiCaller,_=Gn.getUseTypeInt(r);c.call("create_upload_auth",[s,l,u,t,_],function(t){o.fileService.upload(t,l,e).then(function(e){n(t)},function(e){var t=new Rr({code:null,detail:null,message:e});if(r!=Yn.THUMBNAIL&&r!=Yn.NOTE_THUMBNAIL&&r!=Yn.NOTE_ATTACHMENT){var n=Fr.toLocalError(Ot.GeneralFileError,t);o.sendNotification("error_occurred",n)}a(t)})},function(e){if(r!=Yn.THUMBNAIL&&r!=Yn.NOTE_THUMBNAIL&&r!=Yn.NOTE_ATTACHMENT&&null!=e)if(502==e.code&&null!=e.detail){var t=tt.fromIntOrInt64(e.detail.limit_max);if("file_size"==e.detail.limit_target){var n=Fr.toLocalError(Ot.UploadSizeOvered(t),e);o.sendNotification("error_occurred",n)}else if("storage_size"==e.detail.limit_target){var i=Fr.toLocalError(Ot.StorageSizeOvered(t),e);o.sendNotification("error_occurred",i)}}else o.sendNotification("error_occurred",e);a(e)})},createDownloadAuth:function(e,t,n,i,r){var a=this;this.apiCaller.callApiReliable("create_download_auth",[e,t,n],function(e){i(new gt(e))},function(e){r(e)},function(e){return 429==e.code&&"too many requests"==e.message?Ra.Some(1e3*a.asInt(e.detail.retry_after)):Ra.None})},deleteAttachment:function(e,t){this.apiCaller.call("delete_attachment",[e,t])},getAttachments:function(n,e){var i=this;null==e&&(e={sinceId:null,maxId:null}),this.apiCaller.call("get_attachments",[n,20,e.sinceId,e.maxId],function(e){var t=e.map(go(mo=i.dataFactory,mo.newFileInfo));i.sendNotification("get_file_responsed",{talkId:n,files:t})})},createAnnouncement:function(e,t,n,i){var r=this;if(null!=e||null!=(e=this.settings.getSelectedDomainId())){var a=this.dataFactory.newDummyMessage(null,t,n);this.sendNotification("create_announcement_start",a),this.apiCaller.call("create_announcement",[e,Ft.enumIndex(t),n],function(e){var t=r.dataFactory.newAnnouncement(e);r.sendNotification("create_announcement_complete",[t,a.id],i)},function(e){r.sendNotification("create_announcement_fail",a),r.sendNotification("error_occurred",e)})}},getAnnouncements:function(e,n,i){var r=this,a=this.settings.getSelectedDomainId();if(null!=a){e=null==e?{sinceId:null,maxId:null}:e;var t=this.apiCaller,o=e.sinceId,s=e.maxId,l=Ht.orderToInt(n);t.call("get_announcements",[a,20,o,s,l],function(e){var t=e.map(go(mo=r.dataFactory,mo.newAnnouncement));r.sendNotification("notify_get_announcements",{domainId:a,announcements:t,sortOrder:n,callerKey:i})})}},getAnnouncementStatuses:function(r){var a=this;this.apiCaller.call("get_announcement_statuses",[],function(e){for(var t=0;t<e.length;){var n=e[t];++t;var i=a.dataFactory.newAnnouncementStatus(n);a.sendAnnouncementStatusNotification(i),null!=r&&r()}})},getAnnouncementStatus:function(e,n){var i=this;this.apiCaller.callApiReliable("get_announcement_status",[e],function(e){var t=i.dataFactory.newAnnouncementStatus(e);i.sendAnnouncementStatusNotification(t),null!=n&&n()},null,function(e){return 400==e.code&&"invalid domain_id"==e.message?Ra.Some(i.apiCaller.retryTimeForReplicationLag()):Ra.None})},updateAnnouncementReadStatus:function(r,a){var o=this;this.apiCaller.call("update_announcement_status",[r,a],function(e){var t,n=o.dataStore.getAnnouncementStatus(r);if(null!=n){var i=n.maxReadAnnouncementId;t=null!=i&&null!=a&&i.high==a.high&&i.low==a.low}else t=!1;t&&o.sendAnnouncementStatusNotification(n)})},getQuestions:function(e,n,i,t){var r=this,a=this.settings.getSelectedDomainId(),o=null;null!=e&&(a=e.domainId,o=e.id);var s=Xt.fromTypeToInt(n),l=it.orNull(Xt.filterToOpBool(i));t=null==t?{sinceId:null,maxId:null}:t,this.apiCaller.call("get_actions",[a,o,s,l,20,t.sinceId,t.maxId],function(e){var t=e.map(go(mo=r.dataFactory,mo.newQuestion));r.sendNotification("get_questions_responsed",{domainId:a,talkId:o,questions:t,fromType:n,filter:i})})},getQuestion:function(e,n){var i=this;this.apiCaller.callApiReliable("get_action",[e],function(e){var t=i.dataFactory.newQuestion(e);i.sendNotification("notify_update_question",t),null!=n&&n(t)})},searchMessages:function(t,n,i,r){var a=this;this.searchService.prepareForSearching(t,i),this.apiCaller.call("search_messages",[t.domainId,t.talkId,t.getQueryText(),n,i],function(e){a.searchService.isRecentParams(t)&&a.searchService.isSearching()&&a.searchService.saveSearchMessagesResult(new on(e)),null!=r&&r()},function(e){a.searchService.notifySearchMessagesFail(),400!=e.code||null==i?a.sendNotification("error_occurred",e):a.searchMessages(t,n,null,r)})},searchAttachments:function(t,n,i,r){var a=this;this.searchService.prepareForSearching(t,i),this.apiCaller.call("search_attachments",[t.domainId,t.talkId,t.getQueryText(),n,i],function(e){a.searchService.isRecentParams(t)&&a.searchService.isSearching()&&a.searchService.saveSearchAttachmentsResult(new an(e)),null!=r&&r()},function(e){a.searchService.notifySearchAttachmentsFail(),400!=e.code||null==i?a.sendNotification("error_occurred",e):a.searchAttachments(t,n,null,r)})},startUpdateLastUsedAtIfNeed:function(){this.lastUsedAtUpdater.startPolling(go(this,this.updateLastUsedAt))},updateLastUsedAt:function(){var t=this;this.apiCaller.call("update_last_used_at",[],function(e){t.lastUsedAtUpdater.update()})},addFavoriteTalk:function(e,t){this.apiCaller.call("add_favorite_talk",[e,t])},deleteFavoriteTalk:function(e,t){this.apiCaller.call("delete_favorite_talk",[e,t])},disablePushNotification:function(e,t){this.apiCaller.call("disable_push_notification",[e,t])},enablePushNotification:function(e,t){this.apiCaller.call("enable_push_notification",[e,t])},getSolutions:function(e,t){var n=this;this.apiCaller.call("get_solutions",[e,t],function(e){et.iter(e,go(mo=n.dataFactory,mo.newSolution)),n.sendNotification("solutions_loaded")})},getPresences:function(e,a){var o=this;return new Promise(function(r,t){o.apiCaller.call("get_presences",[e,a],function(e){var t=I.nowAsInt64(),n=go(mo=o.dataFactory,mo.newUserPresence),i=t;et.iter(e,function(e){return n(e,i)}),o.sendNotification("presences_updated",a),r(a)},function(e){o.apiCaller.handleServerErrorDefault(e),t(e)})})},joinConference:function(n,e){var i=this;this.apiCaller.call("join_conference",[n,e],function(e){var t=new kt(e);i.sendNotification("join_conference_responsed",{talkId:n,joinConference:t})},function(e){i.sendNotification("join_conference_canceled",e)})},rejectConference:function(e){var t=this;this.apiCaller.call("reject_conference",[e],function(e){},function(e){404!=e.code?409!=e.code?t.sendNotification("error_occurred",e):Gi._d("["+$e.dateStr(new Date)+"] ","joined.","","","",""):Gi._d("["+$e.dateStr(new Date)+"] ","conference not found.","","","","")})},leaveConference:function(e){var t=this;this.apiCaller.call("leave_conference",[e],function(e){},function(e){404!=e.code?t.sendNotification("error_occurred",e):Gi._d("["+$e.dateStr(new Date)+"] ","conference not found.","","","","")})},getConferences:function(){var n=this;this.apiCaller.call("get_conferences",[],function(e){var t=e.map(go(mo=n.dataFactory,mo.newConference));et.iter(t,function(e){n.sendNotification("notify_open_conference",e)}),n.dataStore.filterReactedConferenceIds(t.filter(function(e){return!n.dataStore.isReactedConferenceId(e.id)}).map(function(e){return e.id}))})},getConferenceParticipants:function(e){var n=this;this.apiCaller.call("get_conference_participants",[e],function(t){it.foreach(n.conferenceStore.getConference(e),function(e){e.participants=t,n.sendNotification("get_conference_participants_responsed",e)})})},getNoteStatuses:function(e,t){var n=this.settings.getSelectedDomainId();this.apiNote.getNoteStatuses(n,e,t).catch(function(e){Gi._d("["+$e.dateStr(new Date)+"] ","getNoteStatuses error:",e,"","","")})},getNote:function(e,t){var n=null!=t?t:function(e,t){};this.apiNote.getNote(e).then(function(e){n(null,e)}).catch(function(e){Gi._d("["+$e.dateStr(new Date)+"] ","getNote error:",e,"","",""),n(e,null)})},createNote:function(e,t,n,i,r){Gi._w("["+$e.dateStr(new Date)+"] ","'createNote' is deprecated, please use 'res.send' instead.","","","",""),this.apiNote.createNote(e,t,n,i,r).catch(function(e){Gi._d("["+$e.dateStr(new Date)+"] ","createNote error:",e,"","","")})},createNoteV2:function(a,o,s,e){var l=this,t=this.dataStore.getTalk(o.getTalkId());if(null!=t){var r=t.domainId,u=o.getNoteId();this.dataStore.setNoteLocalEdit(u,o);for(var n=Promise.resolve(),i=0,c=o.getUnuploadedFileInfos();i<c.length;){var _=[c[i]];++i,n=n.then(function(n){return function(e){return l.prepareNoteFileAsync(n[0].file,n[0].localThumbInfo,r).then((t=n,function(e){t[0].setUploadResult(wt.SUCCESS(e))})).catch((i=n,function(e){i[0].setUploadResult(wt.FAILUER);var t=Mt.convertFileErrorForNote(u,e);if(null!=t){o.setState(Ei.FAILED_BY_FILE(i[0].id,t)),l.dataStore.setNoteLocalEdit(u,o);var n=Fr.toLocalError(t,e);l.sendNotification("error_occurred",n)}return Promise.reject(e)}));var i,t}}(_))}var h=null!=e?e:function(e,t){};n.then(function(e){var t=l.apiNote,n=o.getTitle(),i=o.getContentType(),r=o.getContent();return t.createNote(a,n,i,r,s,o)}).then(function(e){h(null,e)}).catch(function(e){Gi._d("["+$e.dateStr(new Date)+"] ","createNoteV2 error:",e,"","",""),h(e,null)})}},updateNoteSetting:function(e,t,n){this.apiNote.updateNoteSetting(e,t,n).catch(function(e){Gi._d("["+$e.dateStr(new Date)+"] ","updateNoteSetting error:",e,"","","")})},updateNote:function(e,t,n,i,r,a){this.apiNote.updateNote(e,t,n,i,r,a).catch(function(e){Gi._d("["+$e.dateStr(new Date)+"] ","updateNote error:",e,"","","")})},updateNoteV2:function(a,o,s,l,e){var u=this,t=this.dataStore.getTalk(s.getTalkId());if(null==t)return Promise.resolve();var r=t.domainId;this.dataStore.setNoteLocalEdit(a,s);for(var n=Promise.resolve(),i=0,c=s.getUnuploadedFileInfos();i<c.length;){var _=[c[i]];++i,n=n.then(function(n){return function(e){return u.prepareNoteFileAsync(n[0].file,n[0].localThumbInfo,r).then((t=n,function(e){t[0].setUploadResult(wt.SUCCESS(e))})).catch((i=n,function(e){i[0].setUploadResult(wt.FAILUER);var t=Mt.convertFileErrorForNote(a,e);if(null!=t){s.setState(Ei.FAILED_BY_FILE(i[0].id,t)),u.dataStore.setNoteLocalEdit(a,s);var n=Fr.toLocalError(t,e);u.sendNotification("error_occurred",n)}return Promise.reject(e)}));var i,t}}(_))}var h=null!=e?e:function(e,t){};return n.then(function(e){var t=u.apiNote,n=s.getTitle(),i=s.getContentType(),r=s.getContent();return t.updateNote(a,o,n,i,r,l,s)}).then(function(e){h(null,e)}).catch(function(e){return Gi._d("["+$e.dateStr(new Date)+"] ","updateNote error:",e,"","",""),h(e,null),409==e.code&&"locked by another user"==e.message?Promise.reject(e):u.unlockNote(a,o).then(function(e){})}).catch(function(e){})},deleteNote:function(e,t){var n=null!=t?t:function(e,t){};this.apiNote.deleteNote(e).then(function(e){n(null,e)}).catch(function(e){Gi._d("["+$e.dateStr(new Date)+"] ","deleteNote error:",e,"","",""),n(e,null)})},lockNote:function(e,t){var n=this.settings.getSelectedDomainId();return this.apiNote.lockNote(n,e,t)},unlockNote:function(e,t){var n=this.settings.getSelectedDomainId();return this.apiNote.unlockNote(n,e,t)},addFavoriteMessage:function(e,t,n){var i=this;this.apiCaller.call("add_favorite_message",[e,t,n],function(e){i.sendNotification("add_favorite_message_completed",new qn(e))},function(e){400==e.code&&"invalid message"==e.message&&Gi._d("["+$e.dateStr(new Date)+"] ","invalid message.","","","",""),400==e.code&&"invalid message (not favoritable message)"==e.message&&Gi._d("["+$e.dateStr(new Date)+"] ","invalid message (not favoritable message).","","","",""),403==e.code&&"forbidden"==e.message&&Gi._d("["+$e.dateStr(new Date)+"] ","forbidden.","","","",""),404==e.code&&Gi._d("["+$e.dateStr(new Date)+"] ","message is not found.","","","",""),409!=e.code||"conflict"!=e.message?i.sendNotification("error_occurred",e):Gi._d("["+$e.dateStr(new Date)+"] ","conflict","","","","")})},deleteFavoriteMessage:function(e,t){var n=this;this.apiCaller.call("delete_favorite_message",[e,t],function(e){n.sendNotification("delete_favorite_message_completed",new Qn(e))},function(e){400==e.code&&Gi._d("["+$e.dateStr(new Date)+"] ","invalid parameter.","","","",""),404==e.code&&Gi._d("["+$e.dateStr(new Date)+"] ","message is not found.","","","",""),n.sendNotification("error_occurred",e)})},getFavoriteMessages:function(a,o,e){var s=this;this.apiCaller.call("get_favorite_messages",[a,o,20,e],function(e){var t=e.marker,n=e.next_marker,i=e.contents.map(go(mo=s.dataFactory,mo.newMessage)),r=new Jn(a,o,t,n,i);s.sendNotification("get_favorite_messages_completed",r)},function(e){400==e.code&&Gi._d("["+$e.dateStr(new Date)+"] ","invalid parameter.","","","",""),s.sendNotification("error_occurred",e)})},getStampsets:function(e){var i=this;return new Promise(function(n,t){i.apiCaller.call("get_stampsets",[e],function(e){var t=e.map(Sn.originalStampset);i.stampsStore.addStampsets(t),n(t)},function(e){t(e)})})},getFlowNotificationBadges:function(e){var t=this;return this._getFlowNotificationBadges(e).then(function(e){t.sendNotification("get_flow_notification_badges_completed")},function(e){t.apiCaller.handleServerErrorDefault(e),t.sendNotification("get_flow_notification_badges_failed")})},_getFlowNotificationBadges:function(e){var i=this;if(0==e.length)return Promise.resolve();var r=e.slice(0,100),t=e.slice(100);return new Promise(function(n,t){i.apiCaller.call("get_flow_notification_badges",[r],function(e){var t=e.map(function(e){return new It(e)});et.iter(t,function(e){i.dataStore.setFlowNotificationBadge(e.domainId,e)}),Wi.resolveVoid(n)},function(e){t(e)})}).then(function(e){return i._getFlowNotificationBadges(t)})},asInt:function(e){return Va.__cast(e,vo)},__class__:ur});var cr=function(){this.callbacksWhenCreateSessionSucceed=[],this.createSessionSucceed=!1,ir.call(this,"apiCaller")};(n["albero.proxy.ApiCallerProxy"]=cr).__name__=["albero","proxy","ApiCallerProxy"],cr.delayForReplicationLag=function(){return Wi.delay(500)},cr.__super__=ir,cr.prototype=i(ir.prototype,{onSessionClear:function(){this.createSessionSucceed=!1},onSessionCreated:function(){this.createSessionSucceed=!0},fireCallbacksWaitingForSession:function(){et.iter(this.callbacksWhenCreateSessionSucceed,function(e){e()}),this.callbacksWhenCreateSessionSucceed.splice(0,this.callbacksWhenCreateSessionSucceed.length)},callImmediately:function(e,t,n,i){this.rpc.call(e,t,n,i)},callImmediatelyReliable:function(t,n,i,r,a,o){null==o&&(o=3);var s=this,e=this.createOnErrorReliable(o,r,a,function(e){Ea.delay(function(){s.callImmediatelyReliable(t,n,i,r,a,o-1)},e)});this.callImmediately(t,n,i,e)},call:function(e,t,n,i){function r(){a(o,s,l,u)}var a=go(mo=this.rpc,mo.call),o=e,s=t,l=n,u=i;this.createSessionSucceed?r():this.callbacksWhenCreateSessionSucceed.push(r)},callApiReliable:function(t,n,i,r,a,o){null==o&&(o=3);var s=this,e=this.createOnErrorReliable(o,r,a,function(e){Ea.delay(function(){s.callApiReliable(t,n,i,r,a,o-1)},e)});this.call(t,n,i,e)},createOnErrorReliable:function(n,i,r,a){var t=this;return null==r&&(r=function(e){return 404==e.code?Ra.Some(t.retryTimeForReplicationLag()):Ra.None}),null==i&&(i=go(this,this.handleServerErrorDefault)),function(e){if(0!=n){var t=r(e);it.isEmpty(t)?i(e):it.foreach(t,a)}else i(e)}},handleServerErrorDefault:function(e){this.rpc.onServerError(e)},restart:function(){this.rpc.restart()},retryTimeForReplicationLag:function(){return 1e3},__class__:cr});var _r=function(){ir.call(this,"apiNote")};(n["albero.proxy.ApiNoteProxy"]=_r).__name__=["albero","proxy","ApiNoteProxy"],_r.__super__=ir,_r.prototype=i(ir.prototype,{getNoteStatuses:function(n,r,i){var a=this;return new Promise(function(t,e){a.apiCaller.call("get_note_statuses",[n,r,60,i],function(e){t(new ti(e))},e)}).then(function(e){if(e.isNotEmptyNoteStatuses())for(var t=0,n=e.noteStatuses;t<n.length;){var i=n[t];++t,a.dataStore.setNoteRevisionSummary(i.noteId,i.getNoteRevisionSummary())}return a.sendNotification("get_note_statuses_loaded",{talkId:r,result:e}),e},function(e){return a.sendNotification("error_occurred",e),Promise.reject(e)})},getNote:function(n){var i=this;return new Promise(function(t,e){i.apiCaller.call("get_note",[n.value],function(e){t(new ei(e))},e)}).then(function(e){return i.dataStore.setNote(e.getNoteId(),e.note),i.sendNotification("get_note_loaded",e),e},function(e){return 404==e.code?(i.dataStore.setNote(n,null),i.sendNotification("get_note_failed_by_note_not_found",n)):i.sendNotification("error_occurred",e),Promise.reject(e)})},createNote:function(i,r,a,o,s,l){var u=this;return new Promise(function(t,e){var n=wi.getValue(a);u.apiCaller.callApiReliable("create_note",[i,r,n,o,s],function(e){t(new Zn(e))},e,go(u,u.retryTimeForCreateOrUpdateNoteFromError))}).then(function(e){var t;return null!=l&&u.dataStore.setNoteLocalEdit(l.getNoteId(),null),t=null!=l&&l.hasEmitterKey()?e.updateWithEmitterKey(l.getEmitterKey()):e,u.sendNotification("create_note_completed",t),e},function(e){if(null!=l&&(l.setState(Ei.FAILED_BY_UNKNOWN),u.dataStore.setNoteLocalEdit(l.getNoteId(),l)),null!=l&&l.hasEmitterKey()){var t=u.dataStore.me.id,n=l.getEmitterKey();u.sendNotification("create_note_failed",new Xn(t,e,n))}return u.sendNotification("error_occurred",e),Promise.reject(e)})},updateNoteSetting:function(n,i,r){var a=this;return new Promise(function(t,e){a.apiCaller.call("update_note_setting",[n.value,i,r],function(e){t(new ii(e))},e)}).then(function(e){return a.sendNotification("update_note_setting_completed",e),e},function(e){return 404==e.code?(a.dataStore.setNote(n,null),a.sendNotification("update_note_setting_failed_by_not_found",n)):409==e.code&&"conflict"==e.message?(a.dataStore.setNote(n,null),a.sendNotification("update_note_setting_failed_by_conflict",n)):409==e.code&&"locked by another user"==e.message&&null!=e.detail&&null!=e.detail.user_id&&null!=e.detail.device_id?a.sendNotification("update_note_setting_failed_by_editing",n):a.sendNotification("error_occurred",e),Promise.reject(e)})},updateNote:function(i,r,a,o,s,l,t){var u=this;return new Promise(function(t,e){var n=wi.getValue(o);u.apiCaller.callApiReliable("update_note",[i.value,r,a,n,s,l],function(e){t(new ni(e))},e,go(u,u.retryTimeForCreateOrUpdateNoteFromError))}).then(function(e){return null!=t&&u.dataStore.setNoteLocalEdit(i,null),u.dataStore.setNote(i,e.note),u.sendNotification("update_note_completed",e),e},function(e){return 404==e.code?null!=t?(t.setState(Ei.FAILED_BY_NOT_FOUND),u.dataStore.setNoteLocalEdit(i,t)):u.dataStore.setNote(i,null):409==e.code&&"conflict"==e.message?null!=t?(t.setState(Ei.FAILED_BY_CONFLICT),u.dataStore.setNoteLocalEdit(i,t)):u.dataStore.setNote(i,null):409==e.code&&"locked by another user"==e.message&&null!=e.detail&&null!=e.detail.user_id&&null!=e.detail.device_id?null!=t&&(t.setState(Ei.FAILED_BY_CONFLICT),u.dataStore.setNoteLocalEdit(i,t)):(null!=t&&(t.setState(Ei.FAILED_BY_UNKNOWN),u.dataStore.setNoteLocalEdit(i,t)),u.sendNotification("error_occurred",e)),Promise.reject(e)})},deleteNote:function(n){var i=this;return new Promise(function(t,e){i.apiCaller.call("delete_note",[n.value],function(e){t(new $n(e))},e)}).then(function(e){return i.sendNotification("delete_note_completed",e),e},function(e){return 404==e.code&&i.dataStore.setNote(n,null),i.sendNotification("error_occurred",e),Promise.reject(e)})},lockNote:function(n,r,a){var o=this;return new Promise(function(e,t){o.apiCaller.call("lock_note",[r.value,a],e,t)}).then(function(e){var t=o.dataStore.getNote(r);if(null!=t){var n=o.dataStore.me.id,i=o.settings.getDeviceId();t.lock(a,n,i,e)}return new Di(bi.COMPLETED(new Ai(e)))}).catch(function(e){if(400==e.code)return Gi._d("["+$e.dateStr(new Date)+"] ","invalid parameter.","","","",""),o.sendNotification("error_occurred",e),new Di(bi.FAILED_BY_UNKNOWN);if(403==e.code)return Gi._d("["+$e.dateStr(new Date)+"] ","forbidden.","","","",""),o.sendNotification("error_occurred",e),new Di(bi.FAILED_BY_UNKNOWN);if(404==e.code)return Gi._d("["+$e.dateStr(new Date)+"] ","note is not found.","","","",""),o.dataStore.setNote(r,null),new Di(bi.FAILED_BY_NOT_FOUND);if(409!=e.code||"locked by another user"!=e.message||null==e.detail||null==e.detail.user_id||null==e.detail.device_id)return 409==e.code&&"conflict"==e.message?(Gi._d("["+$e.dateStr(new Date)+"] ","conflict","","","",""),new Di(bi.FAILED_BY_CONFLICT)):(o.sendNotification("error_occurred",e),new Di(bi.FAILED_BY_UNKNOWN));var t=o.dataStore.getUser(n,e.detail.user_id);return new Di(bi.FAILED_BY_LOCKED(t))})},unlockNote:function(n,i,r){var a=this;return new Promise(function(e,t){a.apiCaller.call("unlock_note",[i.value,r],e,t)}).then(function(e){var t=a.dataStore.getNote(i);return null!=t&&t.unlock(r,a.dataStore.me.id),new Di(bi.RELEASED)}).catch(function(e){if(400==e.code)return Gi._d("["+$e.dateStr(new Date)+"] ","invalid parameter.","","","",""),a.sendNotification("error_occurred",e),new Di(bi.FAILED_BY_UNKNOWN);if(403==e.code)return Gi._d("["+$e.dateStr(new Date)+"] ","forbidden.","","","",""),a.sendNotification("error_occurred",e),new Di(bi.FAILED_BY_UNKNOWN);if(404==e.code)return Gi._d("["+$e.dateStr(new Date)+"] ","note is not found.","","","",""),a.dataStore.setNote(i,null),new Di(bi.FAILED_BY_NOT_FOUND);if(409==e.code&&"conflict"==e.message)return new Di(bi.FAILED_BY_CONFLICT);if(409!=e.code||"locked by another user"!=e.message||null==e.detail||null==e.detail.user_id||null==e.detail.device_id)return a.sendNotification("error_occurred",e),new Di(bi.FAILED_BY_UNKNOWN);var t=a.dataStore.getUser(n,e.detail.user_id);return new Di(bi.FAILED_BY_LOCKED(t))})},retryTimeForCreateOrUpdateNoteFromError:function(e){return this.shouldRetryCreateOrUpdateNote(e)?Ra.Some(this.apiCaller.retryTimeForReplicationLag()):Ra.None},shouldRetryCreateOrUpdateNote:function(e){return null!=e.code&&(500==e.code?"Internal Error (IllegalStateException)"==e.message:400==e.code&&"invalid file_id"==e.message)},__class__:_r});var hr=function(){ir.call(this,"appState")};(n["albero.proxy.AppStateProxy"]=hr).__name__=["albero","proxy","AppStateProxy"],hr.__super__=ir,hr.prototype=i(ir.prototype,{start:function(){this.updateLastActivityAt(),this.checkInactiveInterval()},activateAppIfNeed:function(){this.updateLastActivityAt(),this.appState==g.Inactive&&this.setAppState(g.Active)},setAppState:function(e){Gi._d("["+$e.dateStr(new Date)+"] ","APP_STATE_CHANGED: ",e,"","",""),this.appState=e,this.sendNotification("app_state_changed",this.appState)},updateLastActivityAt:function(){this.lastActivityAt=new Date},checkInactiveInterval:function(){this.checkInactive(),new Ea(500).run=go(this,this.checkInactive)},checkInactive:function(){this.appState!=g.Inactive&&((new Date).getTime()-this.lastActivityAt.getTime()<2e3||this.setAppState(g.Inactive))},__class__:hr});var dr=function(){ir.call(this,"conferenceStore"),this.conferencesMap=new xa,this.talkIdConferenceIdMap=new xa};(n["albero.proxy.ConferenceStoreProxy"]=dr).__name__=["albero","proxy","ConferenceStoreProxy"],dr.__super__=ir,dr.prototype=i(ir.prototype,{addConference:function(e){var t=e.id,n="_"+t.high+"_"+t.low,i=this.conferencesMap;null!=No[n]?i.setReserved(n,e):i.h[n]=e;var r=e.talkId,a="_"+r.high+"_"+r.low,o=this.talkIdConferenceIdMap;null!=No[a]?o.setReserved(a,n):o.h[a]=n},removeConference:function(e){this.dataStore.removeReactedConfereceId(e.id);var t=e.id,n="_"+t.high+"_"+t.low;this.conferencesMap.remove(n);var i=e.talkId,r="_"+i.high+"_"+i.low,a=this.talkIdConferenceIdMap;(null!=No[r]?a.getReserved(r):a.h[r])==n&&this.talkIdConferenceIdMap.remove(r),this.messageStore.onConferenceClose(e)},getConference:function(e){var t="_"+e.high+"_"+e.low,n=this.conferencesMap;return it.option(null!=No[t]?n.getReserved(t):n.h[t])},hasConference:function(e){if(null==e)return!1;var t="_"+e.high+"_"+e.low,n=this.talkIdConferenceIdMap;return null!=No[t]?n.existsReserved(t):n.h.hasOwnProperty(t)},hasConferenceInDomain:function(n){return null!=et.find(this.getConferenceTalkIds().map(tt.makeFromIdStr).map(go(mo=this.dataStore,mo.getTalk)),function(e){if(null==e)return!1;var t=e.domainId;return null!=t&&null!=n&&t.high==n.high&&t.low==n.low})},getConferenceTalkIds:function(){for(var e=[],t=this.talkIdConferenceIdMap.keys();t.hasNext();){var n=t.next();e.push(n)}return e},hasConferenceInAllDomains:function(i){return it.isEmpty(i)?this.talkIdConferenceIdMap.keys().hasNext():null!=et.find(this.getConferenceTalkIds().map(tt.makeFromIdStr).map(go(mo=this.dataStore,mo.getTalk)),function(e){if(null==e)return!1;var t=e.domainId,n=it.get(i);return!(null!=t&&null!=n&&t.high==n.high&&t.low==n.low)})},removeConferencesOnLeaveDomain:function(e){for(var t=this.conferencesMap,n=new Fa(t,t.arrayKeys());n.hasNext();){var i=n.next(),r=i.domainId;null!=r&&null!=e&&r.high==e.high&&r.low==e.low&&(this.removeConference(i),this.sendNotification("notify_close_conference",i))}},removeConferencesOnLeaveTalk:function(e){for(var t=this.conferencesMap,n=new Fa(t,t.arrayKeys());n.hasNext();){var i=n.next(),r=i.talkId;null!=r&&null!=e&&r.high==e.high&&r.low==e.low&&(this.removeConference(i),this.sendNotification("notify_close_conference",i))}},updatePrevSelectedMic:function(e){var t=this.settings.getBrowserSettings().createCopy(),n=this.dataStore.me;if(null!=n){var i=n.id;t.setPrevSelectedMic("_"+i.high+"_"+i.low,e),this.settings.applyUserDataSettings(t)}},updatePrevSelectedSpeaker:function(e){var t=this.settings.getBrowserSettings().createCopy(),n=this.dataStore.me;if(null!=n){var i=n.id;t.setPrevSelectedSpeaker("_"+i.high+"_"+i.low,e),this.settings.applyUserDataSettings(t)}},updatePrevSelectedCamera:function(e){var t=this.settings.getBrowserSettings().createCopy(),n=this.dataStore.me;if(null!=n){var i=n.id;t.setPrevSelectedCamera("_"+i.high+"_"+i.low,e),this.settings.applyUserDataSettings(t)}},getPrevSelectedDevice:function(){var e=this.dataStore.me;if(null==e)return{mic:"",speaker:"",camera:""};var t=e.id,n="_"+t.high+"_"+t.low;return this.settings.getBrowserSettings().getPrevSelectedDevice(n)},__class__:dr});var fr=function(){var e=new Kn(-1,-1);this.dummyFileId=e;var t=new Kn(-1,-1);this.dummyMsgId=t,ir.call(this,"dataFactory")};(n["albero.proxy.DataFactoryProxy"]=fr).__name__=["albero","proxy","DataFactoryProxy"],fr.__super__=ir,fr.prototype=i(ir.prototype,{onRegister:function(){},newAcquaintance:function(e){return this.dataStore.addAcquaintance(this.newDomainUser(e))},newFriend:function(e){return this.dataStore.addFriend(this.newDomainUser(e))},newDomainUser:function(e){return new ft(e)},newDomain:function(e){return this.dataStore.setDomainIfLatest(new ct(e))},newDomainInvite:function(e){return this.dataStore.setDomainInvite(new ht(e))},newTalk:function(e){return this.dataStore.setTalk(new Nn(e))},newTalkStatus:function(e){return this.dataStore.setTalkStatus(new Un(e))},newMessage:function(e){var t=new Ft(e);switch(t.type[1]){case 4:this.fileInfoStore.setMessageFileInfos(t.id,[St.fromMessageAndFile(t,t.content)]);break;case 5:var n=t;this.fileInfoStore.setMessageFileInfos(t.id,nt.asArray(t.content.files).map(function(e){return St.fromMessageAndFile(n,e)}))}return this.messageStore.setMessage(t),t},newDummyMessage:function(e,t,n){var i=this,r=new Ft;r.id=this.dummyMsgId,r.userId=this.dataStore.me.id,r.talkId=e,r.type=t,r.content=n;var a,o=this.dummyMsgId;if(null==o)a=null;else{var s=new Kn(0,1),l=o.high-s.high|0,u=o.low-s.low|0;if(Sa.ucompare(o.low,s.low)<0){l--;l|=0}a=new Kn(l,u)}switch(this.dummyMsgId=a,r.type[1]){case 4:var c=[this.createDummyFileInfo(r,r.content)];this.fileInfoStore.setMessageFileInfos(r.id,c);break;case 5:var _=Va.__cast(r.content.files,Array).map(function(e){return i.createDummyFileInfo(r,e)});this.fileInfoStore.setMessageFileInfos(r.id,_)}return this.messageStore.setMessage(r),r},newDummyFileMessage:function(e,t){var n=this.createFileInfoDynamic(t);return this.newDummyMessage(e,xt.file,n)},newDummyMultipleFileMessage:function(e,t,n){var i=et.array(n.filter(function(e){return null!=e.file}).map(go(this,this.createFileInfoDynamic)));return this.newDummyMessage(e,xt.textMultipleFile,{text:t,files:i})},createFileInfoDynamic:function(e){var t=e.file;return{content_type:t.type,content_size:t.size,name:Qi.normalizeForFile(t.name),file:t,localThumbInfo:e.thumb}},createDummyFileInfo:function(e,t){var n,i=St.fromMessageAndFileWithFileId(e,t,this.dummyFileId),r=this.dummyFileId;if(null==r)n=null;else{var a=new Kn(0,1),o=r.high-a.high|0,s=r.low-a.low|0;if(Sa.ucompare(r.low,a.low)<0){o--;o|=0}n=new Kn(o,s)}return this.dummyFileId=n,i},newQuestion:function(e){return this.dataStore.setQuestion(new Xt(e))},newFileInfo:function(e){var t=new St(e);return this.fileInfoStore.setTalkFileInfo(t,!0),t},newAnnouncement:function(e){return new st(e)},newAnnouncementStatus:function(e){return this.dataStore.setAnnouncementStatus(new Re(e))},newAnnouncementStatusForDomain:function(e){var t=new Re;return t.domainId=e,this.dataStore.setAnnouncementStatus(t)},newAccountControlRequest:function(e){return this.dataStore.setAccountControlRequest(new ot(e))},newAccountControlGroup:function(e){return this.dataStore.setAccountControlGroup(new rt(e))},newSolution:function(e){var t=new dn(e);return this.solutionsStore.setSolution(t),t},newUserPresence:function(e,t){var n=new Wn(e,t);return this.dataStore.setUserPresence(n),n},newConference:function(e){var t=new ut(e);return this.conferenceStore.addConference(t),t},__class__:fr});var mr=function(){this.flowNotificationBadgeStore=new Et,ir.call(this,"dataStore")};(n["albero.proxy.DataStoreProxy"]=mr).__name__=["albero","proxy","DataStoreProxy"],mr.__super__=ir,mr.prototype=i(ir.prototype,{onRegister:function(){this.init()},setMe:function(e){this.me=e;for(var t=0,n=this.getDomains();t<n.length;){var i=n[t];++t,this.sendNotification("notify_update_user",this.me.toDomainUser(i.id))}this.sendNotification("current_user_changed",e),this.storage.setDirtyFlag()},getMe:function(){return this.me},isMe:function(e){if(null==this.me)return!1;var t=this.me.id;return null!=t&&null!=e&&t.high==e.high&&t.low==e.low},getFriendsOrAcquaintances:function(e){var t="_"+e.high+"_"+e.low,n=this.users,i=null!=No[t]?n.getReserved(t):n.h[t],r=[];if(null!=i)for(var a=new Fa(i,i.arrayKeys());a.hasNext();){var o=a.next();0!=o.type&&1!=o.type||r.push(o.user)}return r},getFriends:function(e){var t="_"+e.high+"_"+e.low,n=this.users,i=null!=No[t]?n.getReserved(t):n.h[t],r=[];if(null!=i)for(var a=new Fa(i,i.arrayKeys());a.hasNext();){var o=a.next();0==o.type&&r.push(o.user)}return r},getAcquaintances:function(e){var t="_"+e.high+"_"+e.low,n=this.users,i=null!=No[t]?n.getReserved(t):n.h[t],r=[];if(null!=i)for(var a=new Fa(i,i.arrayKeys());a.hasNext();){var o=a.next();1==o.type&&r.push(o.user)}return r},isFriend:function(e,t){var n="_"+e.high+"_"+e.low,i=this.users,r=null!=No[n]?i.getReserved(n):i.h[n];if(null==r)return!1;var a="_"+t.high+"_"+t.low,o=null!=No[a]?r.getReserved(a):r.h[a];return null!=o&&0==o.type},addFriend:function(e){var t=this.ensureDomainUserMap(e.domainId),n=e.id,i="_"+n.high+"_"+n.low,r={type:0,user:e};return null!=No[i]?t.setReserved(i,r):t.h[i]=r,this.storage.setDirtyFlag(),e},addAcquaintance:function(e){var t=this.ensureDomainUserMap(e.domainId),n=e.id,i="_"+n.high+"_"+n.low,r={type:1,user:e};return null!=No[i]?t.setReserved(i,r):t.h[i]=r,this.storage.setDirtyFlag(),e},ensureDomainUserMap:function(e){var t="_"+e.high+"_"+e.low,n=this.users,i=null!=No[t]?n.getReserved(t):n.h[t];if(null==i){i=new xa;var r=this.users;null!=No[t]?r.setReserved(t,i):r.h[t]=i}return i},setUserIfLatest:function(e,t){null==e&&(e=this.ensureDomainUserMap(t.domainId));var n=t.id,i="_"+n.high+"_"+n.low,r=null!=No[i]?e.getReserved(i):e.h[i];if(null!=r){var a=t.updatedAt,o=r.user.updatedAt,s=a.high-o.high|0;s=0!=s?s:Sa.ucompare(a.low,o.low);var l=a.high<0?o.high<0?s:-1:0<=o.high?s:1;(1<l||2==r.type&&0!=l)&&(r.user=t,this.sendNotification("notify_update_user",t))}else{var u={type:2,user:t};null!=No[i]?e.setReserved(i,u):e.h[i]=u}this.storage.setDirtyFlag()},setUserPresence:function(e){null==this.userPresences&&(this.userPresences=new xa);var t=e.userId,n="_"+t.high+"_"+t.low,i=this.userPresences;null!=No[n]?i.setReserved(n,e):i.h[n]=e,this.storage.setDirtyFlag()},getUserPresence:function(e){if(null==this.userPresences)return null;var t="_"+e.high+"_"+e.low,n=this.userPresences;return null!=No[t]?n.getReserved(t):n.h[t]},isDepartmentsChanged:function(e,t){return!tt.eqArray(e.departments,t.departments)},setUsersIfLatest:function(e,t){var n=this.ensureDomainUserMap(e),i=go(this,this.setUserIfLatest),r=n;et.iter(t,function(e){i(r,e)})},clearDomainUsers:function(e){this.users.remove("_"+e.high+"_"+e.low)&&this.storage.setDirtyFlag()},clearUsersDepartments:function(e){var t="_"+e.high+"_"+e.low,n=this.users,i=null!=No[t]?n.getReserved(t):n.h[t];if(null!=i)for(var r=new Fa(i,i.arrayKeys());r.hasNext();){var a=r.next();a.user.departments=null,this.sendNotification("notify_update_user",a.user)}this.storage.setDirtyFlag()},removeFriend:function(e,t){var n="_"+e.high+"_"+e.low,i=this.users,r=null!=No[n]?i.getReserved(n):i.h[n];if(null!=r){var a="_"+t.high+"_"+t.low,o=null!=No[a]?r.getReserved(a):r.h[a];null!=o&&(o.type=2)}this.storage.setDirtyFlag()},removeAcquaintance:function(e,t){this.removeFriend(e,t)},getUser:function(e,t){if(null==t)return null;var n,i=new Kn(0,0);if(t.high==i.high&&t.low==i.low)return null;if(null!=this.me){var r=this.me.id;n=null!=r&&null!=t&&r.high==t.high&&r.low==t.low}else n=!1;if(n)return this.me.toDomainUser(e);var a="_"+e.high+"_"+e.low,o=this.users,s=null!=No[a]?o.getReserved(a):o.h[a];if(null!=s){var l="_"+t.high+"_"+t.low,u=null!=No[l]?s.getReserved(l):s.h[l];if(null!=u)return u.user}return null},getUsers:function(e,t){function n(a,e){var t="_"+a.high+"_"+a.low,n=l.users,o=null!=No[t]?n.getReserved(t):n.h[t];if(null==o)return[];if(null!=e)return e.map(function(e){var t=new Kn(0,0);if(e.high==t.high&&e.low==t.low)return null;var n=l.me.id;if(null!=n&&null!=e&&n.high==e.high&&n.low==e.low)return l.me.toDomainUser(a);var i="_"+e.high+"_"+e.low,r=null!=No[i]?o.getReserved(i):o.h[i];return null!=r?r.user:null});for(var i=[],r=o.arrayKeys(),s=new Fa(o,r);s.hasNext();)i.push(s.next().user);return i}var l=this;if(null!=e)return n(e,t);for(var i=this.domains,r=new Fa(i,i.arrayKeys()),a=null;r.hasNext();)a=null==a?n(r.next().id,t):a.concat(n(r.next().id,t));return null==a?[]:a},getTalk:function(e){var t="_"+e.high+"_"+e.low,n=this.talks;return null!=No[t]?n.getReserved(t):n.h[t]},getValidPairTalk:function(n,i){var r=this;return null==this.me?null:et.find(this.getTalks(),function(e){if(!ee.enumEq(e.type,bn.PairTalk))return!1;var t=e.domainId;return null!=t&&null!=i&&t.high==i.high&&t.low==i.low&&(!!et.exists(e.userIds,function(e){return null!=e&&null!=n&&e.high==n.high&&e.low==n.low})&&!!et.exists(e.userIds,function(e){var t=r.me.id;return null!=e&&null!=t&&e.high==t.high&&e.low==t.low}))})},setTalk:function(e){var t=e.id,n="_"+t.high+"_"+t.low,i=this.talks;if(null!=No[n]?i.setReserved(n,e):i.h[n]=e,null!=e.leftUsers)for(var r=this.ensureDomainUserMap(e.domainId),a=0,o=e.leftUsers;a<o.length;){var s=o[a];++a;var l=s.id,u="_"+l.high+"_"+l.low,c=null!=No[u]?r.getReserved(u):r.h[u];if(null!=c){var _;if(2==c.type){var h=s.updatedAt,d=c.user.updatedAt,f=h.high-d.high|0;f=0!=f?f:Sa.ucompare(h.low,d.low),_=0<(h.high<0?d.high<0?f:-1:0<=d.high?f:1)}else _=!1;_&&(c.user=s,this.sendNotification("notify_update_user",s))}else{var m={type:2,user:s};null!=No[u]?r.setReserved(u,m):r.h[u]=m,this.sendNotification("notify_update_user",s)}}return this.storage.setDirtyFlag(),e},getTalks:function(){for(var e=[],t=this.talks.keys();t.hasNext();){var n=t.next(),i=this.talks;e.push(null!=No[n]?i.getReserved(n):i.h[n])}return e},setTalks:function(e){et.iter(e,go(this,this.setTalk))},removeTalk:function(e){if(null!=this.domainUnreadCounts){var t="_"+e.high+"_"+e.low,n=this.talks,i=null!=No[t]?n.getReserved(t):n.h[t];if(null!=i){var r=i.domainId;this.domainUnreadCounts.remove("_"+r.high+"_"+r.low)}}if(null!=this.questions)for(var a=this.getQuestions(e),o=0;o<a.length;){var s=a[o];++o;var l=s.id;this.questions.remove("_"+l.high+"_"+l.low)}this.talks.remove("_"+e.high+"_"+e.low),this.storage.setDirtyFlag()},getTalkStatuses:function(){for(var e=[],t=this.talkStatuses.keys();t.hasNext();){var n=t.next(),i=this.talks;if(null!=No[n]?i.existsReserved(n):i.h.hasOwnProperty(n)){var r=this.talkStatuses;e.push(null!=No[n]?r.getReserved(n):r.h[n])}}return e},getTalkStatus:function(e){var t="_"+e.high+"_"+e.low,n=this.talkStatuses;return null!=No[t]?n.getReserved(t):n.h[t]},setTalkStatus:function(e){var t=e.id,n="_"+t.high+"_"+t.low;if(null!=this.domainUnreadCounts){var i=this.talks,r=null!=No[n]?i.getReserved(n):i.h[n];if(null!=r){var a=r.domainId;this.domainUnreadCounts.remove("_"+a.high+"_"+a.low)}}var o=this.talkStatuses;return null!=No[n]?o.setReserved(n,e):o.h[n]=e,this.sendNotification("brand_badge_changed"),this.storage.setDirtyFlag(),e},removeTalkStatus:function(e){var t="_"+e.high+"_"+e.low;if(null!=this.domainUnreadCounts){var n=this.talks,i=null!=No[t]?n.getReserved(t):n.h[t];if(null!=i){var r=i.domainId;this.domainUnreadCounts.remove("_"+r.high+"_"+r.low)}}this.talkStatuses.remove(t),this.storage.setDirtyFlag()},getDomains:function(){for(var e=[],t=this.domains,n=new Fa(t,t.arrayKeys());n.hasNext();){var i=n.next();e.push(i)}return e},getDomain:function(e){var t="_"+e.high+"_"+e.low,n=this.domains;return null!=No[t]?n.getReserved(t):n.h[t]},setDomainIfLatest:function(e){var t,n=e.id,i="_"+n.high+"_"+n.low,r=this.domains,a=null!=No[i]?r.getReserved(i):r.h[i];if(null!=a){var o=e.updatedAt,s=a.updatedAt,l=o.high-s.high|0;l=0!=l?l:Sa.ucompare(o.low,s.low),t=0<=(o.high<0?s.high<0?l:-1:0<=s.high?l:1)}else t=!0;if(t){var u=this.domains;return null!=No[i]?u.setReserved(i,e):u.h[i]=e,this.storage.setDirtyFlag(),e}return a},removeDomain:function(n){this.domains.remove("_"+n.high+"_"+n.low),this.storage.setDirtyFlag();for(var e=this.getTalks().filter(function(e){var t=e.domainId;return null!=t&&null!=n&&t.high==n.high&&t.low==n.low}),t=0;t<e.length;){var i=e[t];++t,this.removeTalk(i.id),this.removeTalkStatus(i.id)}},getUnreadCount:function(){for(var e=0,t=this.domains.keys();t.hasNext();){var n=t.next();e+=this._getDomainUnreadCount(n)}return e+=this.getDomainInvitesCount()},_getDomainUnreadCount:function(e){var t;if(null!=this.domainUnreadCounts){var n=this.domainUnreadCounts;t=null!=No[e]?n.existsReserved(e):n.h.hasOwnProperty(e)}else t=!1;if(t){var i=this.domainUnreadCounts;return null!=No[e]?i.getReserved(e):i.h[e]}null==this.domainUnreadCounts&&(this.domainUnreadCounts=new xa);for(var r=0,a=this.talkStatuses,o=new Fa(a,a.arrayKeys());o.hasNext();){var s=o.next();if(0!=s.unreadCount){var l,u=s.id,c="_"+u.high+"_"+u.low,_=this.talks,h=null!=No[c]?_.getReserved(c):_.h[c];if(null!=h){var d=h.domainId;l="_"+d.high+"_"+d.low==e}else l=!1;l&&(r+=s.unreadCount)}}var f=this.announcementStatuses,m=null!=No[e]?f.getReserved(e):f.h[e];if(null!=m&&null!=m.unreadCount){var p=this.domains,g=null!=No[e]?p.getReserved(e):p.h[e];null!=g&&g.role.allowReadAnnouncements&&(r+=m.unreadCount)}var v=this.domainUnreadCounts;return null!=No[e]?v.setReserved(e,r):v.h[e]=r,r},getDomainUnreadCount:function(e){return null==e?0:this._getDomainUnreadCount("_"+e.high+"_"+e.low)},getDomainInvites:function(){for(var e=[],t=this.domainInvites.keys();t.hasNext();){var n=t.next(),i=this.domainInvites;e.push(null!=No[n]?i.getReserved(n):i.h[n])}return e},getDomainInvitesCount:function(){var e=0;if(null==this.accountControlGroup)for(var t=this.domainInvites,n=new Fa(t,t.arrayKeys());n.hasNext();){var i=n.next();null!=i.accountControlRequestId&&null!=this.getAccountControlRequest(i.accountControlRequestId)||++e}else for(var r=this.domainInvites,a=new Fa(r,r.arrayKeys());a.hasNext();){a.next();++e}return e},getDomainInvite:function(e){var t="_"+e.high+"_"+e.low,n=this.domainInvites;return null!=No[t]?n.getReserved(t):n.h[t]},setDomainInvite:function(e){var t=e.id,n="_"+t.high+"_"+t.low,i=this.domainInvites;return null!=No[n]?i.setReserved(n,e):i.h[n]=e,this.sendNotification("brand_badge_changed"),this.storage.setDirtyFlag(),e},removeDomainInvite:function(e){this.domainInvites.remove("_"+e.high+"_"+e.low),this.sendNotification("brand_badge_changed"),this.storage.setDirtyFlag()},clearFlowNotificationBadge:function(){this.flowNotificationBadgeStore.clear()},setFlowNotificationBadge:function(e,t){var n=this.flowNotificationBadgeStore.getBadge(e);(null==n||n.version<t.version)&&this.flowNotificationBadgeStore.setBadge(e,t)},removeFlowNotificationBadge:function(e){this.flowNotificationBadgeStore.removeBadge(e)},isFlowNotificationBadgeShownForDomains:function(e){return this.flowNotificationBadgeStore.isBadgeShownForDomains(e)},isFlowNotificationBadgeShownForOneDomain:function(e){return this.flowNotificationBadgeStore.isBadgeShownForOneDomain(e)},getQuestions:function(e,t){var n=[];if(null!=this.questions)for(var i=this.questions,r=new Fa(i,i.arrayKeys());r.hasNext();){var a=r.next(),o=a.talkId;if(null!=o&&null!=e&&o.high==e.high&&o.low==e.low){var s;if(null!=t){var l=a.userId;s=!(null!=t&&null!=l&&t.high==l.high&&t.low==l.low)}else s=!1;s||n.push(a)}}return n},getQuestion:function(e){var t="_"+e.high+"_"+e.low,n=this.questions;return null!=No[t]?n.getReserved(t):n.h[t]},setQuestion:function(e){return e},getAnnouncementStatus:function(e){var t="_"+e.high+"_"+e.low,n=this.announcementStatuses;return null!=No[t]?n.getReserved(t):n.h[t]},setAnnouncementStatus:function(e){var t=e.domainId,n="_"+t.high+"_"+t.low,i=this.announcementStatuses;return null!=No[n]?i.setReserved(n,e):i.h[n]=e,null!=this.domainUnreadCounts&&this.domainUnreadCounts.remove(n),this.sendNotification("brand_badge_changed"),this.storage.setDirtyFlag(),e},removeAnnouncementStatus:function(e){var t="_"+e.high+"_"+e.low;this.announcementStatuses.remove(t),null!=this.domainUnreadCounts&&this.domainUnreadCounts.remove(t),this.sendNotification("brand_badge_changed"),this.storage.setDirtyFlag()},getAccountControlRequests:function(){for(var e=[],t=this.accountControlRequests,n=new Fa(t,t.arrayKeys());n.hasNext();){var i=n.next();e.push(i)}return e},getAccountControlRequest:function(e){var t="_"+e.high+"_"+e.low,n=this.accountControlRequests;return null!=No[t]?n.getReserved(t):n.h[t]},setAccountControlRequest:function(e){var t=e.id,n="_"+t.high+"_"+t.low,i=this.accountControlRequests,r=null!=No[n]?i.getReserved(n):i.h[n];if(null!=r&&r.version>e.version)return r;var a=this.accountControlRequests;return null!=No[n]?a.setReserved(n,e):a.h[n]=e,this.storage.setDirtyFlag(),e},removeAccountControlRequest:function(e){var t="_"+e.high+"_"+e.low;this.accountControlRequests.remove(t),this.storage.setDirtyFlag()},removeAccountControlRequests:function(){this.accountControlRequests=new xa,this.storage.setDirtyFlag()},getAccountControlGroup:function(){return this.accountControlGroup},setAccountControlGroup:function(e){return this.accountControlGroup=e,this.storage.setDirtyFlag(),this.accountControlGroup},updateAccountControlGroup:function(e){if(null!=this.accountControlGroup){var t=this.accountControlGroup.id,n=e.id;if(null!=t&&null!=n&&t.high==n.high&&t.low==n.low){var i=e.group;null!=i&&this.accountControlGroup.group.version<i.version&&(this.accountControlGroup.group=i,this.storage.setDirtyFlag());var r=e.profilePolicy;null!=r&&this.accountControlGroup.profilePolicy.version<r.version&&(this.accountControlGroup.profilePolicy=r,this.storage.setDirtyFlag())}}},removeAccountControlGroup:function(e){var t;if(null!=this.accountControlGroup){var n=this.accountControlGroup.id;t=null!=n&&null!=e&&n.high==e.high&&n.low==e.low}else t=!1;t&&(this.accountControlGroup=null,this.storage.setDirtyFlag())},addReactedConfereceId:function(e){var t="_"+e.high+"_"+e.low,n=this.reactedConferenceIds;null!=No[t]?n.setReserved(t,!0):n.h[t]=!0,this.storage.setDirtyFlag()},removeReactedConfereceId:function(e){this.reactedConferenceIds.remove("_"+e.high+"_"+e.low),this.storage.setDirtyFlag()},isReactedConferenceId:function(e){var t="_"+e.high+"_"+e.low,n=this.reactedConferenceIds;return null!=No[t]?n.existsReserved(t):n.h.hasOwnProperty(t)},filterReactedConferenceIds:function(e){var n=this,t=new xa;et.iter(e.map(function(e){return"_"+e.high+"_"+e.low}).filter(function(e){var t=n.reactedConferenceIds;return null!=No[e]?t.existsReserved(e):t.h.hasOwnProperty(e)}),function(e){null!=No[e]?t.setReserved(e,!0):t.h[e]=!0}),this.reactedConferenceIds=t},getNote:function(e){if(null==this.notes)return null;var t=this.notes,n=e.toString(),i=t;return null!=No[n]?i.getReserved(n):i.h[n]},setNote:function(e,t){if(null==this.notes&&(this.notes=new xa),null==t)return this.fileInfoStore.setNoteFileInfos(e,null),this.notes.remove(e.toString()),t;this.fileInfoStore.setNoteFileInfos(e,t.noteRevision.contentFiles);var n=this.notes,i=e.toString(),r=n;return null!=No[i]?r.setReserved(i,t):r.h[i]=t,t},setNoteRevisionSummary:function(e,t){if(null==this.noteRevisionSummaries&&(this.noteRevisionSummaries=new xa),null==t)return this.noteRevisionSummaries.remove(e.toString()),void this.fileInfoStore.setNoteFileInfos(e,null);var n=this.noteRevisionSummaries,i=e.toString(),r=n;null!=No[i]?r.setReserved(i,t):r.h[i]=t,this.fileInfoStore.setNoteFileInfos(e,t.contentFiles)},getNoteRevisionSummary:function(e){if(null==this.noteRevisionSummaries)return null;var t=this.noteRevisionSummaries,n=e.toString(),i=t;return null!=No[n]?i.getReserved(n):i.h[n]},setNoteLocalEdit:function(e,t){if(null==this.noteLocalEdits&&(this.noteLocalEdits=new xa),null==t){var n=this.noteLocalEdits,i=e.toString(),r=n,a=null!=No[i]?r.getReserved(i):r.h[i];if(null==a)return;return this.noteLocalEdits.remove(e.toString()),this.fileInfoStore.setNoteFileInfosForEdit(e,null),void this.sendNotification("clear_note_local_edit",a)}var o=this.noteLocalEdits,s=e.toString(),l=o;null!=No[s]?l.setReserved(s,t):l.h[s]=t,this.fileInfoStore.setNoteFileInfosForEdit(e,t.getFileInfos()),this.sendNotification("update_note_local_edit",t)},getNoteLocalEdit:function(e){if(null==this.noteLocalEdits)return null;var t=this.noteLocalEdits,n=e.toString(),i=t;return null!=No[n]?i.getReserved(n):i.h[n]},getNoteLocalEdits:function(e){var t=[];if(null!=this.noteLocalEdits)for(var n=this.noteLocalEdits,i=new Fa(n,n.arrayKeys());i.hasNext();){var r=i.next(),a=r.getTalkId();null!=a&&null!=e&&a.high==e.high&&a.low==e.low&&t.push(r)}return t},clear:function(e){this.users=new xa,this.talks=new xa,this.talkStatuses=new xa,this.domains=new xa,this.domainInvites=new xa,this.announcementStatuses=new xa,this.accountControlRequests=new xa,this.accountControlGroup=null,this.reactedConferenceIds=new xa,e&&(this.me=null),this.storage.setDirtyFlag()},init:function(){this.storage=new ji("dataStore"),this.questions=new xa;var e=this.storage.load();if(null!=e&&"1.114_0"==e.shift())return this.me=e.shift(),this.users=e.shift(),this.talks=e.shift(),this.talkStatuses=e.shift(),this.domains=e.shift(),this.domainInvites=e.shift(),this.announcementStatuses=e.shift(),this.accountControlRequests=e.shift(),this.accountControlGroup=e.shift(),this.reactedConferenceIds=e.shift(),void Gi._d("["+$e.dateStr(new Date)+"] ","dataStore is loaded.","","","","");this.clear(!0),Gi._d("["+$e.dateStr(new Date)+"] ","dataStore is initialized.","","","","")},saveIfNeeded:function(){this.storage.isDirty&&(this.storage.save(["1.114_0",this.me,this.users,this.talks,this.talkStatuses,this.domains,this.domainInvites,this.announcementStatuses,this.accountControlRequests,this.accountControlGroup,this.reactedConferenceIds]),Gi._d("["+$e.dateStr(new Date)+"] ","dataStore is saved.","","","",""))},__class__:mr});var pr=function(){ir.call(this,"departmentStore"),this.departmentMap=new xa,this.rootDepartmentIdMap=new xa};(n["albero.proxy.DepartmentStoreProxy"]=pr).__name__=["albero","proxy","DepartmentStoreProxy"],pr.__super__=ir,pr.prototype=i(ir.prototype,{getDepartment:function(e){if(null==e)return null;var t="_"+e.high+"_"+e.low,n=this.departmentMap;return null!=No[t]?n.getReserved(t):n.h[t]},setDepartment:function(e){if(null!=e.parentId){var t=this.getDepartment(e.parentId);null!=t&&(t.addChild(e.id),e.depth=t.depth+1)}var n=e.id,i="_"+n.high+"_"+n.low,r=this.departmentMap;null!=No[i]?r.setReserved(i,e):r.h[i]=e},clearDomainDepartment:function(e){var n=this,t="_"+e.high+"_"+e.low,i=this.rootDepartmentIdMap,r=null!=No[t]?i.getReserved(t):i.h[t];null!=r&&(et.iter(this.getDepartmentsDescendantOrSelf(r),function(e){var t=e.id;n.departmentMap.remove("_"+t.high+"_"+t.low)}),this.rootDepartmentIdMap.remove(t))},getRootDepartmentId:function(e){var t="_"+e.high+"_"+e.low,n=this.rootDepartmentIdMap;return null!=No[t]?n.getReserved(t):n.h[t]},setRootDepartmentId:function(e,t){var n="_"+e.high+"_"+e.low,i=this.rootDepartmentIdMap;null!=No[n]?i.setReserved(n,t):i.h[n]=t},setDepartmentUserCount:function(e){var t=this.getDepartment(e.departmentId);null!=t&&(t.userCount=e,t.userCountLoading=!1)},setUserCountLoading:function(e,t){var n=this.getDepartment(e);null!=n&&(n.userCountLoading=t)},needUserCountLoading:function(e){var t=this.getDepartment(e);return null==t||null==t.userCount&&!t.userCountLoading},clearDomainDepartmentUsers:function(e){var t=this.getRootDepartmentId(e);null!=t&&(et.iter(this.getDepartmentsDescendantOrSelf(t),function(e){e.userCount=null,e.userIds=null,e.userCountLoading=!1}),this.sendNotification("department_user_count_cleared",e))},setDepartmentUsers:function(e,t){var n=this.getDepartment(e);null!=n&&(n.userIds=t)},getDepartmentPath:function(e){return this.getDepartmentsAncestorOrSelf(e)},getDepartmentPathWithoutRoot:function(e){return this.getDepartmentPath(e).filter(function(e){return!e.isRoot()})},getDepartmentsAncestorOrSelf:function(e){var t=[];return this._getDepartmentsAncestorOrSelf(e,t),t},_getDepartmentsAncestorOrSelf:function(e,t){var n=this.getDepartment(e);null!=n&&(null!=n.parentId&&this._getDepartmentsAncestorOrSelf(n.parentId,t),t.push(n))},getDepartmentsDescendantOrSelf:function(e){var t=[];return this._getDepartmentsDescendantOrSelf(e,t),t},_getDepartmentsDescendantOrSelf:function(e,t){var n=this,i=this.getDepartment(e);null!=i&&(t.push(i),null!=i.childrenIds&&et.iter(i.childrenIds,function(e){n._getDepartmentsDescendantOrSelf(e,t)}))},__class__:pr});var gr=function(){ir.call(this,"features")};(n["albero.proxy.FeaturesProxy"]=gr).__name__=["albero","proxy","FeaturesProxy"],gr.__super__=ir,gr.prototype=i(ir.prototype,{canSendMessageOnMultiView:function(e){return!!this.settings.isOnPremises()||this.selectedDomainHasSolution(e,pn.MultiView)},canDetectKeyword:function(e){return!!this.settings.isOnPremises()||this.selectedDomainHasSolution(e,pn.KeywordWatching)},selectedDomainHasSolution:function(e,t){if(null==e)return!1;var n=this.dataStore.getDomain(e);return null!=n&&null!=n.contract&&null!=n.contract.solutionIds&&et.exists(n.contract.solutionIds,function(e){return dn.getSolutionType(e)==t})},canConference:function(e){if(null==e)return!1;var t=this.dataStore.getDomain(e);return null!=t&&null!=t.contract&&t.contract.isConferenceEnalbed()},__class__:gr});var vr=function(){ir.call(this,"fileInfoStore"),this.fileInfoMap=new xa,this.fileIdStrsMap=new xa,this.messageFileIdStrsMap=new xa,this.noteFileIdStrsMap=new xa,this.stagedFileInfosMaxId=0};(n["albero.proxy.FileInfoStoreProxy"]=vr).__name__=["albero","proxy","FileInfoStoreProxy"],vr.__super__=ir,vr.prototype=i(ir.prototype,{ensureStagedFileInfos:function(e){return this.ensureStagedFileIdStrs(e).map(tt.makeFromIdStr).filter(function(e){return null!=e}).map(go(this,this.getFileInfo))},moveStagedFile:function(e,t,n){var i=this.ensureStagedFileIdStrs(e);if(null!=i){var r=i[t];$e.remove(i,r),i.splice(n,0,r)}},ensureStagedFileIdStrs:function(e){var t=e.toString(),n=this.fileIdStrsMap,i=null!=No[t]?n.getReserved(t):n.h[t];if(null==i){i=[];var r=this.fileIdStrsMap;null!=No[t]?r.setReserved(t,i):r.h[t]=i}return i},addStagedFileInfo:function(e,t,n,i){var r=this.createStagedFileInfo(e,n,i),a=r.id,o="_"+a.high+"_"+a.low,s=this.fileInfoMap;null!=No[o]?s.setReserved(o,r):s.h[o]=r;var l=r.id,u="_"+l.high+"_"+l.low;return this.ensureStagedFileIdStrs(t).push(u),r},replaceStagedFileInfo:function(e,t,n,i){var r=this.createStagedFileInfo(e.talkId,n,i);return this.replaceStagedFileInfoFromFileId(e.id,t,r),r},replaceStagedFileInfoFromFileId:function(e,t,n){var i=n.id,r="_"+i.high+"_"+i.low,a=this.fileInfoMap;null!=No[r]?a.setReserved(r,n):a.h[r]=n;var o=this.ensureStagedFileIdStrs(t),s=o.indexOf("_"+e.high+"_"+e.low);if(-1!=s){o.splice(s,1);var l=n.id;o.splice(s,0,"_"+l.high+"_"+l.low),this.removeStagedFileInfo(t,e)}},createStagedFileInfo:function(e,t,n){var i=t,r=new St,a=new Kn(0,--this.stagedFileInfosMaxId);return r.id=a,r.talkId=e,null!=t&&(r.contentType=i.type,r.contentSize=i.size,r.addLocalFile(t),r.name=i.name),null!=n&&r.addLocalThumbInfo(n),r},createStagedFileInfoFromDummyFile:function(e,t,n){var i=new St,r=new Kn(0,--this.stagedFileInfosMaxId);return i.id=r,i.talkId=e,null!=t&&(i.contentType=t.type,i.contentSize=t.size,i.file=t,i.name=t.name),null!=n&&i.addLocalThumbInfo(n),i},createUploadedFileInfo:function(e){var t=new St;return t.id=e.id,t.contentType=e.content_type,t.contentSize=e.content_size,t.url=e.url,t.name=e.name,t},restoreStagedFile:function(e,t){var n=t.id,i="_"+n.high+"_"+n.low,r=this.fileInfoMap;null!=No[i]?r.setReserved(i,t):r.h[i]=t;var a=t.id,o="_"+a.high+"_"+a.low;this.ensureStagedFileIdStrs(e).push(o)},removeStagedFileInfo:function(e,t){var n="_"+t.high+"_"+t.low;$e.remove(this.ensureStagedFileIdStrs(e),n);var i=this.fileInfoMap;(null!=No[n]?i.getReserved(n):i.h[n]).isRemote()||this.fileInfoMap.remove(n)},removeStagedFileInfos:function(e){for(var t=0,n=this.ensureStagedFileIdStrs(e);t<n.length;){var i=n[t];++t,this.fileInfoMap.remove(i)}this.fileIdStrsMap.remove(e.toString())},ensureTalkFileInfos:function(e){return this.ensureTalkFileIds(e).map(go(this,this.fileInfoGetter))},ensureTalkFileIds:function(e){var t="_"+e.high+"_"+e.low,n=this.fileIdStrsMap,i=null!=No[t]?n.getReserved(t):n.h[t];if(null==i){i=[];var r=this.fileIdStrsMap;null!=No[t]?r.setReserved(t,i):r.h[t]=i}return i},getTalkFileInfo:function(e,t,n){return this.getFileInfo(n)},setTalkFileInfo:function(e,t){var n=e.id,i="_"+n.high+"_"+n.low,r=this.fileInfoMap;null!=No[i]?r.setReserved(i,e):r.h[i]=e;var a=this.ensureTalkFileIds(e.talkId);-1==a.indexOf(i)&&a.push(i)},onFileDeleted:function(e){var t=this.getTalkFileInfo(e.talkId,e.messageId,e.fileId);null!=t&&(t.deleted=!0)},getFileInfo:function(e){var t="_"+e.high+"_"+e.low,n=this.fileInfoMap;return null!=No[t]?n.getReserved(t):n.h[t]},getMessageFileInfos:function(e){var t=this,n="_"+e.high+"_"+e.low,i=this.messageFileIdStrsMap;return it.map(it.option(null!=No[n]?i.getReserved(n):i.h[n]),function(e){return e.map(go(t,t.fileInfoGetter))})},setMessageFileInfos:function(e,t){for(var n=0;n<t.length;){var i=t[n];++n;var r=i.id,a="_"+r.high+"_"+r.low,o=this.fileInfoMap;null!=No[a]?o.setReserved(a,i):o.h[a]=i}var s=this.messageFileIdStrsMap,l="_"+e.high+"_"+e.low,u=t.map(go(this,this.fileIdStrGetter)),c=s;null!=No[l]?c.setReserved(l,u):c.h[l]=u},removeMessageFileInfos:function(e){var t="_"+e.high+"_"+e.low,n=this.messageFileIdStrsMap,i=null!=No[t]?n.getReserved(t):n.h[t];if(null!=i)for(var r=0;r<i.length;){var a=i[r];++r,this.fileInfoMap.remove(a)}this.messageFileIdStrsMap.remove("_"+e.high+"_"+e.low)},isAllFileDeletedOnMessage:function(e){var t,n=this.getMessageFileInfos(e);switch(n[1]){case 0:t=n[2];break;case 1:t=[]}return!et.exists(t,function(e){return!e.deleted})},getNoteFileInfos:function(e){var t=this,n=e.toString(),i=this.noteFileIdStrsMap;return it.map(it.option(null!=No[n]?i.getReserved(n):i.h[n]),function(e){return e.map(go(t,t.fileInfoGetter))})},setNoteFileInfos:function(e,t){var n=e.toString(),i=this.noteFileIdStrsMap,r=null!=No[n]?i.getReserved(n):i.h[n];if(null!=r)for(var a=0;a<r.length;){var o=r[a];++a,this.fileInfoMap.remove(o)}if(this.noteFileIdStrsMap.remove(n),null!=t&&0!=t.length){for(var s=0;s<t.length;){var l=t[s];++s;var u=l.id,c="_"+u.high+"_"+u.low,_=this.fileInfoMap;null!=No[c]?_.setReserved(c,l):_.h[c]=l}var h=this.noteFileIdStrsMap,d=t.map(go(this,this.fileIdStrGetter)),f=h;null!=No[n]?f.setReserved(n,d):f.h[n]=d}},getNoteFileInfosForEdit:function(e){var t=this,n=e.toString()+"edit",i=this.noteFileIdStrsMap;return it.map(it.option(null!=No[n]?i.getReserved(n):i.h[n]),function(e){return e.map(go(t,t.fileInfoGetter))})},setNoteFileInfosForEdit:function(e,t){var n=e.toString()+"edit",i=this.noteFileIdStrsMap,r=null!=No[n]?i.getReserved(n):i.h[n];if(null!=r)for(var a=0;a<r.length;){var o=r[a];++a,this.fileInfoMap.remove(o)}if(this.noteFileIdStrsMap.remove(n),null!=t&&0!=t.length){for(var s=0;s<t.length;){var l=t[s];++s;var u=l.id,c="_"+u.high+"_"+u.low,_=this.fileInfoMap;null!=No[c]?_.setReserved(c,l):_.h[c]=l}var h=this.noteFileIdStrsMap,d=t.map(go(this,this.fileIdStrGetter)),f=h;null!=No[n]?f.setReserved(n,d):f.h[n]=d}},fileIdStrGetter:function(e){var t=e.id;return"_"+t.high+"_"+t.low},fileInfoGetter:function(e){var t=this.fileInfoMap;return null!=No[e]?t.getReserved(e):t.h[e]},__class__:vr});var yr=function(){};(n["albero.proxy.FileServiceProxy"]=yr).__name__=["albero","proxy","FileServiceProxy"],yr.__interfaces__=[er],yr.prototype={__class__:yr};var Sr=function(){};(n["albero.proxy.FileServiceProxyFactory"]=Sr).__name__=["albero","proxy","FileServiceProxyFactory"],Sr.newInstance=function(){return new wr("fileService")};var wr=function(e){ir.call(this,e)};(n["albero.proxy.FileServiceProxyImplForHubot"]=wr).__name__=["albero","proxy","FileServiceProxyImplForHubot"],wr.__interfaces__=[yr],wr.getContentTypeByFileName=function(e,t){return(new w).resolve({name:e,type:t})},wr.__super__=ir,wr.prototype=i(ir.prototype,{downloadUrl:function(e,t){if(null==t&&(t=!1),null==e||0==e.length)return"data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(W.startsWith(e,this.settings.getValidHost())){var n=this.settings.getAccessToken(),i=e;return-1!=e.indexOf("?")?i+="&":i+="?",i+="Authorization=ALB%20"+n,t&&(i+="&download=true"),i}return e},download:function(e,i,r){var a=this;if(e=this.downloadUrl(e),W.startsWith(e,"data:"))r(null,new Error("download URL was not resolved"));else{var t=Za.parse(e);null!=Eo.proxyURL&&(t.agent=Vi.createAgent(Eo.proxyURL));var n=Qa.request(t,function(e){var t=e.headers.location;if(null==t)if(2==Math.floor(e.statusCode/100)){var n=qa.createWriteStream(i);e.on("data",function(e){n.write(e)}),e.on("end",function(){n.end(),n.on("finish",function(){r(i,null)})}),e.on("error",function(e){r(null,e)}),n.on("error",function(e){r(null,e)})}else r(null,new Error("HTTP request failed ("+e.statusCode+" "+e.statusMessage+")"));else a.download(t,i,r)});n.on("error",function(e){r(null,e)}),n.end()}},uploadForNodeJS:function(e,t,r){var n=r,a=Za.parse(e.put_url);a.method="PUT";a.headers={},a.headers["Content-Length"]=""+n.size;var i=e.post_form;return a.headers["Content-Type"]=i["Content-Type"],a.headers["Content-Disposition"]=i["Content-Disposition"],null!=Eo.proxyURL&&(a.agent=Vi.createAgent(Eo.proxyURL)),new Promise(function(n,i){var t=Qa.request(a,function(e){if(2!=Math.floor(e.statusCode/100)){var t="";return e.on("data",function(e){t+=e}),void e.on("end",function(){i(e.statusCode+": "+t)})}Wi.resolveVoid(n)});t.on("error",function(e){i(e.message)});var e=qa.createReadStream(r.path);e.on("data",function(e){t.write(e)}),e.on("end",function(){t.end()}),e.on("error",function(){t.end()})})},upload:function(e,t,n){return this.uploadForNodeJS(e,t,n)},createDummyFile:function(e,t,n){var i=W.replace(e,"/","\\").split("\\");if(0==i.length)return null;var r=i[i.length-1];if(null!=t&&(r=t),0==r.length)return null;var a=wr.getContentTypeByFileName(r,n);return{name:r,size:0|qa.statSync(e).size,type:a,path:e}},asyncCreateThumbnail:function(e){return Promise.reject(null)},__class__:wr});var Tr=function(){ir.call(this,"keywordWatcher")};(n["albero.proxy.KeywordWatcherProxy"]=Tr).__name__=["albero","proxy","KeywordWatcherProxy"],Tr.__super__=ir,Tr.prototype=i(ir.prototype,{onMessageCreated:function(e){if(null!=e){var t,n=it.map(it.option(this.dataStore.getTalk(e.talkId)),function(e){return e.domainId});switch(n[1]){case 0:t=n[2];break;case 1:t=this.settings.getSelectedDomainId()}if(this.features.canDetectKeyword(t)){var i;if(this.settings.getBrowserSettings().keywordWatchingSelfMessage)i=!1;else{var r=this.dataStore,a=e.userId;if(null!=r.me){var o=r.me.id;i=null!=o&&null!=a&&o.high==a.high&&o.low==a.low}else i=!1}if(!i){var s=e.messageStringForKeywordDetection(this.settings.getBrowserSettings().keywordWatchingActionReply);this.detectKeyword(s,e.type,e.id,t,e.talkId)}}}},onAnnouncementCreated:function(e){if(null!=e&&this.features.canDetectKeyword(e.domainId)){var t=Ft.getDisplayTextWithoutEscape(e.type,e.content);this.detectKeyword(t,e.type,e.id,e.domainId,null)}},detectKeyword:function(s,l,u,c,_){var h=this;this.reserveOnNormalizedKeywordPrepared(function(e){for(var t=W.htmlEscape(s,!0),n=e.keys();n.hasNext();){var i=n.next(),r=e.get(i);if(null!=r&&0!=r.length&&Ar.match(l,i))for(var a=0;a<r.length;){var o=r[a];if(++a,0!=o.search(t).length)return void h.addkeywordDetection(c,_,u)}}})},reserveOnNormalizedKeywordPrepared:function(e){var t=this.settings.getBrowserSettings().keywordWatchingText;if(this.cachedKeyword!=t){this.cachedKeyword=t,this.cachedNormalizedKeywordsMap=new Ca;for(var n=0,i=Nr.__empty_constructs__;n<i.length;){var r=i[n];++n,this.cachedNormalizedKeywordsMap.set(r,[])}for(var a=0,o=Ir.parse(t);a<o.length;){var s=o[a];++a,this.cachedNormalizedKeywordsMap.get(s.type).push(new zi(s.word,!0,Qi.normalize))}}e(this.cachedNormalizedKeywordsMap)},addkeywordDetection:function(e,t,n){null==this.detectedDomainTalkIdStrings&&(this.detectedDomainTalkIdStrings=new xa);var i=this.getKey(e,t);if(null!=i)if(this.hasKeywordDetection(e,t)){var r=this.detectedDomainTalkIdStrings;null!=No[i]?r.setReserved(i,n):r.h[i]=n}else{var a=this.detectedDomainTalkIdStrings;null!=No[i]?a.setReserved(i,n):a.h[i]=n;var o=this.settings.getBrowserSettings().keywordWatchingEmphasis;this.sendNotification("keyword_detaction_updated",{domainId:e,talkId:t,detected:!0,emphasis:o})}},readKeywordDetection:function(e,t,n){if(!this.settings.getBrowserSettings().keywordWatchingEmphasis){var i,r=this.getDetectId(e,t);if(Gi._d("["+$e.dateStr(new Date)+"] ","readKeywordDetection",r,n,"",""),null!=r){var a=n.high-r.high|0;a=0!=a?a:Sa.ucompare(n.low,r.low),i=0<=(n.high<0?r.high<0?a:-1:0<=r.high?a:1)}else i=!1;i&&this.removeKeywordDetection(e,t)}},removeKeywordDetection:function(e,t){if(null!=this.detectedDomainTalkIdStrings){var n=this.getKey(e,t);if(null!=n){this.detectedDomainTalkIdStrings.remove(n);var i=this.settings.getBrowserSettings().keywordWatchingEmphasis;this.sendNotification("keyword_detaction_updated",{domainId:e,talkId:t,detected:!1,emphasis:i})}}},removeKeywordDetectionAll:function(){if(null!=this.detectedDomainTalkIdStrings)for(var e=this.settings.getBrowserSettings().keywordWatchingEmphasis,t=this.detectedDomainTalkIdStrings.keys();t.hasNext();){var n=t.next();if(W.startsWith(n,"talk_")){var i=n.substring("talk_".length),r=tt.makeFromIdStr(i);this.sendNotification("keyword_detaction_updated",{domainId:null,talkId:r,detected:!1,emphasis:e})}else if(W.startsWith(n,"announcement_")){var a=n.substring("announcement_".length),o=tt.makeFromIdStr(a);this.sendNotification("keyword_detaction_updated",{domainId:o,talkId:null,detected:!1,emphasis:e})}this.detectedDomainTalkIdStrings.remove(n)}},getDetectId:function(e,t){if(null==this.detectedDomainTalkIdStrings)return null;var n=this.getKey(e,t);if(null==n)return null;var i=this.detectedDomainTalkIdStrings;return null!=No[n]?i.getReserved(n):i.h[n]},hasKeywordDetection:function(e,t){return null!=this.getDetectId(e,t)},getKey:function(e,t){return null==e&&null==t?null:null!=t?"talk__"+t.high+"_"+t.low:"announcement__"+e.high+"_"+e.low},__class__:Tr});var Ir=function(){};(n["albero.proxy.KeywordParser"]=Ir).__name__=["albero","proxy","KeywordParser"],Ir.parse=function(e){var t=W.htmlEscape(e,!0),n=new y("&quot;(.*?)&quot;","g").map(t,function(e){return Ir.encodeSpace(e.matched(1))});return new y("[  ]","g").split(n).filter(k.isNotEmpty).map(Ir.decodeSpace).map(Ir.createParsedKeyword)},Ir.encodeSpace=function(e){return W.replace(W.replace(e," ","&SPACE")," ","&FULL_PITCH_SPACE")},Ir.decodeSpace=function(e){return W.replace(W.replace(e,"&SPACE"," "),"&FULL_PITCH_SPACE"," ")},Ir.createParsedKeyword=function(e){var t=new y("\\[type:([A-Za-z]+)\\](.*)","g");if(t.match(e)){var n=t.matched(1),i=t.matched(2),r=Ar.getKeywordTypeByMessageTypeString(n);if(r!=Nr.normal)return new Er(r,i)}return new Er(Nr.normal,e)};var Er=function(e,t){this.type=e,this.word=t};(n["albero.proxy.ParsedKeyword"]=Er).__name__=["albero","proxy","ParsedKeyword"],Er.prototype={__class__:Er};var Nr=n["albero.proxy.KeywordType"]={__ename__:["albero","proxy","KeywordType"],__constructs__:["normal","selectOneReplyOnly","yesOrNoReplyOnly","todoDoneOnly"]};Nr.normal=["normal",0],Nr.normal.toString=s,(Nr.normal.__enum__=Nr).selectOneReplyOnly=["selectOneReplyOnly",1],Nr.selectOneReplyOnly.toString=s,(Nr.selectOneReplyOnly.__enum__=Nr).yesOrNoReplyOnly=["yesOrNoReplyOnly",2],Nr.yesOrNoReplyOnly.toString=s,(Nr.yesOrNoReplyOnly.__enum__=Nr).todoDoneOnly=["todoDoneOnly",3],Nr.todoDoneOnly.toString=s,(Nr.todoDoneOnly.__enum__=Nr).__empty_constructs__=[Nr.normal,Nr.selectOneReplyOnly,Nr.yesOrNoReplyOnly,Nr.todoDoneOnly];var Ar=function(){};(n["albero.proxy.KeywordTypeHelper"]=Ar).__name__=["albero","proxy","KeywordTypeHelper"],Ar.getKeywordType=function(e){return null!=e?Ar.getKeywordTypeByMessageTypeString(Ft.typeString(e)):Nr.normal},Ar.getKeywordTypeByMessageTypeString=function(e){if(null!=e)switch(e){case"selectOneReply":return Nr.selectOneReplyOnly;case"todoDone":return Nr.todoDoneOnly;case"yesOrNoReply":return Nr.yesOrNoReplyOnly}return Nr.normal},Ar.match=function(e,t){switch(t[1]){case 0:return!0;case 1:return e==xt.selectOneReply;case 2:return e==xt.yesOrNoReply;case 3:return e==xt.todoDone}},Ar.createFilterClassStringFromMessageType=function(e){return Ar.createFilterClassString(Ar.getKeywordType(e))},Ar.createFilterClassString=function(e){return"keyword_type_"+K.string(e)};var br=function(){ir.call(this,"lastUsedAtUpdater")};(n["albero.proxy.LastUsedAtUpdaterProxy"]=br).__name__=["albero","proxy","LastUsedAtUpdaterProxy"],br.__super__=ir,br.prototype=i(ir.prototype,{startPolling:function(e){if(null==this.pollingTimer){var t,n=this.getLastUsedExpiredAt();if(null==n)t=0;else{var i=n.high,r=n.low;t=4294967296*i+(0<=r?r:r+4294967296)-(new Date).getTime()|0}if(t<=0)e(),this.pollingTimer=new Ea(6e5),this.pollingTimer.run=e;else{var a=go(this,this.startPolling),o=e;Ea.delay(function(){a(o)},t)}}},stopPolling:function(){null!=this.pollingTimer&&(this.pollingTimer.stop(),this.pollingTimer=null)},getLastUsedExpiredAt:function(){return null!=this.lastUsedExpiredAtCache?this.lastUsedExpiredAtCache:this.settings.getLastUsedExpiredAt()},update:function(){this.lastUsedExpiredAtCache=I.afterAsInt64(6e5),this.settings.setLastUsedExpiredAt(this.lastUsedExpiredAtCache)},__class__:br});var Dr=function(){ir.call(this,"limitations")};(n["albero.proxy.LimitationsProxy"]=Dr).__name__=["albero","proxy","LimitationsProxy"],Dr.__super__=ir,Dr.prototype=i(ir.prototype,{getMaxTalkers:function(){var t=this,e=it.flatMap(it.flatMap(it.option(this.settings.getSelectedDomainId()),function(e){return it.option(t.dataStore.getDomain(e))}),function(e){return e.getMaxTalkers()});switch(e[1]){case 0:return e[2];case 1:return this.settings.getConfiguration().maxTalkers}},__class__:Dr});var kr=function(){ir.call(this,"messageStore")};(n["albero.proxy.MessageStoreProxy"]=kr).__name__=["albero","proxy","MessageStoreProxy"],kr.__super__=ir,kr.prototype=i(ir.prototype,{onRegister:function(){this.messages=new xa},getMessage:function(e){if(null==e)return Ra.None;var t="_"+e.high+"_"+e.low,n=this.messages;return it.option(null!=No[t]?n.getReserved(t):n.h[t])},setMessage:function(e){},removeMessage:function(e){this.messages.remove("_"+e.high+"_"+e.low)},onFileDeleted:function(t){it.foreach(this.getMessage(t.messageId),function(e){e.deleteFile(t)})},onConferenceClose:function(e){it.foreach(this.getMessage(e.messageId),function(e){e.close()})},onActionStampClose:function(e){it.foreach(this.getMessage(e),function(e){e.close()})},onDeleteFavoriteMessage:function(t){var e=this.getMessage(t.getMessageId());it.foreach(e,function(e){e.updateFavorite(t)})},onAddFavoriteMessage:function(t){var e=this.getMessage(t.getMessageId());it.foreach(e,function(e){e.updateFavorite(t)}),it.isEmpty(e)&&this.setMessage(t.getMessage())},__class__:kr});var Cr=function(){this.connectionStatus=v.Ok,ir.call(this,"rpc"),this.responseHandlers=new Oa,this.errorHandler=go(this,this.onServerErrorWithMethod),this.connectionKeeper=new Or(go(this,this.ping))};(n["albero.proxy.MsgPackRpcProxy"]=Cr).__name__=["albero","proxy","MsgPackRpcProxy"],Cr.__super__=ir,Cr.prototype=i(ir.prototype,{initWebSocket:function(){null==this.ws&&(this.ws=Zi.newInstance(Eo.endpoint,{onopen:go(this,this.onOpen),onmessage:go(this,this.onMessage),onclose:go(this,this.onClose),onpong:go(this,this.onPong)}),Cr.pingAt=null)},finishWebSocket:function(){if(null==this.ws)return null;this.ws.close();var e=this.ws;return this.ws=null,Cr.pingAt=null,this.lastUsedAtUpdater.stopPolling(),e},onRegister:function(){this.initWebSocket(),this.connectionKeeper.start()},onRemove:function(){this.connectionKeeper.stop(),this.finishWebSocket()},onOpen:function(){this.connectionStatus=v.Ok,this.connectionKeeper.setConnected(!0),this.sendNotification("SignIn")},onPong:function(e){Cr.pingAt=null;var t="PONG "+K.string(e);Gi._d("["+$e.dateStr(new Date)+"] ",t,"","","","")},onMessage:function(e){var t=this,n=new eo(e,!0).o,i=Va.__cast(n[0],vo);if(1==i&&4==n.length){var r=Va.__cast(n[1],vo),a=n[2],o=n[3],s=this.responseHandlers.h[r];if(null==s)return void Gi._e("["+$e.dateStr(new Date)+"] ","No ResponseHandler prepared. msgId:%s error:%s result:",r,a,o,"");var l=s.method;if(Gi._d("["+$e.dateStr(new Date)+"] ","response received. method:",l," data:",n,""),null==a){var u=s.onSuccess;null!=u&&u(o)}else{var c=s.method;Gi._e("["+$e.dateStr(new Date)+"] ","Receive Error Response. method:",c," error:",a,"");var _=s.onError;null!=_?_(a):null!=this.errorHandler&&this.errorHandler(s.method,a)}this.responseHandlers.remove(r)}else if(0==i&&4==n.length){var h=Va.__cast(n[1],vo),d=Va.__cast(n[2],String),f=Va.__cast(n[3],Array);if(Gi._d("["+$e.dateStr(new Date)+"] ","request received. method:",d,"","",""),0==f.length)return void Gi._e("["+$e.dateStr(new Date)+"] ","empty params.","","","","");this.broadcast.handleNotification(d,f[0],function(){null!=t.ws?(Gi._d("["+$e.dateStr(new Date)+"] ","response sent. method:",d,"","",""),t.ws.send(new to([1,h,null,!0]).o.getBytes())):Gi._e("["+$e.dateStr(new Date)+"] ","websocket was finished.","","","","")})}},onClose:function(e,t,n){Gi._i("["+$e.dateStr(new Date)+"] ","onClose. code:"+e+", reason:"+t+", wasClean:"+(null==n?"null":""+n),"","","",""),1001==e&&n||(this.connectionStatus=1e3!=e&&1005!=e||"concurrent access"!=t?1e3!=e&&1005!=e||"forcibly closed"!=t?v.Error:v.ForcibliyClosedError:v.ConcurrentAccessError,this.connectionStatus==v.ForcibliyClosedError?this.sendNotification("SignOut"):this.sendNotification("Url",be.FORWARD(V.error))),this.finishWebSocket(),this.connectionKeeper.setConnected(!1)},restart:function(e){null==e&&(e=500);for(var t=this,n=this.finishWebSocket(),i=this.responseHandlers.keys();i.hasNext();){var r=i.next();this.responseHandlers.remove(r)}var a=null;a=function(){null==n||n.isClosed()?t.initWebSocket():Ea.delay(a,100)},Ea.delay(a,e)},call:function(e,t,n,i){if(null!=this.ws){null==t&&(t=[]);var r=Cr.lastMsgId++,a=this.responseHandlers,o=new Mr(e,n,i);a.h[r]=o;var s=[0,r,e,t],l=new to(s).o.getBytes();this.ws.send(l),Gi._d("["+$e.dateStr(new Date)+"] ","send request. data:",s,"","","")}else{var u=this.data;Gi._e("["+$e.dateStr(new Date)+"] ","disconnected. data:",u,"","","")}},ping:function(){switch(this.connectionStatus[1]){case 2:case 3:return}if(null==this.ws||this.ws.isClosed()){this.restart();var e="restart connection. "+Cr.pingAt+" "+K.string(null==this.ws||this.ws.isClosed());Gi._d("["+$e.dateStr(new Date)+"] ",e,"","","","")}else if(0<Cr.pingAt){this.restart();var t="restart connection. "+Cr.pingAt+" "+K.string(null==this.ws||this.ws.isClosed());Gi._d("["+$e.dateStr(new Date)+"] ",t,"","","","")}else{var n="before pingAt "+Cr.pingAt;Gi._d("["+$e.dateStr(new Date)+"] ",n,"","","",""),this.connectionKeeper.isConnected()&&(this.ws.ping("PING"),Cr.pingAt=(new Date).getTime(),Gi._d("["+$e.dateStr(new Date)+"] ","send ping","","","",""))}},onServerErrorWithMethod:function(e,t){this.onServerError(t)},onServerError:function(e){if(this.sendNotification("error_occurred",e),503==e.code&&"service temporarily unavailable"==e.message){var t=e.detail.retry_after;this.restart(1e3*t)}"invalid session"==e.message&&this.restart()},__class__:Cr});var Or=function(e){this.connected=!1,this.ping=e};(n["albero.proxy._MsgPackRpcProxy.ConnectionKeeper"]=Or).__name__=["albero","proxy","_MsgPackRpcProxy","ConnectionKeeper"],Or.prototype={start:function(){},stop:function(){this.deleteTimer()},setConnected:function(e){this.connected==e&&null!=this.timer||(this.connected=e,this.resetTimer())},isConnected:function(){return this.connected},resetTimer:function(){var i=this;if(this.deleteTimer(),this.connected)this.timer=new Ea(45e3),this.timer.run=this.ping;else{var r=null;(r=function(t){var n=0|Math.min(2*t,45e3);return function(){i.ping();var e=r(n);i.timer=Ea.delay(e,t)}})(3e3)()}},deleteTimer:function(){null!=this.timer&&(this.timer.stop(),this.timer=null)},__class__:Or};var Mr=function(e,t,n){this.method=e,this.onSuccess=t,this.onError=n};(n["albero.proxy._MsgPackRpcProxy.ResponseHandler"]=Mr).__name__=["albero","proxy","_MsgPackRpcProxy","ResponseHandler"],Mr.prototype={__class__:Mr};var Rr=function(e){this.code=e.code,this.message=e.message,this.detail=e.detail};(n["albero.proxy.Error"]=Rr).__name__=["albero","proxy","Error"],Rr.prototype={__class__:Rr};var Fr=function(){};(n["albero.proxy.ErrorConverter"]=Fr).__name__=["albero","proxy","ErrorConverter"],Fr.toLocalError=function(e,t){return{code:t.code,message:t.message,detail:t.detail,localErrorType:e}};var xr=function(){ir.call(this,"readStatusUpdater"),this.updateReadStatusesTimers=new xa,this.updateReadAnnouncementStatusesTimers=new xa};(n["albero.proxy.ReadStatusUpdaterProxy"]=xr).__name__=["albero","proxy","ReadStatusUpdaterProxy"],xr.__super__=ir,xr.prototype=i(ir.prototype,{updateReadStatuses:function(e,t){var n=this,i=this.dataStore.getTalkStatus(e);if(null!=i&&i.updateByReadingMessages(t,this.dataStore.me.id)){this.dataStore.setTalkStatus(i);var r="_"+e.high+"_"+e.low,a=this.updateReadStatusesTimers,o=null!=No[r]?a.getReserved(r):a.h[r];null!=o&&o.stop();var s=i.maxReadMessageId,l=Ea.delay(function(){n.updateReadStatusesTimers.remove(r),null!=n.dataStore.getTalkStatus(e)&&n.api.updateReadStatuses(e,s)},1e3),u=this.updateReadStatusesTimers;null!=No[r]?u.setReserved(r,l):u.h[r]=l}},updateAnnouncementReadStatus:function(e,t){var n=this,i=this.dataStore.getAnnouncementStatus(e);if(null!=i&&i.updateByReadingAnnouncements(t)){this.dataStore.setAnnouncementStatus(i);var r="_"+e.high+"_"+e.low,a=this.updateReadAnnouncementStatusesTimers,o=null!=No[r]?a.getReserved(r):a.h[r];null!=o&&o.stop();var s=i.maxReadAnnouncementId;o=Ea.delay(function(){n.updateReadAnnouncementStatusesTimers.remove(r),n.api.updateAnnouncementReadStatus(e,s)},1e3);var l=this.updateReadAnnouncementStatusesTimers;null!=No[r]?l.setReserved(r,o):l.h[r]=o}},__class__:xr});var Ur=function(){ir.call(this,"routing")};(n["albero.proxy.RoutingProxy"]=Ur).__name__=["albero","proxy","RoutingProxy"],Ur.__super__=ir,Ur.prototype=i(ir.prototype,{onRegister:function(){},init:function(){null==this.router&&(this.sendNotification("first_routing_will_start"),this.router=new Pr(this,this.settings,this.dataStore),this.router.start())},forward:function(e){this.init(),this.router.forward(e)},redirect:function(e,t){this.init(),this.router.redirect(e,t)},back:function(){null!=this.router&&this.router.back()},stop:function(){null!=this.router&&this.router.stop()},__class__:Ur});var Pr=function(e,t,n){this.proxy=e,this.settings=t,this.dataStore=n,this.urlConverterDelegate=new Lr(t,n)};(n["albero.proxy._RoutingProxy.LocalRouter"]=Pr).__name__=["albero","proxy","_RoutingProxy","LocalRouter"],Pr.prototype={notify:function(e){var t=this.getDomainId(e);this.settings.setSelectedDomainId(t),this.proxy.sendNotification("current_page_changed",e)},start:function(){},forward:function(e){0!=e[1]&&this.notify(e)},redirect:function(e,t){},redirectWithHash:function(){},back:function(){this.notify(this.prev)},stop:function(){},getDomainId:function(e){switch(e[1]){case 2:return e[2];case 3:return e[2];case 4:return e[2];case 5:return e[2];case 6:return e[2];case 7:return e[2];case 11:return e[2];default:return null}},parseFragment:function(e){return M.createUrls(e,this.urlConverterDelegate)},toFragment:function(e){return M.createFragment(e,this.urlConverterDelegate)},__class__:Pr};var Lr=function(e,t){this.settings=e,this.dataStore=t};(n["albero.proxy.UrlConverterDelegate"]=Lr).__name__=["albero","proxy","UrlConverterDelegate"],Lr.__interfaces__=[R],Lr.prototype={isMultiViewMode:function(){return this.settings.isMultiViewMode()},getLastSelectedDomainId:function(){return it.option(this.settings.getLastSelectedDomainId())},getFallbackDomainId:function(){var e;switch(it.flatMap(this.getLastSelectedDomainId(),go(this,this.getDomain))[1]){case 0:e=it.flatMap(this.getLastSelectedDomainId(),go(this,this.getDomain));break;case 1:e=this.getOldestDomain()}return it.map(e,function(e){return e.id})},getDomain:function(e){return it.option(this.dataStore.getDomain(e))},getOldestDomain:function(){return new mt(this.dataStore.getDomains()).getOldestDomain()},__class__:Lr};var Br=function(){ir.call(this,"searchService")};(n["albero.proxy.SearchServiceProxy"]=Br).__name__=["albero","proxy","SearchServiceProxy"],Br.__super__=ir,Br.prototype=i(ir.prototype,{isSearching:function(){return this.searching},clearSearching:function(){this.searching=!1},isRecentParams:function(e){return null!=this.recentParams&&null!=e&&this.recentParams.eq(e)},clearRecentParams:function(){this.recentParams=null},clearEditingParams:function(){this.editingParams=null},saveParams:function(e){this.editingParams=e,this.recentParams=e.copy()},updateTalkIdParam:function(e){this.assureParams(),this.editingParams.talkId=e},updateSearchTypeParam:function(e){this.assureParams(),this.editingParams.searchType=e},updateFromUserIdParam:function(e){this.assureParams(),this.editingParams.fromUserId=e},updateKeywordParam:function(e){this.assureParams(),this.editingParams.keyword=e},updateDomainIdParam:function(e){this.assureParams(),this.editingParams.domainId=e},updateSinceTextParam:function(e){this.assureParams(),this.editingParams.sinceText=e},updateUntilTextParam:function(e){this.assureParams(),this.editingParams.untilText=e},assureParams:function(){if(null==this.editingParams){var e=this.settings.getSelectedDomainId(),t={domain_id_str:"_"+e.high+"_"+e.low};this.editingParams=new sn(t)}},prepareForSearching:function(e,t){this.searching=!0,null==t&&this.sendNotification("notify_search_prepare",{searching:!0,params:e})},notifySearchMessagesFail:function(){this.searching=!1,this.sendNotification("notify_search_messages_fail",{})},notifySearchAttachmentsFail:function(){this.searching=!1,this.sendNotification("notify_search_attachments_fail",{})},saveSearchMessagesResult:function(e){null==this.contextMap&&(this.contextMap=new xa),this.messagesNextMarker=e.nextMarker,null==e.marker&&(this.hitMessageIdSet=new xa);for(var t=0,n=e.contents;t<n.length;){var i=n[t];++t;var r=i.messages[0].id,a="_"+r.high+"_"+r.low,o=this.contextMap;null!=No[a]?o.setReserved(a,i):o.h[a]=i,this.hitMessageIdSet=et.fold(i.messages,function(e,t){if(e.hit){var n=e.id,i="_"+n.high+"_"+n.low;null!=No[i]?t.setReserved(i,1):t.h[i]=1}return t},this.hitMessageIdSet)}this.searching=!1,this.sendNotification("notify_search_messages",e)},saveSearchAttachmentsResult:function(e){null==this.attachmentsMap&&(this.attachmentsMap=new xa),this.attachmentsNextMarker=e.nextMarker;for(var t=0,n=e.contents;t<n.length;){var i=n[t];++t;var r=i.attachmentId,a="_"+r.high+"_"+r.low,o=this.attachmentsMap;null!=No[a]?o.setReserved(a,i):o.h[a]=i}this.searching=!1,this.sendNotification("notify_search_attachments",e)},getHitContext:function(e){var t=this.contextMap;return null!=No[e]?t.getReserved(e):t.h[e]},getFileInfo:function(e){var t=this.attachmentsMap;return null!=No[e]?t.getReserved(e):t.h[e]},isHitMessage:function(e){var t="_"+e.high+"_"+e.low,n=this.hitMessageIdSet;return null!=No[t]?n.existsReserved(t):n.h.hasOwnProperty(t)},reserveOnNormalizedKeywordPrepared:function(e){var t=this;if(null!=this.recentParams&&null!=this.recentParams.keyword){var n=null==this.recentParams?"":this.recentParams.keyword;if(this.cachedKeyword!=n){this.cachedKeyword=n,null==this.cachedNormalizedKeywords?this.cachedNormalizedKeywords=[]:this.cachedNormalizedKeywords.splice(0,this.cachedNormalizedKeywords.length);var i=new y("[  ]","g").split(W.htmlEscape(n,!0));et.iter(i.filter(k.isNotEmpty),function(e){t.cachedNormalizedKeywords.push(new zi(e,!0,Qi.normalize))})}e(this.cachedNormalizedKeywords)}},__class__:Br});var Hr=function(){ir.call(this,"session"),this.createSessionCount=0};(n["albero.proxy.SessionProxy"]=Hr).__name__=["albero","proxy","SessionProxy"],Hr.__super__=ir,Hr.prototype=i(ir.prototype,{start:function(e){this.api.createSession(e,go(this,this.onSessionCreated))},onSessionCreated:function(e){var t,n=this;if(e.notification){var i=this.dataStore,r=e.user.id;if(null!=i.me){var a=i.me.id;t=null!=a&&null!=r&&a.high==r.high&&a.low==r.low}else t=!1}else t=!1;var o=this.dataStore,s=e.user;o.me=s;for(var l=0,u=o.getDomains();l<u.length;){var c=u[l];++l,o.sendNotification("notify_update_user",o.me.toDomainUser(c.id))}o.sendNotification("current_user_changed",s),o.storage.setDirtyFlag(),this.settings.setConfiguration(e.configuration),this.settings.setDeviceId(e.device.device_id),this.sendNotification("data_recovering"),Promise.all([Yi.asyncPrepare(),Qi.asyncAssureNormalize()]).then(function(e){t?n.prepareNecessaryDataFromCache():(n.dataStore.clear(!1),n.prepareNecessaryDataFromServer()),n.createSessionCount++})},prepareNecessaryDataFromServer:function(){var a=this;this.api.resetNotification(function(e){function r(){4==(t+=1)&&a.api.getAllUserIdentifiers(go(a,a.onNecessaryDataPrepared))}var t=0;a.api.getDomains(function(){var e=a.dataStore.getDomains(),t=0;0<e.length?a.api.getAnnouncementStatuses(function(){(t+=1)==e.length&&r()}):r();function n(){2==(i+=1)&&a.api.getTalks(r)}var i=0;a.api.getFriends(n),a.api.getAcquaintances(n)}),a.api.getAccountControlRequests(function(){a.api.getDomainInvites(r)}),a.api.getJoinedAccountControlGroup(r)})},prepareNecessaryDataFromCache:function(){var e=nt.sortAndReturn(this.dataStore.getDomains(),function(e,t){var n=t.id,i=e.id,r=n.high-i.high|0;return r=0!=r?r:Sa.ucompare(n.low,i.low),n.high<0?i.high<0?r:-1:0<=i.high?r:1});this.api.sendDomainNotifications(e);for(var t=0;t<e.length;){var n=e[t];++t;var i=this.dataStore.getAnnouncementStatus(n.id);null==i&&(i=this.dataFactory.newAnnouncementStatusForDomain(n.id)),this.api.sendAnnouncementStatusNotification(i);for(var r=0,a=this.dataStore.getFriends(n.id);r<a.length;){var o=a[r];++r,this.sendNotification("notify_add_friend",o)}for(var s=0,l=this.dataStore.getAcquaintances(n.id);s<l.length;){var u=l[s];++s,this.sendNotification("notify_add_acquaintance",u)}}this.api.sendTalkNotifications(this.dataStore.getTalks()),this.api.sendTalkStatusNotifications(this.dataStore.getTalkStatuses());for(var c=0,_=this.dataStore.getDomainInvites();c<_.length;){var h=_[c];++c,this.sendNotification("notify_add_domain_invite",h)}for(var d=0,f=this.dataStore.getAccountControlRequests();d<f.length;){var m=f[d];++d,this.sendNotification("notify_add_account_control_request",m)}var p=this.dataStore.getAccountControlGroup();null!=p&&this.sendNotification("notify_join_account_control_group",p),this.onNecessaryDataPrepared()},onNecessaryDataPrepared:function(){var e=this.settings.getConfiguration().botExpiredVersion;if(Gi._d("["+$e.dateStr(new Date)+"] ","bot_expired_version",e,"","",""),null!=e){var t=require("../../package.json").version;if(Gi._d("["+$e.dateStr(new Date)+"] ","current",t,"","",""),null!=t){var n=e.split("."),i=t.split(".");3==n.length&&3==i.length&&0<=1e4*(parseFloat(n[0])-parseFloat(i[0]))+100*(parseFloat(n[1])-parseFloat(i[1]))+(parseFloat(n[2])-parseFloat(i[2]))&&process.stderr.write("-----------------------------------------\nCurrent version is expired! (current: "+t+")\nRun 'npm install direct-js' to update\n-----------------------------------------\n")}}this.sendNotification("data_recovered"),this.api.startNotification(),this.api.startUpdateLastUsedAtIfNeed()},__class__:Hr});var jr=function(){this.deviceId=null,this.selectedDomainIdOnTalkSelectionChanged=null,this.selectedDomainId=null,this.remember=!0,ir.call(this,"settings")};(n["albero.proxy.SettingsProxy"]=jr).__name__=["albero","proxy","SettingsProxy"],jr.__interfaces__=[Mn],jr.__super__=ir,jr.prototype=i(ir.prototype,{onRegister:function(){this.loadBrowserSettings()},getValidHost:function(){return"https://"+Eo.host},setAccessTokenRemember:function(e){this.remember=e},setAccessToken:function(e){this.remember&&(this.accessToken=e,this.sendNotification("access_token_changed",e))},getAccessToken:function(){return null==this.accessToken&&(this.accessToken=Eo.accessToken),this.accessToken},clearAccessToken:function(){this.accessToken=null},getOs:function(){return"bot"},getIDFV:function(){var e=D.getItem("idfv");return null!=e&&""!=e||(e=k.randomString(),D.setItem("idfv",e)),e},setConfiguration:function(e){this.configuration=e,this.sendNotification("configuration_changed",e)},getConfiguration:function(){return this.configuration},setDeviceId:function(e){this.deviceId=e},getDeviceId:function(){return this.deviceId},setSelectedDomainId:function(e){var t=this.selectedDomainId;null!=t&&null!=e&&t.high==e.high&&t.low==e.low||(null!=e?(D.setItem("selected_domain_id_h",K.string(e.high)),D.setItem("selected_domain_id_l",K.string(e.low))):(D.removeItem("selected_domain_id_h"),D.removeItem("selected_domain_id_l")),this.selectedDomainId=e,this.sendNotification("domain_selection_changed",e))},getLastSelectedDomainId:function(){var e,t=D.getItemAsInt("selected_domain_id_h"),n=D.getItemAsInt("selected_domain_id_l");null!=t&&null!=n?e=new Kn(t,n):e=null;return e},getSelectedDomainId:function(){return this.selectedDomainId},getSelectedDomainIdOnTalkSelectionChanged:function(){return this.selectedDomainIdOnTalkSelectionChanged},clearDomainSelection:function(){this.selectedDomainId=null,D.removeItem("selected_domain_id_h"),D.removeItem("selected_domain_id_l")},clearSelectedTalk:function(e){null==e&&(e=jt.SingleTalkPane);var t=this.selectedDomainId;this.assureTalkSelectionMap("_"+t.high+"_"+t.low).remove(e),this.selectedDomainIdOnTalkSelectionChanged=this.selectedDomainId,this.sendNotification("talk_selection_changed",new On(e,Fn.NotSelected))},selectTalk:function(e,t,n,i){var r="_"+t.high+"_"+t.low;if(null==r)return!1;var a=this.assureTalkSelectionMap(r),o=Fn.TalkSelected(n,i);a.set(e,o);var s=this.selectedDomainId;return null!=t&&null!=s&&t.high==s.high&&t.low==s.low&&(this.selectedDomainIdOnTalkSelectionChanged=this.selectedDomainId,this.sendNotification("talk_selection_changed",new On(e,o)),!0)},selectAnnouncement:function(e){if(null==this.selectedDomainId)return!1;var t=this.selectedDomainId,n="_"+t.high+"_"+t.low;return this.assureTalkSelectionMap(n).set(e,Fn.AnnouncementsSelected),this.selectedDomainIdOnTalkSelectionChanged=this.selectedDomainId,this.sendNotification("talk_selection_changed",new On(e,Fn.AnnouncementsSelected)),!0},hasSelectedTalkOrAnnouncements:function(e){null==e&&(e=jt.SingleTalkPane);var t=this.getTalkSelectionMap(this.selectedDomainId);return null!=t&&t.get(e)!=Fn.NotSelected},hasSelectedTalk:function(e){null==e&&(e=jt.SingleTalkPane);var t=this.getTalkSelectionMap(this.selectedDomainId);if(null==t)return!1;var n=t.get(e);return null!=n&&0!=n[1]},getTalkSelectionMap:function(e){if(null==this.paneTalkSelections)return null;if(null==e)return null;var t="_"+e.high+"_"+e.low,n=this.paneTalkSelections;return null!=No[t]?n.getReserved(t):n.h[t]},assureTalkSelectionMap:function(e){null==this.paneTalkSelections&&(this.paneTalkSelections=new xa);var t=this.paneTalkSelections,n=null!=No[e]?t.getReserved(e):t.h[e];if(null==n){n=new Ca;var i=this.paneTalkSelections;null!=No[e]?i.setReserved(e,n):i.h[e]=n}return n},getSelectedTalkId:function(){var e=this.getTalkSelection(this.selectedDomainId,jt.SingleTalkPane);if(1!=e[1])return null;e[3];return e[2]},isSelectedTalkOrAnnouncements:function(e,t){return xn.isSelected(this.getTalkSelection(this.selectedDomainId,e),t)},getTalkSelection:function(e,t){if(null==this.paneTalkSelections)return Fn.NotSelected;var n=this.getTalkSelectionMap(e);if(null==n)return Fn.NotSelected;var i=n.get(t);return null==i?Fn.NotSelected:i},isSendByEnter:function(){return null==this.sendByEnter&&(this.sendByEnter=!0),this.sendByEnter},setSendByEnter:function(e){e!=this.sendByEnter&&(this.sendByEnter=e,this.sendNotification("send_by_enter_changed",e))},setSelectedStampsetType:function(e){D.setItem("selected_stamp_tab_id",e.toTabId())},getSelectedStampsetType:function(){return En.fromTabId(D.getItem("selected_stamp_tab_id"))},clearSelectedStampsetType:function(){D.removeItem("selected_stamp_tab_id")},setInputTextForTalkId:function(e,t){null==e||0==e.length?this.clearInputTextForTalkId(t):(this.loadInputTextForAll(),this.inputTexts["_"+t.high+"_"+t.low]=e)},getInputTextForTalkId:function(e){this.loadInputTextForAll();var t=this.inputTexts["_"+e.high+"_"+e.low];return null!=t?t:""},clearInputTextForTalkId:function(e){this.loadInputTextForAll(),delete this.inputTexts["_"+e.high+"_"+e.low]},loadInputTextForAll:function(){null==this.inputTexts&&(this.inputTexts=D.getItemAsJson("input_text"),null==this.inputTexts&&(this.inputTexts={}))},saveInputTextForAll:function(){if(null!=this.inputTexts){var e=JSON.stringify(this.inputTexts);D.setItem("input_text",e)}},clearInputTextForAll:function(){D.removeItem("input_text"),this.inputTexts=null},setCopyProfileToAllDomains:function(e){e?D.setItem("copy_profile_to_all_domains","true"):D.removeItem("copy_profile_to_all_domains")},isCopyProfileToAllDomains:function(){return null!=D.getItem("copy_profile_to_all_domains")},setSearchHistoriesForSelectedDomain:function(e){if(null!=this.selectedDomainId){if(this.loadSearchHistoryForAll(),null==e){var t=this.selectedDomainId;delete this.searchHistories["_"+t.high+"_"+t.low]}else{var n=this.selectedDomainId;this.searchHistories["_"+n.high+"_"+n.low]=e}this.saveSearchHistoryForAll()}},getSearchHistoriesForSelectedDomain:function(){if(null==this.selectedDomainId)return null;this.loadSearchHistoryForAll();var e=this.selectedDomainId;return this.searchHistories["_"+e.high+"_"+e.low]},loadSearchHistoryForAll:function(){null==this.searchHistories&&(this.searchHistories=D.getItemAsJson("search_histories"),null==this.searchHistories&&(this.searchHistories={}))},saveSearchHistoryForAll:function(){if(null!=this.searchHistories){var e=JSON.stringify(this.searchHistories);D.setItem("search_histories",e)}},setSelectedDepartmentId:function(e,t){if(null!=e){if(this.loadSelectedDepartmentIdsForAll(),null==t)this.selectedDepartmentIds.remove("_"+e.high+"_"+e.low);else{var n="_"+e.high+"_"+e.low,i=this.selectedDepartmentIds;null!=No[n]?i.setReserved(n,t):i.h[n]=t}this.saveSelectedDepartmentIdsForAll()}},getSelectedDepartmentId:function(e){if(null==e)return null;this.loadSelectedDepartmentIdsForAll();var t="_"+e.high+"_"+e.low,n=this.selectedDepartmentIds;return null!=No[t]?n.getReserved(t):n.h[t]},loadSelectedDepartmentIdsForAll:function(){null==this.selectedDepartmentIds&&(this.selectedDepartmentIds=D.getItemWithUnserialize("selected_department_ids"),null==this.selectedDepartmentIds&&(this.selectedDepartmentIds=new xa))},saveSelectedDepartmentIdsForAll:function(){null!=this.selectedDepartmentIds&&D.setItemWithSerialize("selected_department_ids",this.selectedDepartmentIds)},setRightPanelOpened:function(e){e?D.removeItem("right_panel_opened"):D.setItem("right_panel_opened","false")},isRightPanelOpened:function(){return null==D.getItem("right_panel_opened")},setMultiViewMode:function(e){e?D.setItem("multi_view_mode","true"):D.removeItem("multi_view_mode")},isMultiViewMode:function(){return null!=D.getItem("multi_view_mode")},setPasswordWarningSkipUntil:function(e){null==e?D.removeItem("password_warning_skip_until"):D.setItem("password_warning_skip_until","_"+e.high+"_"+e.low)},getPasswordWarningSkipUntil:function(){var e=D.getItem("password_warning_skip_until");return null==e?null:tt.makeFromIdStr(e)},setLastUsedExpiredAt:function(e){null==e?D.removeItem("last_used_expired_at"):D.setItem("last_used_expired_at","_"+e.high+"_"+e.low)},getLastUsedExpiredAt:function(){var e=D.getItem("last_used_expired_at");return null==e?null:tt.makeFromIdStr(e)},setOnPremise:function(e){this.onPremises=e},isOnPremises:function(){return this.onPremises},getBrowserSettings:function(){return this.browserSettings},applyNotificationSettings:function(e){return e.copyNotificationSettingsTo(this.browserSettings),this.saveBrowserSettings()},applyKeywordWatchingSettings:function(e){return e.copyKeywordSettingsTo(this.browserSettings),this.saveBrowserSettings()},applyTalkSettings:function(e){return e.copyTalkSettingsTo(this.browserSettings),this.saveBrowserSettings()},applyUserDataSettings:function(e){return e.copyUserDataContainerTo(this.browserSettings),this.saveBrowserSettings()},applyLanguageSettings:function(e){return e.copyLanguageSettingsTo(this.browserSettings),this.saveBrowserSettings()},applyConferenceSettings:function(e){return e.copyConferenceSettingsTo(this.browserSettings),this.saveBrowserSettings()},loadBrowserSettings:function(){this.browserSettings=xe.fromJson(D.getItemAsJson(xe.NAME))},saveBrowserSettings:function(){var e=D.getItemAsJson(xe.NAME);return null==e&&(e={}),this.browserSettings.copyTo(e),D.setItem(xe.NAME,JSON.stringify(e))},__class__:jr});var Yr=function(){ir.call(this,"solutionsStore")};(n["albero.proxy.SolutionsStoreProxy"]=Yr).__name__=["albero","proxy","SolutionsStoreProxy"],Yr.__super__=ir,Yr.prototype=i(ir.prototype,{getSolutions:function(e){var t=this;return null==this.solutionsMap?[]:this.getSolutionIds(e).map(function(e){return t.solutionsMap.h[e]}).filter(function(e){return null!=e})},getSolution:function(e){return null==this.solutionsMap?null:this.solutionsMap.h[e]},getSolutionIds:function(e){return null==e?[]:null==e.contract?[]:null==e.contract.solutionIds?[]:e.contract.solutionIds},getSolutionIdsLoaded:function(e){var t=this;return this.getSolutionIds(e).filter(function(e){return null!=t.solutionsMap&&t.solutionsMap.h.hasOwnProperty(e)})},getSolutionIdsNotLoaded:function(e){var t=this;return this.getSolutionIds(e).filter(function(e){return null==t.solutionsMap||!t.solutionsMap.h.hasOwnProperty(e)})},setSolution:function(e){null==this.solutionsMap&&(this.solutionsMap=new Oa),this.solutionsMap.h[e.solutionId]=e},isDxflowEnabled:function(e){return!this.settings.isOnPremises()&&et.exists(this.getSolutionIds(e),function(e){return 4==dn.getSolutionType(e)[1]})},__class__:Yr});var Gr=function(){ir.call(this,"stampsStore"),this.stampsetStore=new xa,this.stampStore=new xa};(n["albero.proxy.StampsStoreProxy"]=Gr).__name__=["albero","proxy","StampsStoreProxy"],Gr.__super__=ir,Gr.prototype=i(ir.prototype,{addStampsets:function(e){for(var t=0;t<e.length;){var n=e[t];++t,this.addStampset(n)}},addStampset:function(e){var t=this.stampsetStore,n=e.toTabId(),i=t;null!=No[n]?i.setReserved(n,e):i.h[n]=e;for(var r=0,a=e.getStamps();r<a.length;){var o=a[r];++r;var s=this.stampStore,l=o.getKey(),u=s;null!=No[l]?u.setReserved(l,o):u.h[l]=o}},updateStampsetInfo:function(e){var t=e.toTabId(),n=this.stampsetStore,i=null!=No[t]?n.getReserved(t):n.h[t];if(null!=i&&i.isOlderThan(e)){this.stampsetStore.remove(t);for(var r=0,a=i.getStamps();r<a.length;){var o=a[r];++r,this.stampStore.remove(o.getKey())}}},removeStampsetInfo:function(e){var t=wa.toString(e),n=this.stampsetStore,i=null!=No[t]?n.getReserved(t):n.h[t];if(null!=i){this.stampsetStore.remove(t);for(var r=0,a=i.getStamps();r<a.length;){var o=a[r];++r,this.stampStore.remove(o.getKey())}}},addStampsetInfos:function(e){var a=this;et.iter(e,function(e){var t=a.stampsetStore,n=e.toTabId(),i=t;if(null!=No[n]?!i.existsReserved(n):!i.h.hasOwnProperty(n)){var r=Sn.fromStampsetInfo(e);a.addStampset(r)}})},getStampsetByStampsetId:function(e){return this.getStampsetByTabId("_"+e.high+"_"+e.low)},getStampsetsByTabIds:function(e){return e.map(go(this,this.getStampsetByTabId)).filter(function(e){return null!=e})},getStampsetByTabId:function(e){var t=this.stampsetStore;return null!=No[e]?t.getReserved(e):t.h[e]},getStampByStampKey:function(e){var t=this.stampStore;return null!=No[e]?t.getReserved(e):t.h[e]},getOriginalStamp:function(e){var t=this.getStampByStampKey(yn.createKey(e));return null==t?null:Va.__cast(t,yn)},applyHistories:function(r,e){var t=e.map(function(e){var t=vn.fromJson(e);if(null!=t)return t;var n=yn.fromJson(e);if(null!=n){var i=Va.__cast(n,yn);if(null!=r&&r.stampsetSetting.containSendableStampset(i.stampsetId))return n}return Gi._d("["+$e.dateStr(new Date)+"] ","A history stamp is disabled.",e,r,"",""),null}).filter(function(e){return null!=e}),n=Sn.historyStampset();n.setStamps(t),this.addStampset(n)},__class__:Gr});var zr=function(){ir.call(this,"talksService")};(n["albero.proxy.TalksServiceProxy"]=zr).__name__=["albero","proxy","TalksServiceProxy"],zr.__super__=ir,zr.prototype=i(ir.prototype,{getDomainTalksOrderedByTimestamp:function(e){return nt.sortAndReturn(this.getDomainTalks(e).map(go(this,this.createTalkPack)),Cn.compareTalkOrderingTimestamp).map(go(this,this.getTalkFromTalkPack))},getDomainTalksCount:function(e){return this.getDomainTalks(e).length},hasConference:function(e){return null!=e&&this.conferenceStore.hasConference(e.id)},isFavoriteTalk:function(e){var t=this.dataStore.getTalkStatus(e.id);return null!=t&&null!=t.orderInFavorites},getTalkFromTalkPack:function(e){return e.talk},getTalkIdFromTalk:function(e){return e.id},getDomainTalks:function(n){return null==n?[]:this.dataStore.getTalks().filter(function(e){var t=e.domainId;return null!=t&&null!=n&&t.high==n.high&&t.low==n.low})},createTalkPack:function(e){return new Cn(e,this.dataStore.getTalkStatus(e.id))},__class__:zr});var Kr=function(){ir.call(this,"ThumbnailExpansion")};(n["albero.proxy.ThumbnailExpansionProxy"]=Kr).__name__=["albero","proxy","ThumbnailExpansionProxy"],Kr.__super__=ir,Kr.prototype=i(ir.prototype,{onRegister:function(){var e=this;Ea.delay(function(){e.workingBrowserSettings=e.settings.getBrowserSettings().createCopy()},0)},updateThumbnailExpansionEnabled:function(e){if(null!=this.workingBrowserSettings){var t=this.dataStore.me;if(null!=t){var n=t.id;this.workingBrowserSettings.setThumbnailExpansionEnabled("_"+n.high+"_"+n.low,e),this.settings.applyUserDataSettings(this.workingBrowserSettings)}}},isThumbnailExpansionEnabled:function(){if(null==this.workingBrowserSettings)return!1;var e=this.dataStore.me;if(null==e)return!1;var t=e.id;return this.workingBrowserSettings.isThumbnailExpansionEnabled("_"+t.high+"_"+t.low)},__class__:Kr});var Wr=function(){ir.call(this,"userPresences")};(n["albero.proxy.UserPresencesProxy"]=Wr).__name__=["albero","proxy","UserPresencesProxy"],Wr.__super__=ir,Wr.prototype=i(ir.prototype,{getUserPresenceState:function(e,t){var n=it.map(this.getUserPresence(e),function(e){return e.toState(t)});switch(n[1]){case 0:return n[2];case 1:return Vn.GT_60}},getUserPresence:function(e){return it.option(this.dataStore.getUserPresence(e))},getLastUsedAtString:function(e){var t=it.map(it.flatMap(this.getUserPresence(e),function(e){return e.lastUsedAtOpt}),function(e){return I.datetimeString(e)});switch(t[1]){case 0:return t[2];case 1:return" - "}},__class__:Wr});var Vr=n["albero_cli.UpdateNoteAttachment"]={__ename__:["albero_cli","UpdateNoteAttachment"],__constructs__:["LocalFileAttachment","RemoteFileAttachment"]};Vr.LocalFileAttachment=function(e){var t=["LocalFileAttachment",0,e];return t.__enum__=Vr,t.toString=s,t},Vr.RemoteFileAttachment=function(e){var t=["RemoteFileAttachment",1,e];return t.__enum__=Vr,t.toString=s,t},Vr.__empty_constructs__=[];function qr(){}(n["albero_cli.INotes"]=qr).__name__=["albero_cli","INotes"],qr.prototype={__class__:qr};var Qr=function(e,t){this.delegate=e;var n=null!=t?t:{max:24,interval:12e4};this.ratelimit=new _(n.max,n.interval)};(n["albero_cli.LimitedNotes"]=Qr).__name__=["albero_cli","LimitedNotes"],Qr.__interfaces__=[qr],Qr.prototype={limit:function(e){return this.ratelimit.apply(e)},get:function(e){var t=this;return this.limit(function(){return t.delegate.get(e)})},update:function(e,t){var n=this;return this.limit(function(){return n.delegate.update(e,t)})},delete:function(e){var t=this;return this.limit(function(){return t.delegate.delete(e)})},__class__:Qr};var Jr=function(e,t,n,i){this.utils=e,this.api=t,this.fileInfoStore=n,this.fileService=i};(n["albero_cli.Notes"]=Jr).__name__=["albero_cli","Notes"],Jr.__interfaces__=[qr],Jr.all=function(e,t){return et.foreach(e,t)},Jr.isValidAsAttachment=function(e){return Jr.isStringNullOrEmpty(e.url)?!Jr.isStringNullOrEmpty(e.path):!Jr.isStringNullOrEmpty(e.id)&&!Jr.isStringNullOrEmpty(e.name)&&null!=e.content_size&&!Jr.isStringNullOrEmpty(e.content_type)},Jr.isStringNullOrEmpty=function(e){return null==e||0==e.length},Jr.prototype={toNoteId:function(e){return new Ti(this.utils.parseInt64(e.id))},handleResponse:function(r,a,o){return function(e,t){if(null!=e){var n=fa.of(e);a(n)}else{var i=o(t);r(i)}}},get:function(e){var r=this,a=this.toNoteId(e);return new Promise(function(e,t){var n=r.api,i=r.handleResponse(e,t,ga.of);n.getNote(a,i)})},update:function(e,t){var a=this,n=e.talkId_i64,o=new Ti(e.id_i64),i=this.validateUpdateNoteInput(t);switch(i[1]){case 0:var r=i[2];return Promise.reject(r);case 1:var s=i[2],l=this.mergeNoteObject(e,s),u=this.createNoteLocalEdit(n,o,l,null);return new Promise(function(e,t){var n=a.api,i=l.currentRevision,r=a.handleResponse(e,t,va.of);n.updateNoteV2(o,i,u,!0,r)})}},validateUpdateNoteInput:function(e){if(null!=e.note_title){if("string"!=typeof e.note_title)return ka.Left(fa.createInvalidParameterError("note_title is not String"));if(0==e.note_title.length)return ka.Left(fa.createInvalidParameterError("note_title is empty"))}if(null!=e.note_content){if("string"!=typeof e.note_content)return ka.Left(fa.createInvalidParameterError("note_content is not String"));if(0==e.note_content.length)return ka.Left(fa.createInvalidParameterError("note_content is empty"))}var t=null;if(null!=e.note_attachments){if(!(e.note_attachments instanceof Array&&null==e.note_attachments.__enum__&&Jr.all(e.note_attachments,Jr.isValidAsAttachment))){var n="note_attachments is invalid: "+JSON.stringify(e.note_attachments);return ka.Left(fa.createInvalidParameterError(n))}t=this.toUpdateNoteAttachmentArray(e.note_attachments)}return ka.Right({title:e.note_title,content:e.note_content,attachments:t})},mergeNoteObject:function(e,t){var n={title:e.noteRevision.title,content:e.noteRevision.contentText,attachments:this.toUpdateNoteAttachmentArray(e.get_attachments()),currentRevision:e.noteRevision.revision};return null!=t.title&&(n.title=t.title),null!=t.content&&(n.content=t.content),null!=t.attachments&&(n.attachments=t.attachments),n},toUpdateNoteAttachmentArray:function(e){var n=go(mo=this.utils,mo.parseInt64);return et.array(et.map(e,function(e){if(Jr.isStringNullOrEmpty(e.url))return Vr.LocalFileAttachment(e);var t=null==e?null:JSON.parse(JSON.stringify(e));return t.id=n(e.id),Vr.RemoteFileAttachment(t)}))},createNoteLocalEdit:function(e,t,n,i){var r=this.createNoteAttachmentFileInfoList(n.attachments);return new Ii(e,t,n.title,n.content,r,i)},createNoteAttachmentFileInfoList:function(e){for(var t=[],n=0;n<e.length;){var i=e[n];++n;var r=null;switch(i[1]){case 0:var a=i[2],o=this.fileService.createDummyFile(a.path,a.name,a.type);r=this.fileInfoStore.createStagedFileInfoFromDummyFile(null,o,null);break;case 1:var s=i[2];r=this.fileInfoStore.createUploadedFileInfo(s)}t.push(r)}return t},delete:function(e){var r=this,a=this.toNoteId(e);return new Promise(function(e,t){var n=r.api,i=r.handleResponse(e,t,pa.of);n.deleteNote(a,i)})},__class__:Jr};function Xr(e,t){this.updatedAt=e.updatedAt,this.domainInfo=e.domainInfo,this.contract=e.contract,this.profileDefinition=e.profileDefinition,this.setting=e.setting,this.role=e.role,this.closed=e.closed,this.id=e.id,null!=t&&(this.talks=t)}(n["albero_cli.entity.Domain"]=Xr).__name__=["albero_cli","entity","Domain"],Xr.create=function(e,t){return new Xr(e,t)},Xr.prototype={toCompatibleData:function(){var e=JSON.parse(JSON.stringify(this));e.id_i64=this.id;var t=this.id;return e.id="_"+t.high+"_"+t.low,e.talks=this.talks,e},__class__:Xr};function Zr(e){this.status=e.status,this.displayName=e.displayName,this.canonicalDisplayName=e.canonicalDisplayName,this.phoneticDisplayName=e.phoneticDisplayName,this.canonicalPhoneticDisplayName=e.canonicalPhoneticDisplayName,this.profileImageUrl=e.profileImageUrl,this.updatedAt=e.updatedAt,this.id=e.id}(n["albero_cli.entity.User"]=Zr).__name__=["albero_cli","entity","User"],Zr.of=function(e){return new Zr(e)},Zr.prototype={toCompatibleData:function(){var e=JSON.parse(JSON.stringify(this));e.id_i64=this.id;var t=this.id;return e.id="_"+t.high+"_"+t.low,e.name=this.displayName,e.profile_url=this.profileImageUrl,e},__class__:Zr};function $r(e){Zr.call(this,e),this.domainId=e.domainId,this.profileContact=this.convertProfileContact(e.profileContact),this.departments=e.departments,this.email=e.email,this.subEmail=e.subEmail,this.groupAlias=e.groupAlias,this.signinId=e.signinId}(n["albero_cli.entity.DomainUser"]=$r).__name__=["albero_cli","entity","DomainUser"],$r.of=function(e){return new $r(e)},$r.__super__=Zr,$r.prototype=i(Zr.prototype,{convertProfileContact:function(e){return null==e?null:e.map(function(e){return ta.of(e)})},__class__:$r});function ea(e){Zr.call(this,e),this.email=e.email,this.signinId=e.signinId,this.profiles=e.profiles,this.departments=e.departments}(n["albero_cli.entity.Me"]=ea).__name__=["albero_cli","entity","Me"],ea.of=function(e){return new ea(e)},ea.__super__=Zr,ea.prototype=i(Zr.prototype,{__class__:ea});var ta=function(e){this.profileItemId=e.profileItemId,this.value=e.value,this.canonicalValue=e.canonicalValue};(n["albero_cli.entity.ProfileItemValue"]=ta).__name__=["albero_cli","entity","ProfileItemValue"],ta.of=function(e){return new ta(e)},ta.prototype={__class__:ta};function na(e){var t=e.id;this.id="_"+t.high+"_"+t.low,this.id_i64=e.id,this.name=e.name,this.content_type=e.contentType,this.content_size=e.contentSize,this.url=e.url}(n["albero_cli.entity.RemoteFileInfo"]=na).__name__=["albero_cli","entity","RemoteFileInfo"],na.of=function(e){return new na(e)},na.prototype={__class__:na};function ia(e,t,n){this.name=e.name,this.iconUrl=e.iconUrl,this.updatedAt=e.updatedAt,this.leftUsers=e.leftUsers,this.groupTalkSettings=e.groupTalkSettings,this.id=e.id,this.type=e.type,this.userIds=e.userIds,this.users=t,this.domain=n,this.domainId=e.domainId}(n["albero_cli.entity.Talk"]=ia).__name__=["albero_cli","entity","Talk"],ia.talkType=function(e){switch(e[1]){case 1:return 1;case 2:return 2;default:return 0}},ia.create=function(e,t,n){return new ia(e,t,n)},ia.prototype={toCompatibleData:function(){var e=JSON.parse(JSON.stringify(this));e.id_i64=this.id;var t=this.id;e.id="_"+t.high+"_"+t.low,e.topic=this.name,e.type=ia.talkType(this.type),e.userIds=this.userIds,e.users=this.users,e.domain=this.domain,e.domainId_i64=this.domainId;var n=this.domainId;return e.domainId="_"+n.high+"_"+n.low,e},__class__:ia};function ra(e){this.id=e.noteId.toString(),this.id_i64=e.noteId.value;var t=e.talkId;this.talkId="_"+t.high+"_"+t.low,this.talkId_i64=e.talkId,this.createdBy=e.createdBy,this.createdAt=e.createdAt,this.noteRevision=aa.of(e.noteRevision),Object.defineProperty(this,"attachments",{get:this.get_attachments})}(n["albero_cli.entity.note.Note"]=ra).__name__=["albero_cli","entity","note","Note"],ra.of=function(e){return new ra(e)},ra.prototype={get_attachments:function(){return this.noteRevision.contentFiles},__class__:ra};var aa=function(e){this.revision=e.revision,this.title=e.title,this.contentType=wi.getValue(e.contentType),this.contentText=e.contentText,this.contentFiles=this.convertFiles(e.contentFiles),this.createdBy=e.createdBy,this.createdAt=e.createdAt};(n["albero_cli.entity.note.NoteRevision"]=aa).__name__=["albero_cli","entity","note","NoteRevision"],aa.of=function(e){return new aa(e)},aa.prototype={convertFiles:function(e){return null==e||e.length<=0?[]:e.map(function(e){return na.of(e)})},__class__:aa};function oa(){}(n["puremvc.interfaces.IMediator"]=oa).__name__=["puremvc","interfaces","IMediator"],oa.prototype={__class__:oa};var sa=function(e,t){x.call(this),this.mediatorName=null!=e?e:sa.NAME,null!=t&&(this.viewComponent=t)};(n["puremvc.patterns.mediator.Mediator"]=sa).__name__=["puremvc","patterns","mediator","Mediator"],sa.__interfaces__=[oa],sa.__super__=x,sa.prototype=i(x.prototype,{getMediatorName:function(){return this.mediatorName},setViewComponent:function(e){this.viewComponent=e},getViewComponent:function(){return this.viewComponent},listNotificationInterests:function(){return[]},handleNotification:function(e){},onRegister:function(){},onRemove:function(){},__class__:sa});var la=function(){sa.call(this,"commandline",null)};(n["albero_cli.mediator.CommandLineMediator"]=la).__name__=["albero_cli","mediator","CommandLineMediator"],la.__super__=sa,la.prototype=i(sa.prototype,{onRegister:function(){this.getViewComponent();this.eventEmitter=r.getInstance(),this.dataRecovered=!1,this.startDataSaver()},listNotificationInterests:function(){return["app_state_changed","access_token_changed","current_user_changed","configuration_changed","domain_selection_changed","talk_selection_changed","talk_list_scroll_to_talk_top_needed","user_selection_needed","user_selection_changed","friend_selection_needed","common_stamp_set_loaded","stamp_selection_started","stamp_selection_ended","stamp_selection_changed","action_selection_changed","current_page_changed","current_page_reassgined","fileinfo_selection_changed","message_fileinfo_selection_changed","staged_fileinfo_selection_changed","staged_fileinfos_added","staged_fileinfos_moved","error_occurred","brand_badge_changed","send_form_top_changed","solutions_loaded","right_pane_opened","right_pane_closed","password_expiration_overed","password_expiration_warned","photo_editor_saved","mc_authenticated_user_received","keyword_watching_updated","keyword_detaction_updated","send_by_enter_changed","department_selection_changed_for_members_page","presences_updated","noteinfo_selection_changed","start_note_editing","start_notification_failed","data_recovering","data_recovered","notify_update_user","notify_add_friend","notify_add_acquaintance","notify_add_acquaintances","notify_delete_friend","notify_delete_acquaintance","notify_delete_acquaintances","notify_update_domain_users","get_domain_users_responsed","get_users_responsed","get_profile_responsed","get_profile_errored","update_user_responsed","update_user_errored","update_profile_responsed","update_profile_errored","notify_update_department_tree","notify_update_department_users","get_department_tree_responsed","get_department_tree_canceled","get_department_users_responsed","get_department_users_canceled","get_department_user_count_responsed","get_me_responsed","department_user_count_cleared","department_user_ids_prepared","notify_add_domain_invite","notify_accept_domain_invite","notify_delete_domain_invite","notify_join_domain","notify_update_domain","notify_leave_domain","notify_add_domain_members","notify_create_pair_talk","notify_create_group_talk","notify_update_group_talk","notify_update_group_talk_ERRORED","notify_add_talkers","notify_add_talkers_including_me","notify_delete_talker","notify_delete_talk","notify_create_message","notify_delete_message","notify_update_read_statuses","notify_update_talk_status","notify_update_local_talk_status","notify_get_messages","notify_get_message_status","notify_add_favorite_talk","notify_delete_favorite_talk","notify_disable_push_notification","notify_enable_push_notification","create_message_start","create_message_complete","create_message_fail","notify_create_announcement","notify_delete_announcement","notify_update_announcement_status","notify_get_announcements","create_announcement_start","create_announcement_complete","create_announcement_fail","notify_update_question","get_questions_responsed","notify_create_attachment","notify_delete_attachment","get_note_statuses_loaded","get_note_loaded","get_note_failed_by_note_not_found","create_note_completed","create_note_failed","update_note_local_edit","clear_note_local_edit","update_note_setting_completed","update_note_setting_failed_by_not_found","update_note_setting_failed_by_conflict","update_note_setting_failed_by_editing","update_note_completed","delete_note_completed","notify_create_note","notify_update_note_partially","notify_delete_note","notify_update_note_for_setting","notify_update_note_for_revision","create_note_button_clicked","notify_lock_note","notify_unlock_note","get_file_responsed","notify_search_messages","notify_search_attachments","notify_search_messages_fail","notify_search_attachments_fail","notify_search_prepare","notify_search_clear","notify_filter_box_text_changed","notify_search_box_popup","notify_add_account_control_request","notify_delete_account_control_request","notify_join_account_control_group","notify_update_account_control_group_partially","notify_leave_account_control_group","prepare_conference_from_message","join_conference_responsed","join_conference_canceled","notify_open_conference","notify_close_conference","notify_conference_participant_join","notify_conference_participant_limit","notify_conference_participant_reject","notify_all_talk_members_rejected_conference"]},handleNotification:function(e){var t=this,n=e.getName();switch(n){case"current_page_changed":var i=e.getBody();ee.enumEq(i,V.error)&&(this.dataRecovered=!1),this.eventEmitter.emit(e.getName(),e.getBody());break;case"data_recovered":if(this.dataRecovered)return;this.dataRecovered=!0,this.eventEmitter.emit(e.getName());break;case"data_recovering":this.dataRecovered=!1,this.eventEmitter.emit(e.getName());break;case"error_occurred":this.eventEmitter.emit(e.getName(),new Error("AdapterError"),e.getBody());break;case"start_notification_failed":Gi._e("["+$e.dateStr(new Date)+"] ","start_notification failed.","","","",""),process.exit(1);break;default:this.eventEmitter.emit(e.getName(),e.getBody())}this.getViewComponent();switch(e.getName()){case"access_token_changed":this.dataStore.clear(!0),console.log(e.getBody()),process.exit(0);break;case"create_announcement_complete":case"create_message_complete":var r,a=e.getBody(),o=a[0],s=(a[1],this.dataStore),l=o.userId;if(null!=s.me){var u=s.me.id;r=null!=u&&null!=l&&u.high==l.high&&u.low==l.low}else r=!1;if(r)return this.messageEvent.messageCreated(o,e.getType()),void this.sendQueue.sendNext(o);break;case"create_message_fail":var c,_=e.getBody()[0],h=e.getBody()[1],d=this.dataStore,f=h.userId;if(null!=d.me){var m=d.me.id;c=null!=m&&null!=f&&m.high==f.high&&m.low==f.low}else c=!1;if(c)return this.messageEvent.messageCreated(null,e.getType()),void(null!=_&&429==_.code?this.sendQueue.retryAfter(1e3*(0|_.detail.retry_after)):null!=_&&503==_.code?this.sendQueue.retryAfter(1e3*(0|_.detail.retry_after)):this.sendQueue.sendNext(h));break;case"create_note_completed":var p,g=e.getBody(),v=this.dataStore,y=g.note.createdBy;if(null!=v.me){var S=v.me.id;p=null!=S&&null!=y&&S.high==y.high&&S.low==y.low}else p=!1;if(p)return this.messageEvent.noteCreated(g.note,g.emitterKey),void this.sendQueue.sendNextTalkMessage();break;case"create_note_failed":var w,T=e.getBody(),I=this.dataStore,E=T.callerId;if(null!=I.me){var N=I.me.id;w=null!=N&&null!=E&&N.high==E.high&&N.low==E.low}else w=!1;if(w){this.messageEvent.noteCreated(null,T.emitterKey),this.sendQueue.sendNextTalkMessage();var A="failed to create note: "+K.string(T.error);return void Gi._d("["+$e.dateStr(new Date)+"] ",A,"","","","")}break;case"current_user_changed":e.getBody();this.sendQueue.restart();break;case"notify_add_domain_invite":e.getBody();break;case"notify_create_group_talk":case"notify_create_pair_talk":if(!this.dataRecovered)return;var b=e.getBody();Ea.delay(function(){t.emitWithMe(b,"JoinMessage",t.dataStore.me)},500);break;case"notify_create_message":var D,k=e.getBody(),C=this.dataStore,O=k.userId;if(null!=C.me){var M=C.me.id;D=null!=M&&null!=O&&M.high==O.high&&M.low==O.low}else D=!1;if(D)return;if(k.isBotMessage&&!Eo.talkWithBot)return;var R=this.dataStore.getTalkStatus(k.talkId),F=qi.getAcceptableEventTimeDiff();if(null!=R&&!R.isMessageAcceptable(k,F))return;Ea.delay(function(){null!=t.dataStore.getTalk(k.talkId)&&(t.sendNotification("Read",_e.TALK(k.talkId)),t.dispatch(k))},200);break;case"notify_delete_talk":var x=e.getBody();this.messageEvent.deleteTalk(x);break;case"notify_get_message_status":var U=e.getBody();this.messageEvent.messageRead(U.talkId,U.id,U.readUserIds,U.unreadUserIds);break;case"notify_leave_domain":var P=e.getBody();this.messageEvent.leaveDomain(P);break;case"notify_update_group_talk":if(!this.dataRecovered)return;var L=e.getBody(),B=null!=L.name?L.name:"";Ea.delay(function(){t.emitWithMe(L,"TopicChangeMessage",t.dataStore.me,B)},500);break;case"notify_update_local_talk_status":var H=e.getBody();this.messageEvent.messageReadEveryone(H.id,H.maxEveryoneReadMessageId);break;case"notify_update_read_statuses":for(var j=e.getBody(),Y=0,G=j.messageIds;Y<G.length;){var z=G[Y];++Y,this.messageEvent.messageRead(j.talkId,z,j.readUserIds)}}},emitWithUser:function(e,t,n,i){this.emit(e,t,this.hubotObject.userObject(n),i)},emitWithMe:function(e,t,n,i){this.emit(e,t,this.hubotObject.meObject(n),i)},emit:function(r,a,o,s){var l=this;null!=a&&null!=r&&null!=o&&this.api.getAllUserIdentifiers(function(){var e=l.eventEmitter,t=r.id,n="_"+t.high+"_"+t.low,i=l.hubotObject.talkObjects();e.emit(a,{room:n,rooms:i},o,s)})},leave:function(e){var t=this;Ea.delay(function(){null!=t.dataStore.getTalk(e.id)&&t.sendNotification("Talk",Te.DELETE_FOR_HUBOT(e.id))},500)},dispatch:function(a){function e(e,t,n){var i=o.dataStore.getUser(s.domainId,t),r=a.id;o.emitWithUser(s,e,i,{id:"_"+r.high+"_"+r.low,content:n})}var o=this,t=a.content,s=this.dataStore.getTalk(a.talkId);if(a.type==xt.system){var n=t.type;if("add_talkers"==n){var i=t.added_user_ids,r=this.dataStore.me.id;if(tt.contains(i,r))return void e("JoinMessage",r);for(var l=0;l<i.length;){var u=i[l];++l,e("EnterMessage",u)}}else"delete_talker"==n?(e("LeaveMessage",t.deleted_user_id),t.user_ids.length<=1&&this.leave(s)):"hide_pair_talk"==n&&(e("LeaveMessage",t.user_id),this.leave(s))}else{var c=null;if(1==a.type[1])c=t;else{for(var _=a.content,h=null==_?null:JSON.parse(JSON.stringify(_)),d=0,f=G.fields(h);d<f.length;){var m=f[d];++d;var p=G.field(h,m);if(G.isObject(h)&&null!=p.high&&null!=p.low){var g=new Kn(p.high,p.low);h[m]="stamp_index"==m?wa.toString(g):"_"+g.high+"_"+g.low}else"stamp_set"==m&&(h[m]=K.string(p))}a.type!=xt.textMultipleFile||null!=h.text&&0!=h.text.length||null==h.files||1!=h.files.length||(h=h.files[0]),c=JSON.stringify(h)}if(null!=c){if(s.type==bn.PairTalk){var v=null!=Eo.name?Eo.name:"Hubot";W.startsWith(c,v)||(c=v+" "+c)}e("TextMessage",a.userId,c)}}},startDataSaver:function(){var e=this;Ea.delay(function(){e.dataRecovered&&e.dataStore.saveIfNeeded(),e.startDataSaver()},5e3)},__class__:la});var ua=function(){ir.call(this,"hubotObject")};(n["albero_cli.proxy.HubotObjectProxy"]=ua).__name__=["albero_cli","proxy","HubotObjectProxy"],ua.__super__=ir,ua.prototype=i(ir.prototype,{userObject:function(e){return $r.of(e).toCompatibleData()},meObject:function(e){return ea.of(e).toCompatibleData()},userObjectByIdStr:function(e,t){var n,i=t.split("_");2<i.length?n=new Kn(K.parseInt(i[1]),K.parseInt(i[2])):n=null;var r=this.userObjectsByIds(e,[n]);return 0<r.length?r[0]:null},userObjectsByIds:function(e,t,n){for(var i=[],r=0,a=this.dataStore.getUsers(e,t);r<a.length;){var o=a[r];if(++r,null!=o){var s=o.id,l="u_"+s.high+"_"+s.low,u=null!=n?null!=No[l]?n.getReserved(l):n.h[l]:null;if(null==u&&(u=this.userObject(o),null!=n)){var c=u;null!=No[l]?n.setReserved(l,c):n.h[l]=c}null!=u&&i.push(u)}}return i},userObjects:function(e){for(var t={},n=new xa,i=0,r=this.dataStore.getUsers(e);i<r.length;){var a=r[i];++i;var o,s=a.id,l="_"+s.high+"_"+s.low;if(null!=t[l]){var u=(null!=No[l]?n.getReserved(l):n.h[l]).updatedAt,c=a.updatedAt,_=u.high-c.high|0;_=0!=_?_:Sa.ucompare(u.low,c.low),o=(u.high<0?c.high<0?_:-1:0<=c.high?_:1)<=0}else o=!0;o&&(t[l]=this.userObject(a),null!=No[l]?n.setReserved(l,a):n.h[l]=a)}return t},talkObject:function(e,t){var n=this.userObjectsByIds(e.domainId,e.userIds,t),i=this.domainObjectById(e.domainId,t);return ia.create(e,n,i).toCompatibleData()},talkObjects:function(e){for(var t=new xa,n={},i=0,r=this.dataStore.getTalks();i<r.length;){var a,o=r[i];if(++i,null!=e){var s=o.domainId;a=!(null!=e&&null!=s&&e.high==s.high&&e.low==s.low)}else a=!1;if(!a){var l=o.id;n["_"+l.high+"_"+l.low]=this.talkObject(o,t)}}return n},domainObjectById:function(e,t){if(null==e)return null;var n="d_"+e.high+"_"+e.low,i=null!=No[n]?t.getReserved(n):t.h[n];if(null==i){var r=i=this.domainObject(this.dataStore.getDomain(e));null!=No[n]?t.setReserved(n,r):t.h[n]=r}return i},domainObject:function(e,t){null==t&&(t=!1);var n=null;return t&&(n=this.talkObjects(e.id)),Xr.create(e,n).toCompatibleData()},domainObjects:function(){for(var e={},t=0,n=this.dataStore.getDomains();t<n.length;){var i=n[t];++t;var r=i.id;e["_"+r.high+"_"+r.low]=this.domainObject(i)}return e},noteObject:function(e){return ra.of(e)},messageObject:function(e){var t=new xa,n=this.dataStore.getTalk(e.talkId),i=this.userObjectsByIds(n.domainId,[e.userId],t),r={};r.type=Ft.enumIndex(e.type);var a=e.content;r.content=null==a?null:JSON.parse(JSON.stringify(a));var o=e.createdAt;r.createdAt=null==o?null:JSON.parse(JSON.stringify(o));var s=e.id;r.id_i64=null==s?null:JSON.parse(JSON.stringify(s));var l=e.id;r.id="_"+l.high+"_"+l.low,r.user=0<i.length?i[0]:null;var u=e.userId;r.userId="_"+u.high+"_"+u.low,r.talk=this.talkObject(n,t);var c=e.talkId;return r.talkId="_"+c.high+"_"+c.low,r},__class__:ua});var ca=function(){ir.call(this,"messageEvent"),this.emitters=new xa};(n["albero_cli.proxy.MessageEventProxy"]=ca).__name__=["albero_cli","proxy","MessageEventProxy"],ca.__super__=ir,ca.prototype=i(ir.prototype,{registEmitter:function(e,t){_a.factory=this;var n=_a.createInstance(t);if(null!=n){var i=this.emitters;null!=No[e]?i.setReserved(e,n):i.h[e]=n}},noteCreated:function(e,t){var n=this.emitters,i=null!=No[t]?n.getReserved(t):n.h[t];if(null!=i&&(this.emitters.remove(t),null!=e)){var r=e.noteId.toString(),a=this.emitters;null!=No[r]?a.setReserved(r,i):a.h[r]=i,i.talk=this.dataStore.getTalk(e.talkId),i.setFirstReader(this.dataStore.me),i.onceOnSend(e),i.hasEventListener()||this.emitters.remove(r)}},messageCreated:function(e,t){var n=this.emitters,i=null!=No[t]?n.getReserved(t):n.h[t];if(null!=i&&(this.emitters.remove(t),null!=e)){var r=e.id,a="_"+r.high+"_"+r.low,o=this.emitters;if(null!=No[a]?o.setReserved(a,i):o.h[a]=i,i.talk=this.dataStore.getTalk(e.talkId),i.setFirstReader(this.dataStore.me),i.emitOnSend(e),i.removeEventListener("send"),!i.hasEventListener()){var s=e.id;this.emitters.remove("_"+s.high+"_"+s.low)}}},messageRead:function(t,n,e,i){var r=this,a="_"+n.high+"_"+n.low,o=this.emitters,s=null!=No[a]?o.getReserved(a):o.h[a];if(null!=s){s.emitOnRead(e,i);var l=16<=s.__readerIds.length;s.startTimer(l,function(e){e?r.messageReadEveryone(t,n):r.sendNotification("Read",_e.READ_STATUS(t,n))}),0==s.__unreadIds.length&&this.messageReadEveryone(t,n)}},messageReadEveryone:function(e,t){if(null!=t)for(var n=this.emitters.keys();n.hasNext();){var i,r=n.next(),a=this.emitters,o=null!=No[r]?a.getReserved(r):a.h[r];if(null!=o.talk){var s=o.talk.id;i=null!=s&&null!=e&&s.high==e.high&&s.low==e.low}else i=!1;if(i){var l=tt.makeFromIdStr(r),u=l.high-t.high|0;u=0!=u?u:Sa.ucompare(l.low,t.low),(l.high<0?t.high<0?u:-1:0<=t.high?u:1)<=0&&this._messageReadEveryone(e,r)}}},_messageReadEveryone:function(e,t){var n=this.emitters,i=null!=No[t]?n.getReserved(t):n.h[t];null!=i&&(0<i.__unreadIds.length&&i.emitOnRead(i.__unreadIds),i.stopTimer(),i.removeEventListener("read"),i.hasEventListener()||this.emitters.remove(t))},deleteTalk:function(e){for(var t=this.emitters.keys();t.hasNext();){var n,i=t.next(),r=this.emitters,a=null!=No[i]?r.getReserved(i):r.h[i];if(null!=a.talk){var o=a.talk.id;n=null!=o&&null!=e&&o.high==e.high&&o.low==e.low}else n=!1;n&&(a.stopTimer(),this.emitters.remove(i))}},leaveDomain:function(e){for(var t=this.emitters.keys();t.hasNext();){var n,i=t.next(),r=this.emitters,a=null!=No[i]?r.getReserved(i):r.h[i];if(null!=a.talk){var o=a.talk.domainId;n=null!=o&&null!=e&&o.high==e.high&&o.low==e.low}else n=!1;n&&(a.stopTimer(),this.emitters.remove(i))}},__class__:ca});var _a=function(e){this.context=e,this.listeners=new xa,Object.defineProperty(this,"readUsers",{get:this.get_readUsers}),Object.defineProperty(this,"unreadUsers",{get:this.get_unreadUsers})};(n["albero_cli.proxy.Emitter"]=_a).__name__=["albero_cli","proxy","Emitter"],_a.createInstance=function(e){for(var t=null,n=G.fields(e),i=0;i<n.length;){var r=n[i];if(++i,W.startsWith(r,"on")){var a=G.field(e,r);G.isFunction(a)&&(G.deleteField(e,r),null==t&&(t=new _a(e)),t.addEventListener($e.substr(r,2,null),a))}}return t},_a.prototype={addEventListener:function(e,t){var n=this.listeners,i=t;null!=No[e]?n.setReserved(e,i):n.h[e]=i},hasEventListener:function(){var e=this.listeners;return new Fa(e,e.arrayKeys()).hasNext()},removeEventListener:function(e){this.listeners.remove(e)},emit:function(e,t){var n=this.listeners,i=null!=No[e]?n.getReserved(e):n.h[e];null!=i&&i.apply(this,t)},onceOnSend:function(e){this.note=this.createNoteObjectForHubot(e),this.emit("send",[this]),this.removeEventListener("send")},emitOnSend:function(e){this.message=this.get_message(e),this.emit("send",[this,e])},emitOnRead:function(e,t){var n=[];null!=t&&(this.__unreadIds=t);for(var i=0;i<e.length;){var r=e[i];++i,tt.contains(this.__readerIds,r)||(this.__readerIds.push(r),n.push(r)),tt.remove(this.__unreadIds,r)}0<n.length&&this.emit("read",[this.users(n),this.get_readUsers(),this.get_unreadUsers()])},setFirstReader:function(e){this.__readerIds=[e.id],this.__unreadIds=this.talk.userIds.slice(),tt.remove(this.__unreadIds,e.id)},get_readUsers:function(){return this.users(this.__readerIds)},get_unreadUsers:function(){return this.users(this.__unreadIds)},users:function(e){return null==e?[]:_a.factory.hubotObject.userObjectsByIds(this.talk.domainId,e)},createNoteObjectForHubot:function(e){return _a.factory.hubotObject.noteObject(e)},get_message:function(e){return _a.factory.hubotObject.messageObject(e)},answer:function(s){var e,l=this,u=Ft.typeOf(this.message.type),t=this.message.id.split("_");2<t.length?e=new Kn(K.parseInt(t[1]),K.parseInt(t[2])):e=null;switch(u[1]){case 14:case 16:case 18:case 19:case 20:case 21:var n=this.message.content.in_reply_to;e=new Kn(n.high,n.low)}var i=de.Question(e,function(e){var t=e.responses;switch(u[1]){case 13:case 14:case 19:var n=l.users(t[0].userIds),i=l.users(t[1].userIds);s(n,i);break;case 17:case 18:case 21:var r=l.users(t[0].userIds),a=l.users(t[1].userIds);s(r,a);break;case 15:case 16:case 20:var o=t.map(function(e){return l.users(e.userIds)});s(o)}});_a.factory.sendNotification("ReloadData",i)},startTimer:function(e,t){var n=this;null!=this.__readerTimer&&this.stopTimer(),this.__readerTimerWait=e?1:1440;var i=null;i=function(){n.__readerTimerWait*=2,n.__readerTimerWait<1440?(t(!1),n.__readerTimer=Ea.delay(i,60*n.__readerTimerWait*1e3|0)):(t(!0),n.__readerTimer=null)},this.__readerTimer=Ea.delay(i,60*this.__readerTimerWait*1e3|0)},stopTimer:function(){null!=this.__readerTimer&&(this.__readerTimer.stop(),this.__readerTimer=null)},__class__:_a};var ha=function(){ir.call(this,"sendQueue"),this.sendCount=0,this.sendMsgQueue=new da(this,550,new ji("sendQueueMessage")),this.sendAnnounceQueue=new da(this,5050,new ji("sendQueueAnnounce"))};(n["albero_cli.proxy.SendQueueProxy"]=ha).__name__=["albero_cli","proxy","SendQueueProxy"],ha.__super__=ir,ha.prototype=i(ir.prototype,{restart:function(){this.sendMsgQueue.sendNext(),this.sendAnnounceQueue.sendNext()},retryAfter:function(e){this.sendMsgQueue.retryAfter(e),this.sendAnnounceQueue.retryAfter(e)},sendNextTalkMessage:function(){this.sendMsgQueue.sendNext()},sendNext:function(e){null!=e.talkId?this.sendMsgQueue.sendNext():this.sendAnnounceQueue.sendNext()},sendAnnouncement:function(e,t){this.send(e,null,t)},sendMessage:function(e,t){this.send(null,e,t)},send:function(e,t,n){if("string"!=typeof n){var i=new Kn(0,this.sendCount++);this.messageEvent.registEmitter("_"+i.high+"_"+i.low,n);var r=new Ft;if(r.id=i,r.domainId=e,r.talkId=t,r.content=this.parseContent(n),r.type=this.detectType(r.content),r.type==xt.unknown)return;if(r.type==xt.file&&null!=r.content.path)return void this.sendFile(t,r.content,"_"+i.high+"_"+i.low);if(r.type==xt.noteCreated)return void this.sendNote(t,r.content,"_"+i.high+"_"+i.low);r.type!=xt.yesOrNo&&r.type!=xt.selectOne||null!=r.content.listing||(r.content.listing=!1),this.applyLimitToMessage(r),this.pushQueue(r)}else for(var a=0,o=h.slice(n,1024);a<o.length;){var s=o[a];++a;var l=new Ft;l.domainId=e,l.talkId=t,l.type=xt.text,l.content=s,this.pushQueue(l)}},sendNote:function(e,t,n){var i=this.validateNoteObject(t);switch(i[1]){case 0:var r=i[2];Gi._e("["+$e.dateStr(new Date)+"] ","validation error: "+r,"","","","");break;case 1:var a=i[2];this.sendMsgQueue.pushQueue("Note",ue.CREATE_NOTE_FOR_HUBOT(e,a,!0,n))}},validateNoteObject:function(e){if(this.isStringEmpty(e.note_title))return ka.Left("note_title is empty");if(this.isStringEmpty(e.note_content))return ka.Left("note_content is empty");var t=null;if(e.note_attachments instanceof Array&&null==e.note_attachments.__enum__&&this.hasPathField(e.note_attachments))t=e.note_attachments;else{if(null!=e.note_attachments)return ka.Left("note_attachments is invalid: "+K.string(e.note_attachments));t=[]}return ka.Right({title:e.note_title,content:e.note_content,attachments:t})},hasPathField:function(e){var t=this;return et.foreach(e,function(e){return!t.isStringEmpty(e.path)})},isStringEmpty:function(e){return null==e||0==e.length},sendFile:function(e,t,n){var i,r=null,a=null;if("string"==typeof t)i=t;else{if(t.path instanceof Array&&null==t.path.__enum__)return void this.sendFiles(e,t.path,t.name,t.type,t.text,n);if(null!=t.text)return void this.sendFiles(e,[t.path],[t.name],[t.type],t.text,n);i=t.path,r=t.name,a=t.type}null!=i&&qa.existsSync(i)?this.sendMsgQueue.pushQueue("File",Z.UPLOAD_PATH(e,i,r,a,n)):Gi._e("["+$e.dateStr(new Date)+"] ","File not found: ",i,"","","")},sendFiles:function(e,t,n,i,r,a){for(var o=0;o<t.length;){var s=t[o];if(++o,!qa.existsSync(s))return void Gi._e("["+$e.dateStr(new Date)+"] ","File not found: ",s,"","","")}var l=t.length;if(null==n){for(var u=[],c=0,_=l;c<_;){c++;u.push(null)}n=u}if(null==i){for(var h=[],d=0,f=l;d<f;){d++;h.push(null)}i=h}n.length==l&&i.length==l?this.sendMsgQueue.pushQueue("File",Z.UPLOAD_MULTI_PATH(e,r,t,n,i,a)):Gi._e("["+$e.dateStr(new Date)+"] ","The length of name or type must be the same as path length.","","","","")},pushQueue:function(e){null==e.talkId?this.sendAnnounceQueue.pushQueue("Send",e):this.sendMsgQueue.pushQueue("Send",e)},parseContent:function(e){if(null==e)return null;for(var t=G.fields(e),n=0;n<t.length;){var i=t[n];++n;var r=G.field(e,i);if("string"==typeof r){var a=null;if("stamp_set"==i)a=K.parseInt(r);else if("stamp_index"==i)a=tt.parse(r);else if("file_id"==i||"in_reply_to"==i){var o=r.split("_");if(2<o.length)a=new Kn(K.parseInt(o[1]),K.parseInt(o[2]));else a=null}else if("close_yesno"==i||"close_select"==i||"close_task"==i){e.close=$e.substr(i,6,null),i="in_reply_to";var s=r.split("_");if(2<s.length)a=new Kn(K.parseInt(s[1]),K.parseInt(s[2]));else a=null}null!=a&&(e[i]=a)}else if(null!=r&&G.isObject(e)&&null!=r.high&&null!=r.low){var l=new Kn(r.high,r.low);e[i]=l}}return 1==t.length&&null!=e.text?e.text:e},detectType:function(e){if(null==e)return xt.unknown;if("string"==typeof e)return xt.text;if(null!=e.stamp_set)return xt.stamp;if(null!=e.lat)return xt.geo;if(null!=e.file_id||null!=e.path)return xt.file;if(null!=e.close){var t=e.close;if(G.deleteField(e,"close"),"yesno"==t)return xt.yesOrNoClosed;if("select"==t)return xt.selectOneClosed;if("task"==t)return xt.todoClosed}else if(null!=e.in_reply_to){if("boolean"==typeof e.response)return xt.yesOrNoReply;var n=e.response;if("number"==typeof n&&(0|n)===n)return xt.selectOneReply;if(null!=e.done)return xt.todoDone}else{if(null!=e.question)return null==e.options?xt.yesOrNo:xt.selectOne;if(null!=e.title)return xt.todo;if(null!=e.note_title)return xt.noteCreated}return xt.unknown},applyLimitToMessage:function(e){switch(e.type[1]){case 1:var t=e.content;null!=t&&1024<t.length&&(e.content=t.substring(0,1024));break;case 2:case 5:var n=e.content.text;null!=n&&1024<n.length&&(e.content.text=n.substring(0,1024));break;case 13:case 15:var i=e.content.question;if(null!=i&&1024<i.length&&(e.content.question=i.substring(0,1024)),e.type==xt.selectOne){var r=e.content.options;9<r.length&&(r=r.slice(0,9),e.content.options=r);for(var a=0,o=r.length;a<o;){var s=a++;64<r[s].length&&(r[s]=r[s].substring(0,64))}}break;case 17:var l=e.content.title;null!=l&&1024<l.length&&(e.content.title=l.substring(0,1024))}},__class__:ha});var da=function(e,t,n){this.proxy=e,this.sendSpan=t,this.storage=n,this.sendQueue=this.loadQueue(),this.sending=0<this.sendQueue.length,this.lastSendNode=null,this.lastSendTime=new Date(0)};(n["albero_cli.proxy._SendQueueProxy.SendQueue"]=da).__name__=["albero_cli","proxy","_SendQueueProxy","SendQueue"],da.prototype={pushQueue:function(e,t){this.sendQueue.push({name:e,param:t}),this.saveQueue(),this.sending||(this.sending=!0,this.sendNext())},sendNext:function(){if(this.sending&&0!=this.sendQueue.length){var e=(new Date).getTime()-this.lastSendTime.getTime(),t=0|Math.max(this.sendSpan-e,100);Ea.delay(go(this,this.sendNotification),t)}else this.closeQueue()},retryAfter:function(e){this.sending&&null!=this.lastSendNode?(this.sendQueue.unshift(this.lastSendNode),this.saveQueue(),Ea.delay(go(this,this.sendNotification),e)):this.closeQueue()},sendNotification:function(){var e=this.sendQueue.shift();this.saveQueue(),this.proxy.sendNotification(e.name,e.param),this.lastSendNode=e,this.lastSendTime=new Date},closeQueue:function(){this.sending=!1,this.lastSendNode=null},saveQueue:function(){null!=this.storage&&this.storage.save(this.sendQueue)},loadQueue:function(){if(null!=this.storage){var e=this.storage.load();if(null!=e)return e}return[]},__class__:da};var fa=function(e,t,n){this.code=e,this.message=t,this.detail=n};(n["albero_cli.value.ApiErrorResponse"]=fa).__name__=["albero_cli","value","ApiErrorResponse"],fa.of=function(e){switch(e.code){case 400:if("invalid parameter"==e.message)return new fa(ma.INVALID_PARAMETER);break;case 403:if("forbidden"==e.message)return new fa(ma.FORBIDDEN);break;case 404:if("not found"==e.message)return new fa(ma.NOT_FOUND);break;case 409:switch(e.message){case"conflict":return new fa(ma.CONFLICT);case"locked by another user":return new fa(ma.LOCKED_BY_ANOTHER_USER,null,{userId:e.detail.user_id})}break;case 429:return fa.createTooManyRequestsError(e.message,e.detail.retry_after)}var t="please contact us: error = "+K.string(e);return Gi._w("["+$e.dateStr(new Date)+"] ",t,"","","",""),new fa(ma.UNKNOWN)},fa.createInvalidParameterError=function(e){return new fa(ma.INVALID_PARAMETER,e)},fa.createTooManyRequestsError=function(e,t){return new fa(ma.TOO_MANY_REQUESTS,e,{retryAfter:t})},fa.prototype={__class__:fa};var ma=function(){};(n["albero_cli.value.ApiErrorCode"]=ma).__name__=["albero_cli","value","ApiErrorCode"];var pa=function(){};(n["albero_cli.value.note.DeleteNoteResult"]=pa).__name__=["albero_cli","value","note","DeleteNoteResult"],pa.of=function(e){return new pa},pa.prototype={__class__:pa};var ga=function(e){this.note=e};(n["albero_cli.value.note.GetNoteResult"]=ga).__name__=["albero_cli","value","note","GetNoteResult"],ga.of=function(e){return new ga(ra.of(e.note))},ga.prototype={__class__:ga};var va=function(e){this.note=e};(n["albero_cli.value.note.UpdateNoteResult"]=va).__name__=["albero_cli","value","note","UpdateNoteResult"],va.of=function(e){return new va(ra.of(e.note))},va.prototype={__class__:va};function ya(){}(n["haxe.IMap"]=ya).__name__=["haxe","IMap"];var Sa={};(n["haxe._Int32.Int32_Impl_"]=Sa).__name__=["haxe","_Int32","Int32_Impl_"],Sa.ucompare=function(e,t){return e<0?t<0?~t-~e|0:1:t<0?-1:e-t|0};var wa={};(n["haxe._Int64.Int64_Impl_"]=wa).__name__=["haxe","_Int64","Int64_Impl_"],wa.toString=function(e){var t=e,n=new Kn(0,0);if(t.high==n.high&&t.low==n.low)return"0";var i="",r=!1;t.high<0&&(r=!0);for(var a=new Kn(0,10);;){var o=new Kn(0,0);if(t.high==o.high&&t.low==o.low)break;var s=wa.divMod(t,a);if(s.modulus.high<0){var l=s.modulus,u=~l.high,c=-l.low;if(0==c){u++;u|=0}i=new Kn(u,c).low+i;var _=s.quotient,h=~_.high,d=-_.low;if(0==d){h++;h|=0}t=new Kn(h,d)}else i=s.modulus.low+i,t=s.quotient}return r&&(i="-"+i),i},wa.divMod=function(e,t){if(0==t.high)switch(t.low){case 0:throw new Wa("divide by zero");case 1:return{quotient:new Kn(e.high,e.low),modulus:new Kn(0,0)}}var n,i=e.high<0!=t.high<0;if(e.high<0){var r=~e.high,a=-e.low;if(0==a){r++;r|=0}n=new Kn(r,a)}else{n=new Kn(e.high,e.low)}if(t.high<0){var o=~t.high,s=-t.low;if(0==s){o++;o|=0}t=new Kn(o,s)}else t=t;for(var l=new Kn(0,0),u=new Kn(0,1);!(t.high<0);){var c=Sa.ucompare(t.high,n.high),_=0!=c?c:Sa.ucompare(t.low,n.low);63,t=new Kn(t.high<<1|t.low>>>31,t.low<<1);if(63,u=new Kn(u.high<<1|u.low>>>31,u.low<<1),0<=_)break}for(;;){var h=new Kn(0,0);if(u.high==h.high&&u.low==h.low)break;var d=Sa.ucompare(n.high,t.high);if(0<=(0!=d?d:Sa.ucompare(n.low,t.low))){l=new Kn(l.high|u.high,l.low|u.low);var f=n.high-t.high|0,m=n.low-t.low|0;if(Sa.ucompare(n.low,t.low)<0){f--;f|=0}n=new Kn(f,m)}63,u=new Kn(u.high>>>1,u.high<<31|u.low>>>1);63,t=new Kn(t.high>>>1,t.high<<31|t.low>>>1)}if(i){var p=~l.high,g=-l.low;if(0==g){p++;p|=0}l=new Kn(p,g)}if(e.high<0){var v=~n.high,y=-n.low;if(0==y){v++;v|=0}n=new Kn(v,y)}return{quotient:l,modulus:n}};var Ta=function(){};(n["haxe.Int64Helper"]=Ta).__name__=["haxe","Int64Helper"],Ta.parseString=function(e){var t=new Kn(0,10),n=new Kn(0,0),i=new Kn(0,1),r=!1,a=W.trim(e);"-"==a.charAt(0)&&(r=!0,a=a.substring(1,a.length));for(var o=a.length,s=0,l=o;s<l;){var u=s++,c=$e.cca(a,o-1-u)-48;if(c<0||9<c)throw new Wa("NumberFormatError");var _=new Kn(c>>31,c);if(r){var h=65535&i.low,d=i.low>>>16,f=65535&_.low,m=_.low>>>16,p=Sa._mul(h,f),g=Sa._mul(d,f),v=Sa._mul(h,m),y=p,S=(Sa._mul(d,m)+(v>>>16)|0)+(g>>>16)|0;if(y=y+(v<<=16)|0,Sa.ucompare(y,v)<0){S++;S|=0}if(y=y+(g<<=16)|0,Sa.ucompare(y,g)<0){S++;S|=0}S=S+(Sa._mul(i.low,_.high)+Sa._mul(i.high,_.low)|0)|0;var w=new Kn(S,y),T=n.high-w.high|0,I=n.low-w.low|0;if(Sa.ucompare(n.low,w.low)<0){T--;T|=0}if(!((n=new Kn(T,I)).high<0))throw new Wa("NumberFormatError: Underflow")}else{var E=65535&i.low,N=i.low>>>16,A=65535&_.low,b=_.low>>>16,D=Sa._mul(E,A),k=Sa._mul(N,A),C=Sa._mul(E,b),O=D,M=(Sa._mul(N,b)+(C>>>16)|0)+(k>>>16)|0;if(O=O+(C<<=16)|0,Sa.ucompare(O,C)<0){M++;M|=0}if(O=O+(k<<=16)|0,Sa.ucompare(O,k)<0){M++;M|=0}M=M+(Sa._mul(i.low,_.high)+Sa._mul(i.high,_.low)|0)|0;var R=new Kn(M,O),F=n.high+R.high|0,x=n.low+R.low|0;if(Sa.ucompare(x,n.low)<0){F++;F|=0}if((n=new Kn(F,x)).high<0)throw new Wa("NumberFormatError: Overflow")}var U=65535&i.low,P=i.low>>>16,L=65535&t.low,B=t.low>>>16,H=Sa._mul(U,L),j=Sa._mul(P,L),Y=Sa._mul(U,B),G=H,z=(Sa._mul(P,B)+(Y>>>16)|0)+(j>>>16)|0;if(G=G+(Y<<=16)|0,Sa.ucompare(G,Y)<0){z++;z|=0}if(G=G+(j<<=16)|0,Sa.ucompare(G,j)<0){z++;z|=0}z=z+(Sa._mul(i.low,t.high)+Sa._mul(i.high,t.low)|0)|0,i=new Kn(z,G)}return n};var Ia=function(){this.buf=new T,this.cache=[],this.useCache=Ia.USE_CACHE,this.useEnumIndex=Ia.USE_ENUM_INDEX,this.shash=new xa,this.scount=0};(n["haxe.Serializer"]=Ia).__name__=["haxe","Serializer"],Ia.run=function(e){var t=new Ia;return t.serialize(e),t.toString()},Ia.prototype={toString:function(){return this.buf.b},serializeString:function(e){var t=this.shash,n=null!=No[e]?t.getReserved(e):t.h[e];if(null!=n)return this.buf.b+="R",void(this.buf.b+=null==n?"null":""+n);var i=this.shash,r=this.scount++;null!=No[e]?i.setReserved(e,r):i.h[e]=r,this.buf.b+="y",e=encodeURIComponent(e),this.buf.b+=K.string(e.length),this.buf.b+=":",this.buf.b+=null==e?"null":""+e},serializeRef:function(e){for(var t=typeof e,n=0,i=this.cache.length;n<i;){var r=n++,a=this.cache[r];if(typeof a==t&&a==e)return this.buf.b+="r",this.buf.b+=null==r?"null":""+r,!0}return this.cache.push(e),!1},serializeFields:function(e){for(var t=0,n=G.fields(e);t<n.length;){var i=n[t];++t,this.serializeString(i),this.serialize(G.field(e,i))}this.buf.b+="g"},serialize:function(e){var t=ee.typeof(e);switch(t[1]){case 0:this.buf.b+="n";break;case 1:var n=e;if(0==n)return void(this.buf.b+="z");this.buf.b+="i",this.buf.b+=null==n?"null":""+n;break;case 2:var i=e;isNaN(i)?this.buf.b+="k":isFinite(i)?(this.buf.b+="d",this.buf.b+=null==i?"null":""+i):this.buf.b+=i<0?"m":"p";break;case 3:this.buf.b+=e?"t":"f";break;case 4:if(Va.__instanceof(e,To)){var r=ee.getClassName(e);this.buf.b+="A",this.serializeString(r)}else if(Va.__instanceof(e,Io))this.buf.b+="B",this.serializeString(ee.getEnumName(e));else{if(this.useCache&&this.serializeRef(e))return;this.buf.b+="o",this.serializeFields(e)}break;case 5:throw new Wa("Cannot serialize function");case 6:var a=t[2];if(a==String)return void this.serializeString(e);if(this.useCache&&this.serializeRef(e))return;switch(a){case Array:var o=0;this.buf.b+="a";for(var s=0,l=e.length;s<l;){var u=s++;null==e[u]?++o:(0<o&&(1==o?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==o?"null":""+o),o=0),this.serialize(e[u]))}0<o&&(1==o?this.buf.b+="n":(this.buf.b+="u",this.buf.b+=null==o?"null":""+o)),this.buf.b+="h";break;case Date:var c=e;this.buf.b+="v",this.buf.b+=K.string(c.getTime());break;case $:this.buf.b+="l";for(var _=e.h;null!=_;){var h=_.item;_=_.next;var d=h;this.serialize(d)}this.buf.b+="h";break;case Oa:this.buf.b+="q";for(var f=e,m=f.keys();m.hasNext();){var p=m.next();this.buf.b+=":",this.buf.b+=null==p?"null":""+p,this.serialize(f.h[p])}this.buf.b+="h";break;case Ma:this.buf.b+="M";for(var g=e,v=g.keys();v.hasNext();){var y=v.next(),S=G.field(y,"__id__");G.deleteField(y,"__id__"),this.serialize(y),y.__id__=S,this.serialize(g.h[y.__id__])}this.buf.b+="h";break;case xa:this.buf.b+="b";for(var w=e,T=w.keys();T.hasNext();){var I=T.next();this.serializeString(I),this.serialize(null!=No[I]?w.getReserved(I):w.h[I])}this.buf.b+="h";break;case Ua:var E=e;this.buf.b+="s",this.buf.b+=K.string(Math.ceil(8*E.length/6)),this.buf.b+=":";var N=0,A=E.length-2,b=Ia.BASE64_CODES;if(null==b){var D=Ia.BASE64.length;b=new Array(D);for(var k=0,C=Ia.BASE64.length;k<C;){var O=k++;b[O]=$e.cca(Ia.BASE64,O)}Ia.BASE64_CODES=b}for(;N<A;){var M=E.b[N++],R=E.b[N++],F=E.b[N++];this.buf.b+=String.fromCharCode(b[M>>2]),this.buf.b+=String.fromCharCode(b[63&(M<<4|R>>4)]),this.buf.b+=String.fromCharCode(b[63&(R<<2|F>>6)]),this.buf.b+=String.fromCharCode(b[63&F])}if(N==A){var x=E.b[N++],U=E.b[N++];this.buf.b+=String.fromCharCode(b[x>>2]),this.buf.b+=String.fromCharCode(b[63&(x<<4|U>>4)]),this.buf.b+=String.fromCharCode(b[U<<2&63])}else if(N==1+A){var P=E.b[N++];this.buf.b+=String.fromCharCode(b[P>>2]),this.buf.b+=String.fromCharCode(b[P<<4&63])}break;default:this.useCache&&this.cache.pop(),null!=e.hxSerialize?(this.buf.b+="C",this.serializeString(ee.getClassName(a)),this.useCache&&this.cache.push(e),e.hxSerialize(this),this.buf.b+="g"):(this.buf.b+="c",this.serializeString(ee.getClassName(a)),this.useCache&&this.cache.push(e),this.serializeFields(e))}break;case 7:var L=t[2];if(this.useCache){if(this.serializeRef(e))return;this.cache.pop()}this.buf.b+=K.string(this.useEnumIndex?"j":"w"),this.serializeString(ee.getEnumName(L)),this.useEnumIndex?(this.buf.b+=":",this.buf.b+=K.string(e[1])):this.serializeString(e[0]),this.buf.b+=":";var B=e.length;this.buf.b+=K.string(B-2);for(var H=2,j=B;H<j;){var Y=H++;this.serialize(e[Y])}this.useCache&&this.cache.push(e);break;default:throw new Wa("Cannot serialize "+K.string(e))}},__class__:Ia};var Ea=function(e){var t=this;this.id=setInterval(function(){t.run()},e)};(n["haxe.Timer"]=Ea).__name__=["haxe","Timer"],Ea.delay=function(e,t){var n=new Ea(t);return n.run=function(){n.stop(),e()},n},Ea.prototype={stop:function(){null!=this.id&&(clearInterval(this.id),this.id=null)},run:function(){},__class__:Ea};function Na(){}(n["haxe._Unserializer.DefaultResolver"]=Na).__name__=["haxe","_Unserializer","DefaultResolver"],Na.prototype={resolveClass:function(e){return ee.resolveClass(e)},resolveEnum:function(e){return ee.resolveEnum(e)},__class__:Na};var Aa=function(e){this.buf=e,this.length=e.length,this.pos=0,this.scache=[],this.cache=[];var t=Aa.DEFAULT_RESOLVER;null==t&&(t=new Na,Aa.DEFAULT_RESOLVER=t),this.resolver=t};(n["haxe.Unserializer"]=Aa).__name__=["haxe","Unserializer"],Aa.initCodes=function(){for(var e=[],t=0,n=Aa.BASE64.length;t<n;){var i=t++;e[Aa.BASE64.charCodeAt(i)]=i}return e},Aa.run=function(e){return new Aa(e).unserialize()},Aa.prototype={readDigits:function(){for(var e=0,t=!1,n=this.pos;;){var i=this.buf.charCodeAt(this.pos);if(i!=i)break;if(45!=i){if(i<48||57<i)break;e=10*e+(i-48),this.pos++}else{if(this.pos!=n)break;t=!0,this.pos++}}return t&&(e*=-1),e},readFloat:function(){for(var e=this.pos;;){var t=this.buf.charCodeAt(this.pos);if(t!=t)break;if(!(43<=t&&t<58||101==t||69==t))break;this.pos++}return parseFloat($e.substr(this.buf,e,this.pos-e))},unserializeObject:function(e){for(;;){if(this.pos>=this.length)throw new Wa("Invalid object");if(103==this.buf.charCodeAt(this.pos))break;var t=this.unserialize();if("string"!=typeof t)throw new Wa("Invalid object key");var n=this.unserialize();e[t]=n}this.pos++},unserializeEnum:function(e,t){if(58!=this.buf.charCodeAt(this.pos++))throw new Wa("Invalid enum format");var n=this.readDigits();if(0==n)return ee.createEnum(e,t);for(var i=[];0<n--;)i.push(this.unserialize());return ee.createEnum(e,t,i)},unserialize:function(){switch(this.buf.charCodeAt(this.pos++)){case 65:var e=this.unserialize(),t=this.resolver.resolveClass(e);if(null==t)throw new Wa("Class not found "+e);return t;case 66:var n=this.unserialize(),i=this.resolver.resolveEnum(n);if(null==i)throw new Wa("Enum not found "+n);return i;case 67:var r=this.unserialize(),a=this.resolver.resolveClass(r);if(null==a)throw new Wa("Class not found "+r);var o=ee.createEmptyInstance(a);if(this.cache.push(o),o.hxUnserialize(this),103!=this.buf.charCodeAt(this.pos++))throw new Wa("Invalid custom data");return o;case 77:var s=new Ma;this.cache.push(s);for(this.buf;104!=this.buf.charCodeAt(this.pos);){var l=this.unserialize();s.set(l,this.unserialize())}return this.pos++,s;case 82:var u=this.readDigits();if(u<0||u>=this.scache.length)throw new Wa("Invalid string reference");return this.scache[u];case 97:this.buf;var c=[];for(this.cache.push(c);;){var _=this.buf.charCodeAt(this.pos);if(104==_){this.pos++;break}if(117==_){this.pos++;var h=this.readDigits();c[c.length+h-1]=null}else c.push(this.unserialize())}return c;case 98:var d=new xa;this.cache.push(d);for(this.buf;104!=this.buf.charCodeAt(this.pos);){var f=this.unserialize(),m=this.unserialize();null!=No[f]?d.setReserved(f,m):d.h[f]=m}return this.pos++,d;case 99:var p=this.unserialize(),g=this.resolver.resolveClass(p);if(null==g)throw new Wa("Class not found "+p);var v=ee.createEmptyInstance(g);return this.cache.push(v),this.unserializeObject(v),v;case 100:return this.readFloat();case 102:return!1;case 105:return this.readDigits();case 106:var y=this.unserialize(),S=this.resolver.resolveEnum(y);if(null==S)throw new Wa("Enum not found "+y);this.pos++;var w=this.readDigits(),T=S.__constructs__.slice()[w];if(null==T)throw new Wa("Unknown enum index "+y+"@"+w);var I=this.unserializeEnum(S,T);return this.cache.push(I),I;case 107:return NaN;case 108:var E=new $;this.cache.push(E);for(this.buf;104!=this.buf.charCodeAt(this.pos);)E.add(this.unserialize());return this.pos++,E;case 109:return-1/0;case 110:return null;case 111:var N={};return this.cache.push(N),this.unserializeObject(N),N;case 112:return 1/0;case 113:var A=new Oa;this.cache.push(A);this.buf;for(var b=this.buf.charCodeAt(this.pos++);58==b;){var D=this.readDigits(),k=this.unserialize();A.h[D]=k,b=this.buf.charCodeAt(this.pos++)}if(104!=b)throw new Wa("Invalid IntMap format");return A;case 114:var C=this.readDigits();if(C<0||C>=this.cache.length)throw new Wa("Invalid reference");return this.cache[C];case 115:var O=this.readDigits(),M=this.buf;if(58!=this.buf.charCodeAt(this.pos++)||this.length-this.pos<O)throw new Wa("Invalid bytes length");var R=Aa.CODES;null==R&&(R=Aa.initCodes(),Aa.CODES=R);for(var F=this.pos,x=3&O,U=F+(O-x),P=new Ua(new ArrayBuffer(3*(O>>2)+(2<=x?x-1:0))),L=0;F<U;){var B=R[M.charCodeAt(F++)],H=R[M.charCodeAt(F++)];P.b[L++]=255&(B<<2|H>>4);var j=R[M.charCodeAt(F++)];P.b[L++]=255&(H<<4|j>>2);var Y=R[M.charCodeAt(F++)];P.b[L++]=255&(j<<6|Y)}if(2<=x){var G=R[M.charCodeAt(F++)],z=R[M.charCodeAt(F++)];if(P.b[L++]=255&(G<<2|z>>4),3==x){var K=R[M.charCodeAt(F++)];P.b[L++]=255&(z<<4|K>>2)}}return this.pos+=O,this.cache.push(P),P;case 116:return!0;case 118:var W;if(48<=this.buf.charCodeAt(this.pos)&&this.buf.charCodeAt(this.pos)<=57&&48<=this.buf.charCodeAt(this.pos+1)&&this.buf.charCodeAt(this.pos+1)<=57&&48<=this.buf.charCodeAt(this.pos+2)&&this.buf.charCodeAt(this.pos+2)<=57&&48<=this.buf.charCodeAt(this.pos+3)&&this.buf.charCodeAt(this.pos+3)<=57&&45==this.buf.charCodeAt(this.pos+4))W=$e.strDate($e.substr(this.buf,this.pos,19)),this.pos+=19;else{var V=this.readFloat();W=new Date(V)}return this.cache.push(W),W;case 119:var q=this.unserialize(),Q=this.resolver.resolveEnum(q);if(null==Q)throw new Wa("Enum not found "+q);var J=this.unserializeEnum(Q,this.unserialize());return this.cache.push(J),J;case 120:throw Wa.wrap(this.unserialize());case 121:var X=this.readDigits();if(58!=this.buf.charCodeAt(this.pos++)||this.length-this.pos<X)throw new Wa("Invalid string length");var Z=$e.substr(this.buf,this.pos,X);return this.pos+=X,Z=decodeURIComponent(Z.split("+").join(" ")),this.scache.push(Z),Z;case 122:return 0}throw this.pos--,new Wa("Invalid char "+this.buf.charAt(this.pos)+" at position "+this.pos)},__class__:Aa};function ba(){}(n["haxe.ds.BalancedTree"]=ba).__name__=["haxe","ds","BalancedTree"],ba.prototype={set:function(e,t){this.root=this.setLoop(e,t,this.root)},get:function(e){for(var t=this.root;null!=t;){var n=this.compare(e,t.key);if(0==n)return t.value;t=n<0?t.left:t.right}return null},remove:function(e){try{return this.root=this.removeLoop(e,this.root),!0}catch(e){if(e instanceof Wa&&(e=e.val),Va.__instanceof(e,String))return!1;throw e}},keys:function(){var e=[];return this.keysLoop(this.root,e),$e.iter(e)},setLoop:function(e,t,n){if(null==n)return new Da(null,e,t,null);var i=this.compare(e,n.key);if(0==i)return new Da(n.left,e,t,n.right,null==n?0:n._height);if(i<0){var r=this.setLoop(e,t,n.left);return this.balance(r,n.key,n.value,n.right)}var a=this.setLoop(e,t,n.right);return this.balance(n.left,n.key,n.value,a)},removeLoop:function(e,t){if(null==t)throw new Wa("Not_found");var n=this.compare(e,t.key);return 0==n?this.merge(t.left,t.right):n<0?this.balance(this.removeLoop(e,t.left),t.key,t.value,t.right):this.balance(t.left,t.key,t.value,this.removeLoop(e,t.right))},keysLoop:function(e,t){null!=e&&(this.keysLoop(e.left,t),t.push(e.key),this.keysLoop(e.right,t))},merge:function(e,t){if(null==e)return t;if(null==t)return e;var n=this.minBinding(t);return this.balance(e,n.key,n.value,this.removeMinBinding(t))},minBinding:function(e){if(null==e)throw new Wa("Not_found");return null==e.left?e:this.minBinding(e.left)},removeMinBinding:function(e){return null==e.left?e.right:this.balance(this.removeMinBinding(e.left),e.key,e.value,e.right)},balance:function(e,t,n,i){var r=null==e?0:e._height,a=null==i?0:i._height;if(a+2<r){var o=e.left,s=e.right;return(null==o?0:o._height)>=(null==s?0:s._height)?new Da(e.left,e.key,e.value,new Da(e.right,t,n,i)):new Da(new Da(e.left,e.key,e.value,e.right.left),e.right.key,e.right.value,new Da(e.right.right,t,n,i))}if(r+2<a){var l=i.right,u=i.left;return(null==l?0:l._height)>(null==u?0:u._height)?new Da(new Da(e,t,n,i.left),i.key,i.value,i.right):new Da(new Da(e,t,n,i.left.left),i.left.key,i.left.value,new Da(i.left.right,i.key,i.value,i.right))}return new Da(e,t,n,i,(a<r?r:a)+1)},compare:function(e,t){return G.compare(e,t)},__class__:ba};var Da=function(e,t,n,i,r){if(null==r&&(r=-1),this.left=e,this.key=t,this.value=n,this.right=i,-1==r){var a,o=this.left,s=this.right;if((null==o?0:o._height)>(null==s?0:s._height)){var l=this.left;a=null==l?0:l._height}else{var u=this.right;a=null==u?0:u._height}this._height=a+1}else this._height=r};(n["haxe.ds.TreeNode"]=Da).__name__=["haxe","ds","TreeNode"],Da.prototype={__class__:Da};var ka=n["haxe.ds.Either"]={__ename__:["haxe","ds","Either"],__constructs__:["Left","Right"]};ka.Left=function(e){var t=["Left",0,e];return t.__enum__=ka,t.toString=s,t},ka.Right=function(e){var t=["Right",1,e];return t.__enum__=ka,t.toString=s,t},ka.__empty_constructs__=[];var Ca=function(){ba.call(this)};(n["haxe.ds.EnumValueMap"]=Ca).__name__=["haxe","ds","EnumValueMap"],Ca.__interfaces__=[ya],Ca.__super__=ba,Ca.prototype=i(ba.prototype,{compare:function(e,t){var n=e[1]-t[1];if(0!=n)return n;var i=e.slice(2),r=t.slice(2);return 0==i.length&&0==r.length?0:this.compareArgs(i,r)},compareArgs:function(e,t){var n=e.length-t.length;if(0!=n)return n;for(var i=0,r=e.length;i<r;){var a=i++,o=this.compareArg(e[a],t[a]);if(0!=o)return o}return 0},compareArg:function(e,t){return G.isEnumValue(e)&&G.isEnumValue(t)?this.compare(e,t):e instanceof Array&&null==e.__enum__&&t instanceof Array&&null==t.__enum__?this.compareArgs(e,t):G.compare(e,t)},__class__:Ca});var Oa=function(){this.h={}};(n["haxe.ds.IntMap"]=Oa).__name__=["haxe","ds","IntMap"],Oa.__interfaces__=[ya],Oa.prototype={remove:function(e){return!!this.h.hasOwnProperty(e)&&(delete this.h[e],!0)},keys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(0|t);return $e.iter(e)},__class__:Oa};var Ma=function(){this.h={__keys__:{}}};(n["haxe.ds.ObjectMap"]=Ma).__name__=["haxe","ds","ObjectMap"],Ma.__interfaces__=[ya],Ma.assignId=function(e){return e.__id__=++Ma.count},Ma.getId=function(e){return e.__id__},Ma.prototype={set:function(e,t){var n=e.__id__||(e.__id__=++Ma.count);this.h[n]=t,this.h.__keys__[n]=e},keys:function(){var e=[];for(var t in this.h.__keys__)this.h.hasOwnProperty(t)&&e.push(this.h.__keys__[t]);return $e.iter(e)},__class__:Ma};var Ra=n["haxe.ds.Option"]={__ename__:["haxe","ds","Option"],__constructs__:["Some","None"]};Ra.Some=function(e){var t=["Some",0,e];return t.__enum__=Ra,t.toString=s,t},Ra.None=["None",1],Ra.None.toString=s,(Ra.None.__enum__=Ra).__empty_constructs__=[Ra.None];var Fa=function(e,t){this.map=e,this.keys=t,this.index=0,this.count=t.length};(n["haxe.ds._StringMap.StringMapIterator"]=Fa).__name__=["haxe","ds","_StringMap","StringMapIterator"],Fa.prototype={hasNext:function(){return this.index<this.count},next:function(){var e=this.map,t=this.keys[this.index++];return null!=No[t]?e.getReserved(t):e.h[t]},__class__:Fa};var xa=function(){this.h={}};(n["haxe.ds.StringMap"]=xa).__name__=["haxe","ds","StringMap"],xa.__interfaces__=[ya],xa.prototype={setReserved:function(e,t){null==this.rh&&(this.rh={}),this.rh["$"+e]=t},getReserved:function(e){return null==this.rh?null:this.rh["$"+e]},existsReserved:function(e){return null!=this.rh&&this.rh.hasOwnProperty("$"+e)},remove:function(e){return null!=No[e]?(e="$"+e,!(null==this.rh||!this.rh.hasOwnProperty(e))&&(delete this.rh[e],!0)):!!this.h.hasOwnProperty(e)&&(delete this.h[e],!0)},keys:function(){return $e.iter(this.arrayKeys())},arrayKeys:function(){var e=[];for(var t in this.h)this.h.hasOwnProperty(t)&&e.push(t);if(null!=this.rh)for(var t in this.rh)36==t.charCodeAt(0)&&e.push(t.substr(1));return e},iterator:function(){return new Fa(this,this.arrayKeys())},__class__:xa};var Ua=function(e){this.length=e.byteLength,this.b=new Uint8Array(e),(this.b.bufferValue=e).hxBytes=this,e.bytes=this.b};(n["haxe.io.Bytes"]=Ua).__name__=["haxe","io","Bytes"],Ua.alloc=function(e){return new Ua(new ArrayBuffer(e))},Ua.ofString=function(e){for(var t=[],n=0;n<e.length;){var i=e.charCodeAt(n++);55296<=i&&i<=56319&&(i=i-55232<<10|1023&e.charCodeAt(n++)),i<=127?t.push(i):(i<=2047?t.push(192|i>>6):(i<=65535?t.push(224|i>>12):(t.push(240|i>>18),t.push(128|i>>12&63)),t.push(128|i>>6&63)),t.push(128|63&i))}return new Ua(new Uint8Array(t).buffer)},Ua.ofData=function(e){var t=e.hxBytes;return null!=t?t:new Ua(e)},Ua.fastGet=function(e,t){return e.bytes[t]},Ua.prototype={getString:function(e,t){if(e<0||t<0||e+t>this.length)throw new Wa(Ga.OutsideBounds);for(var n="",i=this.b,r=String.fromCharCode,a=e,o=e+t;a<o;){var s=i[a++];if(s<128){if(0==s)break;n+=r(s)}else if(s<224)n+=r((63&s)<<6|127&i[a++]);else if(s<240){n+=r((31&s)<<12|(127&i[a++])<<6|127&i[a++])}else{var l=(15&s)<<18|(127&i[a++])<<12|(127&i[a++])<<6|127&i[a++];n+=r(55232+(l>>10)),n+=r(1023&l|56320)}}return n},toString:function(){return this.getString(0,this.length)},__class__:Ua};function Pa(){this.b=[]}(n["haxe.io.BytesBuffer"]=Pa).__name__=["haxe","io","BytesBuffer"],Pa.prototype={getBytes:function(){var e=new Ua(new Uint8Array(this.b).buffer);return this.b=null,e},__class__:Pa};function La(){}(n["haxe.io.Input"]=La).__name__=["haxe","io","Input"],La.prototype={readByte:function(){throw new Wa("Not implemented")},readBytes:function(e,t,n){var i=n,r=e.b;if(t<0||n<0||t+n>e.length)throw new Wa(Ga.OutsideBounds);try{for(;0<i;)r[t]=this.readByte(),++t,--i}catch(e){if(e instanceof Wa&&(e=e.val),!Va.__instanceof(e,Ya))throw e}return n-i},set_bigEndian:function(e){return this.bigEndian=e},read:function(e){for(var t=new Ua(new ArrayBuffer(e)),n=0;0<e;){var i=this.readBytes(t,n,e);if(0==i)throw new Wa(Ga.Blocked);n+=i,e-=i}return t},readFloat:function(){return za.i32ToFloat(this.readInt32())},readDouble:function(){var e=this.readInt32(),t=this.readInt32();return this.bigEndian?za.i64ToDouble(t,e):za.i64ToDouble(e,t)},readInt8:function(){var e=this.readByte();return 128<=e?e-256:e},readInt16:function(){var e=this.readByte(),t=this.readByte(),n=this.bigEndian?t|e<<8:e|t<<8;return 0!=(32768&n)?n-65536:n},readUInt16:function(){var e=this.readByte(),t=this.readByte();return this.bigEndian?t|e<<8:e|t<<8},readInt32:function(){var e=this.readByte(),t=this.readByte(),n=this.readByte(),i=this.readByte();return this.bigEndian?i|n<<8|t<<16|e<<24:e|t<<8|n<<16|i<<24},__class__:La};function Ba(e,t,n){if(null==t&&(t=0),null==n&&(n=e.length-t),t<0||n<0||t+n>e.length)throw new Wa(Ga.OutsideBounds);this.b=e.b,this.pos=t,this.len=n,this.totlen=n}(n["haxe.io.BytesInput"]=Ba).__name__=["haxe","io","BytesInput"],Ba.__super__=La,Ba.prototype=i(La.prototype,{readByte:function(){if(0==this.len)throw new Wa(new Ya);return this.len--,this.b[this.pos++]},readBytes:function(e,t,n){if(t<0||n<0||t+n>e.length)throw new Wa(Ga.OutsideBounds);if(0==this.len&&0<n)throw new Wa(new Ya);this.len<n&&(n=this.len);for(var i=this.b,r=e.b,a=0,o=n;a<o;){var s=a++;r[t+s]=i[this.pos+s]}return this.pos+=n,this.len-=n,n},__class__:Ba});function Ha(){}(n["haxe.io.Output"]=Ha).__name__=["haxe","io","Output"],Ha.prototype={writeByte:function(e){throw new Wa("Not implemented")},writeBytes:function(e,t,n){if(t<0||n<0||t+n>e.length)throw new Wa(Ga.OutsideBounds);for(var i=e.b,r=n;0<r;)this.writeByte(i[t]),++t,--r;return n},set_bigEndian:function(e){return this.bigEndian=e},write:function(e){for(var t=e.length,n=0;0<t;){var i=this.writeBytes(e,n,t);if(0==i)throw new Wa(Ga.Blocked);n+=i,t-=i}},writeFloat:function(e){this.writeInt32(za.floatToI32(e))},writeDouble:function(e){var t=za.doubleToI64(e);this.bigEndian?(this.writeInt32(t.high),this.writeInt32(t.low)):(this.writeInt32(t.low),this.writeInt32(t.high))},writeInt8:function(e){if(e<-128||128<=e)throw new Wa(Ga.Overflow);this.writeByte(255&e)},writeInt16:function(e){if(e<-32768||32768<=e)throw new Wa(Ga.Overflow);this.writeUInt16(65535&e)},writeUInt16:function(e){if(e<0||65536<=e)throw new Wa(Ga.Overflow);this.bigEndian?(this.writeByte(e>>8),this.writeByte(255&e)):(this.writeByte(255&e),this.writeByte(e>>8))},writeInt32:function(e){this.bigEndian?(this.writeByte(e>>>24),this.writeByte(e>>16&255),this.writeByte(e>>8&255),this.writeByte(255&e)):(this.writeByte(255&e),this.writeByte(e>>8&255),this.writeByte(e>>16&255),this.writeByte(e>>>24))},__class__:Ha};function ja(){this.b=new Pa}(n["haxe.io.BytesOutput"]=ja).__name__=["haxe","io","BytesOutput"],ja.__super__=Ha,ja.prototype=i(Ha.prototype,{writeByte:function(e){this.b.b.push(e)},writeBytes:function(e,t,n){var i=this.b;if(t<0||n<0||t+n>e.length)throw new Wa(Ga.OutsideBounds);i.b;for(var r=e.b,a=t,o=t+n;a<o;){var s=a++;i.b.push(r[s])}return n},getBytes:function(){return this.b.getBytes()},__class__:ja});var Ya=function(){};(n["haxe.io.Eof"]=Ya).__name__=["haxe","io","Eof"],Ya.prototype={toString:function(){return"Eof"},__class__:Ya};var Ga=n["haxe.io.Error"]={__ename__:["haxe","io","Error"],__constructs__:["Blocked","Overflow","OutsideBounds","Custom"]};Ga.Blocked=["Blocked",0],Ga.Blocked.toString=s,(Ga.Blocked.__enum__=Ga).Overflow=["Overflow",1],Ga.Overflow.toString=s,(Ga.Overflow.__enum__=Ga).OutsideBounds=["OutsideBounds",2],Ga.OutsideBounds.toString=s,(Ga.OutsideBounds.__enum__=Ga).Custom=function(e){var t=["Custom",3,e];return t.__enum__=Ga,t.toString=s,t},Ga.__empty_constructs__=[Ga.Blocked,Ga.Overflow,Ga.OutsideBounds];var za=function(){};(n["haxe.io.FPHelper"]=za).__name__=["haxe","io","FPHelper"],za.i32ToFloat=function(e){var t=e>>>23&255,n=8388607&e;return 0==n&&0==t?0:(1-(e>>>31<<1))*(1+Math.pow(2,-23)*n)*Math.pow(2,t-127)},za.floatToI32=function(e){if(0==e)return 0;var t=e<0?-e:e,n=Math.floor(Math.log(t)/.6931471805599453);n<-127?n=-127:128<n&&(n=128);var i=Math.round(8388608*(t/Math.pow(2,n)-1));return 8388608==i&&n<128&&(i=0,++n),(e<0?-2147483648:0)|n+127<<23|i},za.i64ToDouble=function(e,t){var n=(t>>20&2047)-1023,i=4294967296*(1048575&t)+2147483648*(e>>>31)+(2147483647&e);return 0==i&&-1023==n?0:(1-(t>>>31<<1))*(1+Math.pow(2,-52)*i)*Math.pow(2,n)},za.doubleToI64=function(e){var t=za.i64tmp;if(0==e)t.low=0,t.high=0;else if(isFinite(e)){var n=e<0?-e:e,i=Math.floor(Math.log(n)/.6931471805599453),r=Math.round(4503599627370496*(n/Math.pow(2,i)-1)),a=0|r,o=r/4294967296|0;t.low=a,t.high=(e<0?-2147483648:0)|i+1023<<20|o}else 0<e?(t.low=0,t.high=2146435072):(t.low=0,t.high=-1048576);return t};var Ka=function(){};(n["haxe.rtti.Meta"]=Ka).__name__=["haxe","rtti","Meta"],Ka.getMeta=function(e){return e.__meta__},Ka.getFields=function(e){var t=Ka.getMeta(e);return null==t||null==t.fields?{}:t.fields};var Wa=function(e){Error.call(this),this.val=e,this.message=String(e),Error.captureStackTrace&&Error.captureStackTrace(this,Wa)};(n["js._Boot.HaxeError"]=Wa).__name__=["js","_Boot","HaxeError"],Wa.wrap=function(e){return e instanceof Error?e:new Wa(e)},Wa.__super__=Error,Wa.prototype=i(Error.prototype,{__class__:Wa});var Va=function(){};(n["js.Boot"]=Va).__name__=["js","Boot"],Va.getClass=function(e){if(e instanceof Array&&null==e.__enum__)return Array;var t=e.__class__;if(null!=t)return t;var n=Va.__nativeClassName(e);return null!=n?Va.__resolveNativeClass(n):null},Va.__string_rec=function(e,t){if(null==e)return"null";if(5<=t.length)return"<...>";var n=typeof e;switch("function"==n&&(e.__name__||e.__ename__)&&(n="object"),n){case"function":return"<function>";case"object":if(e instanceof Array){if(e.__enum__){if(2==e.length)return e[0];var i=e[0]+"(";t+="\t";for(var r=2,a=e.length;r<a;){var o=r++;i+=2!=o?","+Va.__string_rec(e[o],t):Va.__string_rec(e[o],t)}return i+")"}var s="[";t+="\t";for(var l=0,u=e.length;l<u;){var c=l++;s+=(0<c?",":"")+Va.__string_rec(e[c],t)}return s+="]"}var _;try{_=e.toString}catch(e){return"???"}if(null!=_&&_!=Object.toString&&"function"==typeof _){var h=e.toString();if("[object Object]"!=h)return h}var d=null,f="{\n";t+="\t";var m=null!=e.hasOwnProperty;for(var d in e)m&&!e.hasOwnProperty(d)||"prototype"!=d&&"__class__"!=d&&"__super__"!=d&&"__interfaces__"!=d&&"__properties__"!=d&&(2!=f.length&&(f+=", \n"),f+=t+d+" : "+Va.__string_rec(e[d],t));return f+="\n"+(t=t.substring(1))+"}";case"string":return e;default:return String(e)}},Va.__interfLoop=function(e,t){if(null==e)return!1;if(e==t)return!0;var n=e.__interfaces__;if(null!=n)for(var i=0,r=n.length;i<r;){var a=n[i++];if(a==t||Va.__interfLoop(a,t))return!0}return Va.__interfLoop(e.__super__,t)},Va.__instanceof=function(e,t){if(null==t)return!1;switch(t){case Array:return e instanceof Array&&null==e.__enum__;case wo:return"boolean"==typeof e;case yo:return!0;case So:return"number"==typeof e;case vo:return"number"==typeof e&&(0|e)===e;case String:return"string"==typeof e;default:if(null==e)return!1;if("function"==typeof t){if(e instanceof t)return!0;if(Va.__interfLoop(Va.getClass(e),t))return!0}else if("object"==typeof t&&Va.__isNativeObj(t)&&e instanceof t)return!0;return t==To&&null!=e.__name__||(t==Io&&null!=e.__ename__||e.__enum__==t)}},Va.__cast=function(e,t){if(Va.__instanceof(e,t))return e;throw new Wa("Cannot cast "+K.string(e)+" to "+K.string(t))},Va.__nativeClassName=function(e){var t=Va.__toStr.call(e).slice(8,-1);return"Object"==t||"Function"==t||"Math"==t||"JSON"==t?null:t},Va.__isNativeObj=function(e){return null!=Va.__nativeClassName(e)},Va.__resolveNativeClass=function(e){return t[e]};var qa=require("fs"),Qa=require("https"),Ja=require("os"),Xa=require("path"),Za=require("url"),$a=require("buffer").Buffer,eo=function(e,t){var n=new Ba(e);n.set_bigEndian(!0),this.o=this.decode(n,t)};(n["msgpack.Decoder"]=eo).__name__=["msgpack","Decoder"],eo.prototype={decode:function(e,t){try{var n=e.readByte();switch(n){case 192:return null;case 194:return!1;case 195:return!0;case 202:return e.readFloat();case 203:return e.readDouble();case 204:return e.readByte();case 205:return e.readUInt16();case 206:return e.readInt32();case 207:return new Kn(e.readInt32(),e.readInt32());case 208:return e.readInt8();case 209:return e.readInt16();case 210:return e.readInt32();case 211:return new Kn(e.readInt32(),e.readInt32());case 218:case 219:return e.read(218==n?e.readUInt16():e.readInt32()).toString();case 220:case 221:return this.readArray(e,220==n?e.readUInt16():e.readInt32(),t);case 222:case 223:return this.readMap(e,222==n?e.readUInt16():e.readInt32(),t);default:if(n<128)return n;if(n<144)return this.readMap(e,15&n,t);if(n<160)return this.readArray(e,15&n,t);if(n<192)return e.read(31&n).toString();if(223<n)return-256|n}}catch(e){if(e instanceof Wa&&(e=e.val),!Va.__instanceof(e,Ya))throw e}return null},readArray:function(e,t,n){for(var i=[],r=0,a=t;r<a;){r++;i.push(this.decode(e,n))}return i},readMap:function(e,t,n){if(n){for(var i={},r=0,a=t;r<a;){r++;var o=this.decode(e,n),s=this.decode(e,n);i[o]=s}return i}for(var l=new Ma,u=0,c=t;u<c;){u++;var _=this.decode(e,n),h=this.decode(e,n);l.set(_,h)}return l},getResult:function(){return this.o},__class__:eo};var to=function(e){this.o=new ja,this.o.set_bigEndian(!0),this.encode(e)};(n["msgpack.Encoder"]=to).__name__=["msgpack","Encoder"],to.prototype={encode:function(e){var t=ee.typeof(e);switch(t[1]){case 0:this.o.writeByte(192);break;case 1:var n=e;n<-32?n<-32768?(this.o.writeByte(210),this.o.writeInt32(n)):n<-128?(this.o.writeByte(209),this.o.writeInt16(n)):(this.o.writeByte(208),this.o.writeInt8(n)):n<128?this.o.writeByte(255&n):n<256?(this.o.writeByte(204),this.o.writeByte(n)):n<65536?(this.o.writeByte(205),this.o.writeUInt16(n)):(this.o.writeByte(206),this.o.writeInt32(n));break;case 2:var i=e,r=Math.abs(i);1401298464324817e-60<r&&r<34028234663852886e22?(this.o.writeByte(202),this.o.writeFloat(i)):(this.o.writeByte(203),this.o.writeDouble(i));break;case 3:this.o.writeByte(e?195:194);break;case 4:var a=G.fields(e),o=et.count(a);o<16?this.o.writeByte(128|o):o<65536?(this.o.writeByte(222),this.o.writeUInt16(o)):(this.o.writeByte(223),this.o.writeInt32(o));for(var s=0;s<a.length;){var l=a[s];++s;var u=Ua.ofString(l),c=u.length;c<32?this.o.writeByte(160|c):c<65536?(this.o.writeByte(218),this.o.writeUInt16(c)):(this.o.writeByte(219),this.o.writeInt32(c)),this.o.write(u),this.encode(G.field(e,l))}break;case 5:throw new Wa("Error: Function not supported");case 6:var _=t[2];switch(ee.getClassName(_)){case"Array":var h=e,d=h.length;d<16?this.o.writeByte(144|d):d<65536?(this.o.writeByte(220),this.o.writeUInt16(d)):(this.o.writeByte(221),this.o.writeInt32(d));for(var f=0;f<h.length;){var m=h[f];++f,this.encode(m)}break;case"Hash":var p=e,g=et.count(p);g<16?this.o.writeByte(128|g):g<65536?(this.o.writeByte(222),this.o.writeUInt16(g)):(this.o.writeByte(223),this.o.writeInt32(g));for(var v=p.keys();v.hasNext();){var y=v.next(),S=Ua.ofString(y),w=S.length;w<32?this.o.writeByte(160|w):w<65536?(this.o.writeByte(218),this.o.writeUInt16(w)):(this.o.writeByte(219),this.o.writeInt32(w)),this.o.write(S),this.encode(null!=No[y]?p.getReserved(y):p.h[y])}break;case"String":var T=Ua.ofString(e),I=T.length;I<32?this.o.writeByte(160|I):I<65536?(this.o.writeByte(218),this.o.writeUInt16(I)):(this.o.writeByte(219),this.o.writeInt32(I)),this.o.write(T);break;case"haxe._Int64.___Int64":var E=e;this.o.writeByte(E.high<0?211:207),this.o.writeInt32(E.high),this.o.writeInt32(E.low)}break;case 7:throw new Wa("Error: Enum not supported");case 8:throw new Wa("Error: Unknown Data Type")}},writeInt:function(e){e<-32?e<-32768?(this.o.writeByte(210),this.o.writeInt32(e)):e<-128?(this.o.writeByte(209),this.o.writeInt16(e)):(this.o.writeByte(208),this.o.writeInt8(e)):e<128?this.o.writeByte(255&e):e<256?(this.o.writeByte(204),this.o.writeByte(e)):e<65536?(this.o.writeByte(205),this.o.writeUInt16(e)):(this.o.writeByte(206),this.o.writeInt32(e))},writeInt64:function(e){this.o.writeByte(e.high<0?211:207),this.o.writeInt32(e.high),this.o.writeInt32(e.low)},writeFloat:function(e){var t=Math.abs(e);1401298464324817e-60<t&&t<34028234663852886e22?(this.o.writeByte(202),this.o.writeFloat(e)):(this.o.writeByte(203),this.o.writeDouble(e))},writeRaw:function(e){var t=e.length;t<32?this.o.writeByte(160|t):t<65536?(this.o.writeByte(218),this.o.writeUInt16(t)):(this.o.writeByte(219),this.o.writeInt32(t)),this.o.write(e)},writeArray:function(e){var t=e.length;t<16?this.o.writeByte(144|t):t<65536?(this.o.writeByte(220),this.o.writeUInt16(t)):(this.o.writeByte(221),this.o.writeInt32(t));for(var n=0;n<e.length;){var i=e[n];++n,this.encode(i)}},writeMapLength:function(e){e<16?this.o.writeByte(128|e):e<65536?(this.o.writeByte(222),this.o.writeUInt16(e)):(this.o.writeByte(223),this.o.writeInt32(e))},writeHashMap:function(e){var t=et.count(e);t<16?this.o.writeByte(128|t):t<65536?(this.o.writeByte(222),this.o.writeUInt16(t)):(this.o.writeByte(223),this.o.writeInt32(t));for(var n=e.keys();n.hasNext();){var i=n.next(),r=Ua.ofString(i),a=r.length;a<32?this.o.writeByte(160|a):a<65536?(this.o.writeByte(218),this.o.writeUInt16(a)):(this.o.writeByte(219),this.o.writeInt32(a)),this.o.write(r),this.encode(null!=No[i]?e.getReserved(i):e.h[i])}},writeObjectMap:function(e){var t=G.fields(e),n=et.count(t);n<16?this.o.writeByte(128|n):n<65536?(this.o.writeByte(222),this.o.writeUInt16(n)):(this.o.writeByte(223),this.o.writeInt32(n));for(var i=0;i<t.length;){var r=t[i];++i;var a=Ua.ofString(r),o=a.length;o<32?this.o.writeByte(160|o):o<65536?(this.o.writeByte(218),this.o.writeUInt16(o)):(this.o.writeByte(219),this.o.writeInt32(o)),this.o.write(a),this.encode(G.field(e,r))}},getBytes:function(){return this.o.getBytes()},__class__:to};function no(){}(n["msgpack.MsgPack"]=no).__name__=["msgpack","MsgPack"],no.encode=function(e){return new to(e).o.getBytes()},no.decode=function(e,t){return null==t&&(t=!0),new eo(e,t).o};function io(){}(n["puremvc.interfaces.IController"]=io).__name__=["puremvc","interfaces","IController"],io.prototype={__class__:io};var ro=function(){(ro.instance=this).commandMap=new xa,this.initializeController()};(n["puremvc.core.Controller"]=ro).__name__=["puremvc","core","Controller"],ro.__interfaces__=[io],ro.getInstance=function(){return null==ro.instance&&(ro.instance=new ro),ro.instance},ro.prototype={initializeController:function(){this.view=lo.getInstance()},executeCommand:function(e){var t=this.commandMap,n=e.getName(),i=null!=No[n]?t.getReserved(n):t.h[n];null!=i&&ee.createInstance(i,[]).execute(e)},registerCommand:function(e,t){var n=this.commandMap;(null!=No[e]?n.existsReserved(e):n.h.hasOwnProperty(e))||this.view.registerObserver(e,new ho(go(this,this.executeCommand),this));var i=this.commandMap;null!=No[e]?i.setReserved(e,t):i.h[e]=t},hasCommand:function(e){var t=this.commandMap;return null!=No[e]?t.existsReserved(e):t.h.hasOwnProperty(e)},removeCommand:function(e){this.hasCommand(e)&&(this.view.removeObserver(e,this),this.commandMap.remove(e))},__class__:ro};function ao(){}(n["puremvc.interfaces.IModel"]=ao).__name__=["puremvc","interfaces","IModel"],ao.prototype={__class__:ao};var oo=function(){(oo.instance=this).proxyMap=new xa,this.initializeModel()};(n["puremvc.core.Model"]=oo).__name__=["puremvc","core","Model"],oo.__interfaces__=[ao],oo.getInstance=function(){return null==oo.instance&&(oo.instance=new oo),oo.instance},oo.prototype={initializeModel:function(){},registerProxy:function(e){var t=this.proxyMap,n=e.getProxyName();null!=No[n]?t.setReserved(n,e):t.h[n]=e,e.onRegister()},retrieveProxy:function(e){var t=this.proxyMap;return null!=No[e]?t.getReserved(e):t.h[e]},hasProxy:function(e){var t=this.proxyMap;return null!=No[e]?t.existsReserved(e):t.h.hasOwnProperty(e)},removeProxy:function(e){var t=this.proxyMap,n=null!=No[e]?t.getReserved(e):t.h[e];return null!=n&&(this.proxyMap.remove(e),n.onRemove()),n},__class__:oo};function so(){}(n["puremvc.interfaces.IView"]=so).__name__=["puremvc","interfaces","IView"],so.prototype={__class__:so};var lo=function(){(lo.instance=this).mediatorMap=new xa,this.observerMap=new xa,this.initializeView()};(n["puremvc.core.View"]=lo).__name__=["puremvc","core","View"],lo.__interfaces__=[so],lo.getInstance=function(){return null==lo.instance&&(lo.instance=new lo),lo.instance},lo.prototype={initializeView:function(){},registerObserver:function(e,t){var n=this.observerMap;if(!(null!=No[e]?n.existsReserved(e):n.h.hasOwnProperty(e))){var i=this.observerMap,r=new $;null!=No[e]?i.setReserved(e,r):i.h[e]=r}var a=this.observerMap;(null!=No[e]?a.getReserved(e):a.h[e]).add(t)},notifyObservers:function(e){var t=this.observerMap,n=e.getName();if(null!=No[n]?t.existsReserved(n):t.h.hasOwnProperty(n)){for(var i=this.observerMap,r=e.getName(),a=null!=No[r]?i.getReserved(r):i.h[r],o=new $,s=new c(a.h);s.hasNext();){var l=s.next();o.add(l)}for(var u=new c(o.h);u.hasNext();){u.next().notifyObserver(e)}}},removeObserver:function(e,t){for(var n=this.observerMap,i=null!=No[e]?n.getReserved(e):n.h[e],r=i.h;null!=r;){var a=r.item;r=r.next;var o=a;if(1==o.compareNotifyContext(t)){i.remove(o);break}}i.isEmpty()&&this.observerMap.remove(e)},registerMediator:function(e){var t=this.mediatorMap,n=e.getMediatorName();if(null!=No[n]?!t.existsReserved(n):!t.h.hasOwnProperty(n)){var i=this.mediatorMap,r=e.getMediatorName();null!=No[r]?i.setReserved(r,e):i.h[r]=e;var a=e.listNotificationInterests();if(0<a.length)for(var o=new ho(go(e,e.handleNotification),e),s=0,l=a.length;s<l;){var u=s++;this.registerObserver(a[u],o)}e.onRegister()}},retrieveMediator:function(e){var t=this.mediatorMap;return null!=No[e]?t.getReserved(e):t.h[e]},removeMediator:function(e){var t=this.mediatorMap,n=null!=No[e]?t.getReserved(e):t.h[e];if(null!=n){for(var i=n.listNotificationInterests(),r=0,a=i.length;r<a;){var o=r++;this.removeObserver(i[o],n)}this.mediatorMap.remove(e),n.onRemove()}return n},hasMediator:function(e){var t=this.mediatorMap;return null!=No[e]?t.existsReserved(e):t.h.hasOwnProperty(e)},__class__:lo};function uo(){}(n["puremvc.interfaces.INotification"]=uo).__name__=["puremvc","interfaces","INotification"],uo.prototype={__class__:uo};function co(){}(n["puremvc.interfaces.IObserver"]=co).__name__=["puremvc","interfaces","IObserver"],co.prototype={__class__:co};var _o=function(e,t,n){this.name=e,null!=t&&(this.body=t),null!=n&&(this.type=n)};(n["puremvc.patterns.observer.Notification"]=_o).__name__=["puremvc","patterns","observer","Notification"],_o.__interfaces__=[uo],_o.prototype={getName:function(){return this.name},setBody:function(e){this.body=e},getBody:function(){return this.body},setType:function(e){this.type=e},getType:function(){return this.type},toString:function(){var e="Notification Name: "+this.getName();return e+="\nBody:"+(null==this.body?"null":this.body.toString()),e+="\nType:"+(null==this.type?"null":this.type)},__class__:_o};var ho=function(e,t){this.setNotifyMethod(e),this.setNotifyContext(t)};function fo(e){return e instanceof Array?function(){return $e.iter(e)}:"function"==typeof e.iterator?go(e,e.iterator):e.iterator}(n["puremvc.patterns.observer.Observer"]=ho).__name__=["puremvc","patterns","observer","Observer"],ho.__interfaces__=[co],ho.prototype={setNotifyMethod:function(e){this.notify=e},setNotifyContext:function(e){this.context=e},getNotifyMethod:function(){return this.notify},getNotifyContext:function(){return this.context},notifyObserver:function(e){this.getNotifyMethod()(e)},compareNotifyContext:function(e){return e==this.context},__class__:ho};var mo,po=0;function go(e,t){return null==t?null:(null==t.__id__&&(t.__id__=po++),null==e.hx__closures__?e.hx__closures__={}:n=e.hx__closures__[t.__id__],null==n&&((n=function(){return n.method.apply(n.scope,arguments)}).scope=e,n.method=t,e.hx__closures__[t.__id__]=n),n);var n}n.Math=Math,String.prototype.__class__=n.String=String,String.__name__=["String"],n.Array=Array,Array.__name__=["Array"],Date.prototype.__class__=n.Date=Date,Date.__name__=["Date"];var vo=n.Int={__name__:["Int"]},yo=n.Dynamic={__name__:["Dynamic"]},So=n.Float=Number;So.__name__=["Float"];var wo=n.Bool=Boolean;wo.__ename__=["Bool"];var To=n.Class={__name__:["Class"]},Io={},Eo={},No={};p.APP_STATE_CHANGED="app_state_changed",p.ACCESS_TOKEN_CHANGED="access_token_changed",p.CURRENT_USER_CHANGED="current_user_changed",p.CONFIGURATION_CHANGED="configuration_changed",p.DOMAIN_SELECTION_CHANGED="domain_selection_changed",p.TALK_SELECTION_CHANGED="talk_selection_changed",p.TALK_LIST_SCROLL_TO_TALK_TOP_NEEDED="talk_list_scroll_to_talk_top_needed",p.USER_SELECTION_NEEDED="user_selection_needed",p.USER_SELECTION_CHANGED="user_selection_changed",p.FRIEND_SELECTION_NEEDED="friend_selection_needed",p.COMMON_STAMP_SET_LOADED="common_stamp_set_loaded",p.STAMP_SELECTION_STARTED="stamp_selection_started",p.STAMP_SELECTION_ENDED="stamp_selection_ended",p.STAMP_SELECTION_CHANGED="stamp_selection_changed",p.ACTION_SELECTION_CHANGED="action_selection_changed",p.CURRENT_PAGE_CHANGED="current_page_changed",p.CURRENT_PAGE_REASSIGNED="current_page_reassgined",p.FILEINFO_SELECTION_CHANGED="fileinfo_selection_changed",p.NOTE_FILEINFO_SELECTION_CHANGED="note_fileinfo_selection_changed",p.MESSAGE_FILEINFO_SELECTION_CHANGED="message_fileinfo_selection_changed",p.STAGED_FILEINFO_SELECTION_CHANGED="staged_fileinfo_selection_changed",p.STAGED_FILEINFOS_ADDED="staged_fileinfos_added",p.STAGED_FILEINFOS_MOVED="staged_fileinfos_moved",p.CLOSE_FILEPREVIEW_MODAL="close_filepreview_modal",p.ERROR_OCCURRED="error_occurred",p.UNREAD_COUNT_CHANGED="brand_badge_changed",p.SEND_FORM_TOP_CHANGED="send_form_top_changed",p.SOLUTIONS_LOADED="solutions_loaded",p.RIGHT_PANE_OPENED="right_pane_opened",p.RIGHT_PANE_CLOSED="right_pane_closed",p.PASSWORD_EXPIRATION_OVERED="password_expiration_overed",p.PASSWORD_EXPIRATION_WARNED="password_expiration_warned",p.PHOTO_EDITOR_SAVED="photo_editor_saved",p.ICON_EDITOR_SAVED="icon_editor_saved",p.MC_AUTHENTICATED_USER_RECEIVED="mc_authenticated_user_received",p.KEYWORD_WATCHING_UPDATED="keyword_watching_updated",p.KEYWORD_DETECTION_UPDATED="keyword_detaction_updated",p.SEND_BY_ENTER_CHANGED="send_by_enter_changed",p.DEPARTMENT_SELECTION_CHANGED_FOR_MEMBERS_PAGE="department_selection_changed_for_members_page",p.PRESENCES_UPDATED="presences_updated",p.NOTEINFO_SELECTION_CHANGED="noteinfo_selection_changed",p.START_NOTE_EDITING="start_note_editing",p.OPEN_EXISTING_PAIR_TALK_COMPLETED="open_existing_pair_talk_completed",p.FIRST_ROUTING_WILL_START="first_routing_will_start",p.DATA_RECOVERING="data_recovering",p.DATA_RECOVERED="data_recovered",p.NOTIFY_UPDATE_USER="notify_update_user",p.NOTIFY_ADD_FRIEND="notify_add_friend",p.NOTIFY_ADD_ACQUAINTANCE="notify_add_acquaintance",p.NOTIFY_ADD_ACQUAINTANCES="notify_add_acquaintances",p.NOTIFY_DELETE_FRIEND="notify_delete_friend",p.NOTIFY_DELETE_ACQUAINTANCE="notify_delete_acquaintance",p.NOTIFY_DELETE_ACQUAINTANCES="notify_delete_acquaintances",p.NOTIFY_UPDATE_DOMAIN_USERS="notify_update_domain_users",p.GET_DOMAIN_USERS_RESPONSED="get_domain_users_responsed",p.GET_USERS_RESPONSED="get_users_responsed",p.GET_PROFILE_RESPONSED="get_profile_responsed",p.GET_PROFILE_ERRORED="get_profile_errored",p.UPDATE_USER_RESPONSED="update_user_responsed",p.UPDATE_USER_ERRORED="update_user_errored",p.UPDATE_PROFILE_RESPONSED="update_profile_responsed",p.UPDATE_PROFILE_ERRORED="update_profile_errored",p.NOTIFY_UPDATE_DEPARTMENT_TREE="notify_update_department_tree",p.NOTIFY_UPDATE_DEPARTMENT_USERS="notify_update_department_users",p.GET_DEPARTMENT_TREE_RESPONSED="get_department_tree_responsed",p.GET_DEPARTMENT_TREE_CANCELED="get_department_tree_canceled",p.GET_DEPARTMENT_USERS_RESPONSED="get_department_users_responsed",p.GET_DEPARTMENT_USERS_CANCELED="get_department_users_canceled",p.GET_DEPARTMENT_USER_COUNT_RESPONSED="get_department_user_count_responsed",p.GET_ME_RESPONSED="get_me_responsed",p.DEPARTMENT_USER_COUNT_CLEARED="department_user_count_cleared",p.DEPARTMENT_USER_IDS_PREPARED="department_user_ids_prepared",p.NOTIFY_ADD_DOMAIN_INVITE="notify_add_domain_invite",p.NOTIFY_ACCEPT_DOMAIN_INVITE="notify_accept_domain_invite",p.NOTIFY_DELETE_DOMAIN_INVITE="notify_delete_domain_invite",p.NOTIFY_JOIN_DOMAIN="notify_join_domain",p.NOTIFY_UPDATE_DOMAIN="notify_update_domain",p.NOTIFY_LEAVE_DOMAIN="notify_leave_domain",p.NOTIFY_ADD_DOMAIN_MEMBERS="notify_add_domain_members",p.NOTIFY_CREATE_PAIR_TALK="notify_create_pair_talk",p.CREATE_PAIR_TALK_COMPLETE="create_pair_talk_complete",p.CREATE_PAIR_TALK_FAIL="create_pair_talk_fail",p.NOTIFY_CREATE_GROUP_TALK="notify_create_group_talk",p.CREATE_GROUP_TALK_COMPLETE="create_group_talk_complete",p.CREATE_GROUP_TALK_FAIL="create_group_talk_fail",p.NOTIFY_UPDATE_GROUP_TALK="notify_update_group_talk",p.NOTIFY_UPDATE_GROUP_TALK_ERRORED="notify_update_group_talk_ERRORED",p.NOTIFY_ADD_TALKERS="notify_add_talkers",p.NOTIFY_ADD_TALKERS_INCLUDING_ME="notify_add_talkers_including_me",p.NOTIFY_DELETE_TALKER="notify_delete_talker",p.NOTIFY_DELETE_TALK="notify_delete_talk",p.NOTIFY_UPDATE_READ_STATUSES="notify_update_read_statuses",p.NOTIFY_UPDATE_TALK_STATUS="notify_update_talk_status",p.NOTIFY_UPDATE_LOCAL_TALK_STATUS="notify_update_local_talk_status",p.NOTIFY_ADD_FAVORITE_TALK="notify_add_favorite_talk",p.NOTIFY_DELETE_FAVORITE_TALK="notify_delete_favorite_talk",p.NOTIFY_DISABLE_PUSH_NOTIFICATION="notify_disable_push_notification",p.NOTIFY_ENABLE_PUSH_NOTIFICATION="notify_enable_push_notification",p.ADD_TALKERS_SUCCEEDED="add_talkers_succeeded",p.ADD_TALKERS_FAILED="add_talkers_failed",p.NOTIFY_CREATE_MESSAGE="notify_create_message",p.NOTIFY_DELETE_MESSAGE="notify_delete_message",p.NOTIFY_GET_MESSAGES="notify_get_messages",p.NOTIFY_GET_MESSAGE_READ_STATUS="notify_get_message_status",p.CREATE_MESSAGE_START="create_message_start",p.CREATE_MESSAGE_COMPLETE="create_message_complete",p.CREATE_MESSAGE_FAIL="create_message_fail",p.ADD_FAVORITE_MESSAGE_COMPLETED="add_favorite_message_completed",p.DELETE_FAVORITE_MESSAGE_COMPLETED="delete_favorite_message_completed",p.GET_FAVORITE_MESSAGES_COMPLETED="get_favorite_messages_completed",p.NOTIFY_ADD_FAVORITE_MESSAGE="notify_add_favorite_message",p.NOTIFY_DELETE_FAVORITE_MESSAGE="notify_delete_favorite_message",p.NOTIFY_CREATE_ANNOUNCEMENT="notify_create_announcement",p.NOTIFY_DELETE_ANNOUNCEMENT="notify_delete_announcement",p.NOTIFY_UPDATE_ANNOUNCEMENT_STATUS="notify_update_announcement_status",p.NOTIFY_GET_ANNOUNCEMENTS="notify_get_announcements",p.CREATE_ANNOUNCEMENT_START="create_announcement_start",p.CREATE_ANNOUNCEMENT_COMPLETE="create_announcement_complete",p.CREATE_ANNOUNCEMENT_FAIL="create_announcement_fail",p.NOTIFY_UPDATE_QUESTION="notify_update_question",p.NOTIFY_GET_QUESTIONS="get_questions_responsed",p.NOTIFY_CREATE_ATTACHMENT="notify_create_attachment",p.NOTIFY_DELETE_ATTACHMENT="notify_delete_attachment",p.GET_FILE_RESPONSED="get_file_responsed",p.GET_NOTE_STATUSES_LOADED="get_note_statuses_loaded",p.GET_NOTE_LOADED="get_note_loaded",p.GET_NOTE_FAILED_BY_NOTE_NOT_FOUND="get_note_failed_by_note_not_found",p.CREATE_NOTE_COMPLETED="create_note_completed",p.CREATE_NOTE_FAILED="create_note_failed",p.UPDATE_NOTE_LOCAL_EDIT="update_note_local_edit",p.CLEAR_NOTE_LOCAL_EDIT="clear_note_local_edit",p.UPDATE_NOTE_SETTING_COMPLETED="update_note_setting_completed",p.UPDATE_NOTE_SETTING_FAILED_BY_NOT_FOUND="update_note_setting_failed_by_not_found",p.UPDATE_NOTE_SETTING_FAILED_BY_CONFLICT="update_note_setting_failed_by_conflict",p.UPDATE_NOTE_SETTING_FAILED_BY_EDITING="update_note_setting_failed_by_editing",p.UPDATE_NOTE_COMPLETED="update_note_completed",p.DELETE_NOTE_COMPLETED="delete_note_completed",p.NOTIFY_CREATE_NOTE="notify_create_note",p.NOTIFY_UPDATE_NOTE_PARTIALLY="notify_update_note_partially",p.NOTIFY_DELETE_NOTE="notify_delete_note",p.NOTIFY_UPDATE_NOTE_FOR_SETTING="notify_update_note_for_setting",p.NOTIFY_UPDATE_NOTE_FOR_SUMMARY="notify_update_note_for_revision",p.CREATE_NOTE_BUTTON_CLICKED="create_note_button_clicked",p.NOTIFY_LOCK_NOTE="notify_lock_note",p.NOTIFY_UNLOCK_NOTE="notify_unlock_note",p.NOTIFY_SEARCH_MESSAGES="notify_search_messages",p.NOTIFY_SEARCH_ATTACHMENTS="notify_search_attachments",p.NOTIFY_SEARCH_MESSAGES_FAIL="notify_search_messages_fail",p.NOTIFY_SEARCH_ATTACHMENTS_FAIL="notify_search_attachments_fail",p.NOTIFY_SEARCH_PREPARE="notify_search_prepare",p.NOTIFY_SEARCH_CLEAR="notify_search_clear",p.NOTIFY_FILTER_BOX_TEXT_CHANGED="notify_filter_box_text_changed",p.NOTIFY_SEARCH_BOX_POPUP="notify_search_box_popup",p.NOTIFY_ADD_ACCOUNT_CONTROL_REQUEST="notify_add_account_control_request",p.NOTIFY_DELETE_ACCOUNT_CONTROL_REQUEST="notify_delete_account_control_request",p.NOTIFY_JOIN_ACCOUNT_CONTROL_GROUP="notify_join_account_control_group",p.NOTIFY_UPDATE_ACCOUNT_CONTROL_GROUP_PARTIALLY="notify_update_account_control_group_partially",p.NOTIFY_LEAVE_ACCOUNT_CONTROL_GROUP="notify_leave_account_control_group",p.PREPARE_CONFERENCE_FROM_MESSAGE="prepare_conference_from_message",p.JOIN_CONFERENCE_RESPONSED="join_conference_responsed",p.JOIN_CONFERENCE_CANCELED="join_conference_canceled",p.GET_CONFERENCE_PARTICIPANTS_RESPONSED="get_conference_participants_responsed",p.NOTIFY_OPEN_CONFERENCE="notify_open_conference",p.NOTIFY_CLOSE_CONFERENCE="notify_close_conference",p.NOTIFY_CONFERENCE_PARTICIPANT_JOIN="notify_conference_participant_join",p.NOTIFY_CONFERENCE_PARTICIPANT_LIMIT="notify_conference_participant_limit",p.NOTIFY_CONFERENCE_PARTICIPANT_REJECT="notify_conference_participant_reject",p.NOTIFY_ALL_TALK_MEMBERS_REJECTED_CONFERENCE="notify_all_talk_members_rejected_conference",p.NOTIFY_UPDATE_DOMAIN_STAMP_SETTING="notify_update_domain_stampsetting",p.NOTIFY_UPDATE_STAMPSET="notify_update_stampset",p.NOTIFY_DELETE_STAMPSET="notify_delete_stampset",p.NOTIFY_FLOW_NOTIFICATION_BADGE="notify_flow_notification_badge",p.GET_FLOW_NOTIFICATION_BADGES_COMPLETED="get_flow_notification_badges_completed",p.GET_FLOW_NOTIFICATION_BADGES_FAILED="get_flow_notification_badges_failed",p.START_NOTIFICATION_FAILED="start_notification_failed",M.ANNOUNCEMENTS_KEY="-1",B.__meta__={fields:{api:{inject:null}}},B.NAME="AccountControlRequest",j.__meta__={fields:{api:{inject:null},conferenceStore:{inject:null}}},j.NAME="Conference",z.__meta__={fields:{api:{inject:null}}},z.NAME="Device",Q.__meta__={fields:{api:{inject:null}}},Q.NAME="Domain",X.__meta__={fields:{api:{inject:null},dataStore:{inject:null},fileService:{inject:null}}},X.NAME="File",te.__meta__={fields:{api:{inject:null},stampsStore:{inject:null}}},te.NAME="LoadStampset",te.STAMP_VERSION=1,te.TAB_URL="./json/app_ja.json?version=1",te.TAB_PANE_URL="./json/illust_category_ja.json?version=1",re.__meta__={fields:{api:{inject:null}}},re.NAME="ManageFriends",oe.__meta__={fields:{api:{inject:null}}},oe.NAME="Message",le.__meta__={fields:{api:{inject:null},dataStore:{inject:null},fileService:{inject:null},fileInfoStore:{inject:null}}},le.NAME="Note",ce.__meta__={fields:{api:{inject:null},keywordWatcher:{inject:null},readStatusUpdater:{inject:null}}},ce.NAME="Read",he.__meta__={fields:{api:{inject:null}}},he.NAME="ReloadData",fe.__meta__={fields:{api:{inject:null},searchService:{inject:null}}},fe.NAME="Search",pe.__meta__={fields:{dataStore:{inject:null},settings:{inject:null}}},pe.NAME="SelectTalk",ve.__meta__={fields:{api:{inject:null}}},ve.NAME="Send",ye.__meta__={fields:{accessTokenResolver:{inject:null},session:{inject:null}}},ye.NAME="SignIn",Se.__meta__={fields:{api:{inject:null},settings:{inject:null},dataStore:{inject:null}}},Se.NAME="SignOut",we.__meta__={fields:{api:{inject:null},dataStore:{inject:null}}},we.NAME="Talk",Ie.__meta__={fields:{api:{inject:null},dataStore:{inject:null}}},Ie.NAME="UpdateProfile",Ee.__meta__={fields:{api:{inject:null}}},Ee.NAME="UpdateUser",Ne.__meta__={fields:{userPresences:{inject:null},api:{inject:null},settings:{inject:null}}},Ne.NAME="UpdateUserPresences",Ne.MAX_USERS_PER_API=100,Ae.__meta__={fields:{routing:{inject:null}}},Ae.NAME="Url",xe.TalkAutoScrollDelay=1,xe.TalkAutoScrollImmediately=2,xe.TalkAutoScrollNone=3,xe.NAME="browser_settings",Pe.MAX_SIZE=72,ut.INCOMING_TIME=6e4,Le.DEFAULT_PRESENCE_EXPIRATION=3e5,He.DEFAULT_TTL=3600,He.DEFAULT_MAX_PARTICIPANTS=8,bt.TIMESTAMP_SHIFT=22,Ft.MAX_READ_USER_IDS_COUNT=16,sn.QUERY_DATE_TODAY="t",sn.QUERY_DATE_YESTERDAY="-1d",sn.QUERY_DATE_THREE_DAYS_BEFORE="-3d",Sn.HISTORY_TAB_NAME="stamp-history",Wn.SIXTY_MINUTES=new Kn(0,36e5),Wn.FIFTEEN_MINUTES=new Kn(0,9e5),Ti.PREFIX="note-",Ti.nextDummyId=new Kn(-1,-1),Ai.CONTINUE_MARGIN_RATE=.1,Pi.CHEKBOX_UNCHECKED="- [ ] ",Pi.CHEKBOX_CHECKED="- [x] ",Bi.TU_REG=new y("ッ([BCDFGHIJKLMNOPQRSTUVWYZ])","gm"),Bi.XTU_REG=new y("ッ","gm"),Gi.EMERGENCY=0,Gi.ALERT=1,Gi.CRITICAL=2,Gi.ERROR=3,Gi.WARNING=4,Gi.NOTICE=5,Gi.INFO=6,Gi.DEBUG=7,Gi.level=Gi.getLogLevel(process.env.HUBOT_LOG_LEVEL),Gi._d=7<=Gi.level&&null!=console?console.log.bind(console):Gi._nop,Gi._i=6<=Gi.level&&null!=console?console.info.bind(console):Gi._nop,Gi._w=4<=Gi.level&&null!=console?console.warn.bind(console):Gi._nop,Gi._e=3<=Gi.level&&null!=console?console.error.bind(console):Gi._nop,Qi.HIRAGANA_SMALL_A=12353,Qi.HIRAGANA_NN=12435,Qi.KATAKANA_SMALL_A=12449,nr.NAME="accessTokenResolver",ir.NAME="Proxy",rr.__meta__={fields:{settings:{inject:null},accountLoader:{inject:null},api:{inject:null}}},or.NAME="accountLoader",lr.__meta__={fields:{api:{inject:null},dataStore:{inject:null},settings:{inject:null},fileInfoStore:{inject:null},departmentStore:{inject:null},messageStore:{inject:null},dataFactory:{inject:null},keywordWatcher:{inject:null},conferenceStore:{inject:null},stampsStore:{inject:null}}},lr.NAME="broadcast",ur.__meta__={fields:{apiCaller:{inject:null},apiNote:{inject:null},settings:{inject:null},dataStore:{inject:null},dataFactory:{inject:null},fileService:{inject:null},searchService:{inject:null},fileInfoStore:{inject:null},messageStore:{inject:null},departmentStore:{inject:null},conferenceStore:{inject:null},lastUsedAtUpdater:{inject:null},stampsStore:{inject:null}}},ur.NAME="api",ur.API_VERSION="1.114",ur.UPDATE_VERSION="1.114_0",ur.ACTIONS_COUNT_PER_API=20,cr.__meta__={fields:{rpc:{inject:null}}},cr.NAME="apiCaller",cr.DELAY_FOR_DB_REPLICATION=500,cr.DELAY_FOR_DB_REPLICATION_FOR_RETRY=1e3,cr.API_TRY_COUNT=3,_r.__meta__={fields:{apiCaller:{inject:null},dataStore:{inject:null},settings:{inject:null}}},_r.NAME="apiNote",hr.NAME="appState",dr.__meta__={fields:{dataStore:{inject:null},messageStore:{inject:null},settings:{inject:null}}},dr.NAME="conferenceStore",fr.__meta__={fields:{dataStore:{inject:null},fileInfoStore:{inject:null},messageStore:{inject:null},solutionsStore:{inject:null},conferenceStore:{inject:null}}},fr.NAME="dataFactory",mr.__meta__={fields:{fileInfoStore:{inject:null}}},mr.NAME="dataStore",mr.TYPE_FRIEND=0,mr.TYPE_ACQUAINSTANCE=1,mr.TYPE_NONE=2,pr.__meta__={fields:{dataStore:{inject:null}}},pr.NAME="departmentStore",gr.__meta__={fields:{settings:{inject:null},dataStore:{inject:null}}},gr.NAME="features",vr.NAME="fileInfoStore",Sr.NAME="fileService",wr.__meta__={fields:{settings:{inject:null}}},Tr.__meta__={fields:{settings:{inject:null},features:{inject:null},dataStore:{inject:null}}},Tr.NAME="keywordWatcher",Tr.TALK_KEY_PREFIX="talk_",Tr.ANNOUNCEMENT_KEY_PREFIX="announcement_",Ir.TEMP_HALF_SPACE="&SPACE",Ir.TEMP_FULL_SPACE="&FULL_PITCH_SPACE",br.__meta__={fields:{settings:{inject:null}}},br.NAME="lastUsedAtUpdater",br.UPDATE_LAST_USED_AT_INTERVAL=6e5,Dr.__meta__={fields:{settings:{inject:null},dataStore:{inject:null}}},Dr.NAME="limitations",kr.NAME="messageStore",Cr.__meta__={fields:{broadcast:{inject:null},lastUsedAtUpdater:{inject:null}}},Cr.NAME="rpc",Cr.lastMsgId=0,Or.PING_INTERVAL_ON_CONNECTED=45e3,xr.__meta__={fields:{dataStore:{inject:null},api:{inject:null}}},xr.NAME="readStatusUpdater",Ur.__meta__={fields:{settings:{inject:null},dataStore:{inject:null}}},Ur.NAME="routing",Br.__meta__={fields:{settings:{inject:null}}},Br.NAME="searchService",Br.LOAD_SIZE=20,Br.DUMMY_VALUE_FOR_SET=1,Hr.__meta__={fields:{settings:{inject:null},dataStore:{inject:null},dataFactory:{inject:null},api:{inject:null}}},Hr.NAME="session",jr.NAME="settings",jr.KEY_ACCESS_TOKEN="access_token",jr.KEY_ACCESS_TOKEN_WITHOUT_MANAGEMENT_CONSOLE="access_token_without_management_console",jr.KEY_SELECTED_DOMAIN_ID_H="selected_domain_id_h",jr.KEY_SELECTED_DOMAIN_ID_L="selected_domain_id_l",jr.COOKIE_KEY_SEND_BY_ENTER="send-by-enter",jr.COOKIE_EXPIRES_SEND_BY_ENTER=31536e3,jr.KEY_SELECTED_STAMP_TAB_ID="selected_stamp_tab_id",jr.KEY_INPUT_TEXT="input_text",jr.KEY_COPY_PROFILE_TO_ALL_DOMAINS="copy_profile_to_all_domains",jr.KEY_SELECTED_DEPARTMENT_IDS="selected_department_ids",jr.KEY_SEARCH_HISTORIES="search_histories",jr.KEY_RIGHT_PANEL_OPENED="right_panel_opened",jr.KEY_MULTI_VIEW_MODE="multi_view_mode",jr.KEY_PASSWORD_WARNING_SKIP_UNTIL="password_warning_skip_until",jr.KEY_LAST_USED_EXPIRED_AT="last_used_expired_at",jr.KEY_IDFV="idfv",Yr.__meta__={fields:{settings:{inject:null}}},Yr.NAME="solutionsStore",Gr.NAME="stampsStore",zr.__meta__={fields:{dataStore:{inject:null},conferenceStore:{inject:null}}},zr.NAME="talksService",Kr.__meta__={fields:{settings:{inject:null},dataStore:{inject:null}}},Kr.NAME="ThumbnailExpansion",Wr.__meta__={fields:{dataStore:{inject:null}}},Wr.NAME="userPresences",sa.NAME="Mediator",la.__meta__={fields:{dataStore:{inject:null},api:{inject:null},hubotObject:{inject:null},messageEvent:{inject:null},sendQueue:{inject:null}}},la.NAME="commandline",la.DATA_SAVE_SPAN=5e3,ua.__meta__={fields:{dataStore:{inject:null}}},ua.NAME="hubotObject",ca.__meta__={fields:{dataStore:{inject:null},hubotObject:{inject:null}}},ca.NAME="messageEvent",_a.minWaitMinute=1,_a.maxWaitMinute=1440,_a.SEND_EVENT_NAME="send",ha.__meta__={fields:{messageEvent:{inject:null}}},ha.NAME="sendQueue",ha.MIN_SEND_SPAN_MESSAGE=550,ha.MIN_SEND_SPAN_ANNOUNCE=5050,ha.MAX_TEXT_LENGTH=1024,ha.MAX_FIELD_COUNT=9,ha.MAX_FIELD_LENGTH=64,ma.INVALID_PARAMETER="INVALID_PARAMETER",ma.FORBIDDEN="FORBIDDEN",ma.NOT_FOUND="NOT_FOUND",ma.LOCKED_BY_ANOTHER_USER="LOCKED_BY_ANOTHER_USER",ma.CONFLICT="CONFLICT",ma.TOO_MANY_REQUESTS="TOO_MANY_REQUESTS",ma.UNKNOWN="UNKNOWN",Sa._mul=null!=Math.imul?Math.imul:function(e,t){return e*(65535&t)+(e*(t>>>16)<<16|0)|0},Ia.USE_CACHE=!1,Ia.USE_ENUM_INDEX=!1,Ia.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%:",Aa.DEFAULT_RESOLVER=new Na,Aa.BASE64="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%:",Ma.count=0,za.i64tmp=new Kn(0,0),Va.__toStr={}.toString,to.FLOAT_SINGLE_MIN=1401298464324817e-60,to.FLOAT_SINGLE_MAX=34028234663852886e22,to.FLOAT_DOUBLE_MIN=5e-324,to.FLOAT_DOUBLE_MAX=17976931348623157e292,r.main()}("undefined"!=typeof exports?exports:"undefined"!=typeof window?window:"undefined"!=typeof self?self:this,"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this);
pages/api/menu.js
AndriusBil/material-ui
// @flow import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './menu.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
node_modules/react-native/Libraries/Renderer/src/renderers/native/ReactNativeTagHandles.js
aksharora/ReactNativeDemoBasic
/** * Copyright (c) 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 ReactNativeTagHandles * @flow */ 'use strict'; var invariant = require('fbjs/lib/invariant'); /** * Keeps track of allocating and associating native "tags" which are numeric, * unique view IDs. All the native tags are negative numbers, to avoid * collisions, but in the JS we keep track of them as positive integers to store * them effectively in Arrays. So we must refer to them as "inverses" of the * native tags (that are * normally negative). * * It *must* be the case that every `rootNodeID` always maps to the exact same * `tag` forever. The easiest way to accomplish this is to never delete * anything from this table. * Why: Because `dangerouslyReplaceNodeWithMarkupByID` relies on being able to * unmount a component with a `rootNodeID`, then mount a new one in its place, */ var INITIAL_TAG_COUNT = 1; var ReactNativeTagHandles = { tagsStartAt: INITIAL_TAG_COUNT, tagCount: INITIAL_TAG_COUNT, allocateTag: function(): number { // Skip over root IDs as those are reserved for native while (this.reactTagIsNativeTopRootID(ReactNativeTagHandles.tagCount)) { ReactNativeTagHandles.tagCount++; } var tag = ReactNativeTagHandles.tagCount; ReactNativeTagHandles.tagCount++; return tag; }, assertRootTag: function(tag: number): void { invariant( this.reactTagIsNativeTopRootID(tag), 'Expect a native root tag, instead got %s', tag ); }, reactTagIsNativeTopRootID: function(reactTag: number): boolean { // We reserve all tags that are 1 mod 10 for native root views return reactTag % 10 === 1; }, }; module.exports = ReactNativeTagHandles;
client/pages/admin/exportResults.js
limabeans/ccm
import React from 'react'; import ReactDOM from 'react-dom'; const ExportResultsView = React.createClass({ getInitialState() { return { wcaResults: null, exportProblems: [] }; }, wcaResultsJson: function() { let template = Template.instance(); let wcaResults = template.wcaResultsReact.get(); if(!wcaResults) { return ''; } let wcaResultsJson = JSON.stringify(wcaResults, undefined, 2); return wcaResultsJson; }, generateWcaResults() { Meteor.call('exportWcaResults', this.props.competitionId, this.props.competitionUrlId, (err, result) => { if(err) { console.error("Meteor.call() error: " + err); this.setState({ wcaResults: null, exportProblems: [err] }); } else { this.setState({ wcaResults: result.wcaResults, exportProblems: result.exportProblems }); } }); }, render() { let {wcaResults, exportProblems } = this.state; return ( <div className="container"> <h4>Export Results</h4> <hr/> <button id="buttonGenerateWcaResults" className="btn btn-default" onClick={this.generateWcaResults}>Generate WCA JSON</button> <div> <ul className="list-group problemsList"> {exportProblems.map((problem, index) => <li key={index} className="list-group-item {{#if warning}}list-group-item-warning{{/if}} {{#if error}}list-group-item-danger{{/if}}"> {problem.message} {problem.fixUrl ? <a href="{problem.fixUrl}" className="pull-right"> <span className="glyphicon glyphicon-wrench"></span> </a> : null} </li> )} </ul> <pre className="resultsJson">{JSON.stringify(wcaResults)}</pre> </div> </div> ); } }); Template.exportResults.rendered = function() { let template = this; template.autorun(() => { ReactDOM.render( <ExportResultsView competitionId={template.data.competitionId} competitionUrlId={template.data.competitionUrlId} userId={Meteor.userId()}/>, template.$(".reactRenderArea")[0] ); }); };
ajax/libs/forerunnerdb/1.3.515/fdb-all.min.js
froala/cdnjs
!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/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/Grid"),a("../lib/NodeApiClient"),a("../lib/BinaryLog");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/BinaryLog":4,"../lib/CollectionGroup":7,"../lib/Document":11,"../lib/Grid":12,"../lib/Highchart":13,"../lib/NodeApiClient":28,"../lib/Overview":31,"../lib/Persist":33,"../lib/View":40,"./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":8,"../lib/Shim.IE8":39}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){var b;this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0;for(b in a)a.hasOwnProperty(b)&&this._keyArr.push({key:b,dir:a[b]})};d.addModule("ActiveBucket",e),d.mixin(e.prototype,"Mixin.Sorting"),d.synthesize(e.prototype,"primaryKey"),e.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},e.prototype._sortFunc=function(a,b,c,d){var e,f,g,h=c.split(".:."),i=d.split(".:."),j=a._keyArr,k=j.length;for(e=0;k>e;e++)if(f=j[e],g=typeof b[f.key],"number"===g&&(h[e]=Number(h[e]),i[e]=Number(i[e])),h[e]!==i[e]){if(1===f.dir)return a.sortAsc(h[e],i[e]);if(-1===f.dir)return a.sortDesc(h[e],i[e])}},e.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},e.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},e.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},e.prototype.documentKey=function(a){var b,c,d="",e=this._keyArr,f=e.length;for(b=0;f>b;b++)c=e[b],d&&(d+=".:."),d+=a[c.key];return d+=".:."+a[this._primaryKey]},e.prototype.count=function(){return this._count},d.finishModule("ActiveBucket"),b.exports=e},{"./Shared":38}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared"),j=function(){this.init.apply(this,arguments)},j.prototype.init=function(a){var b=this;b._logCounter=0,b._parent=a,b.size(1e3)},d.addModule("BinaryLog",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Events"),f=d.modules.Collection,h=d.modules.Db,e=d.modules.ReactorIO,g=f.prototype.init,i=h.prototype.init,d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"size"),j.prototype.attachIO=function(){var a=this;a._io||(a._log=new f(a._parent.name()+"-BinaryLog",{capped:!0,size:a.size()}),a._log.objectId=function(b){return b||(b=++a._logCounter),b},a._io=new e(a._parent,a,function(b){switch(b.type){case"insert":a._log.insert({type:b.type,data:b.data});break;case"remove":a._log.insert({type:b.type,data:{query:b.data.query}});break;case"update":a._log.insert({type:b.type,data:{query:b.data.query,update:b.data.update}})}return!1}))},j.prototype.detachIO=function(){var a=this;a._io&&(a._log.drop(),a._io.drop(),delete a._log,delete a._io)},f.prototype.init=function(){g.apply(this,arguments),this._binaryLog=new j(this)},d.finishModule("BinaryLog"),b.exports=j},{"./Shared":38}],5:[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.push(a),this._left?this._left.insert(a,this):(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.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){var c,d,e,g=[],h=0;for(c=f.parseArr(this._index,{verbose:!0}),d=f.parseArr(a,{ignore:/\$/,verbose:!0}),e=0;e<c.length;e++)d[e]===c[e]&&(h++,g.push(d[e]));return{matchedKeys:g,totalKeyCount:d.length,score:h}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":32,"./Shared":38}],6:[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){this.init.apply(this,arguments)};o.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._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("./Crc"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,o.prototype.crc=k,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(!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,delete this._listeners,a&&a(!1,!0),!0}return a&&a(!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",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=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=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},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.jStringify(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.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(),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(),{}},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){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:e},c),g.time("Resolve chains"),this._onUpdate(e),this._onChange(),this.deferEmit("change",{type:"update",data:e}))),g.stop(),e||[]},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(!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.deferEmit("change",{type:"remove",data:g}))}return c&&c(!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(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(e),this._onChange(),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.chainSend("insert",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.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},o.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)},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=this.find(a,b);return(new o).subsetOf(this).primaryKey(this._primaryKey).setData(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("Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.apply(this,arguments)},o.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,I=this._metrics.create("find"),J=this.primaryKey(),K=this,L=!0,M={},N=[],O=[],P=[],Q={},R={},S=function(c){return K._match(c,a,b,"and",Q)};if(I.start(),a){if(I.time("analyseQuery"),c=this._analyseQuery(K.decouple(a),b,I),I.time("analyseQuery"),I.data("analysis",c),c.hasJoin&&c.queriesJoin){for(I.time("joinReferences"),g=0;g<c.joinsOn.length;g++)k=c.joinsOn[g],j=new h(c.joinQueries[k]),i=j.value(a)[0],M[c.joinsOn[g]]=this._db.collection(c.joinsOn[g]).subset(i),delete a[c.joinQueries[k]];I.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(I.data("index.potential",c.indexMatch),I.data("index.used",c.indexMatch[0].index),I.time("indexLookup"),e=c.indexMatch[0].lookup||[],I.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(L=!1)):I.flag("usedIndex",!1),L&&(e&&e.length?(d=e.length,I.time("tableScan: "+d),e=e.filter(S)):(d=this._data.length,I.time("tableScan: "+d),e=this._data.filter(S)),I.time("tableScan: "+d)),b.$orderBy&&(I.time("sort"),e=this.sort(b.$orderBy,e),I.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(R.page=b.$page,R.pages=Math.ceil(e.length/b.$limit),R.records=e.length,b.$page&&b.$limit>0&&(I.data("cursor",R),e.splice(0,b.$page*b.$limit))),b.$skip&&(R.skip=b.$skip,e.splice(0,b.$skip),I.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(R.limit=b.$limit,e.length=b.$limit,I.data("limit",b.$limit)),b.$decouple&&(I.time("decouple"),e=this.decouple(e),I.time("decouple"),I.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=M[k]?M[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=K._resolveDynamicQuery(m[n].query,e[x])),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]=K._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 [$multi: 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 N.push(e[x])}I.data("flag.join",!0)}if(N.length){for(I.time("removalQueue"),z=0;z<N.length;z++)y=e.indexOf(N[z]),y>-1&&e.splice(y,1);I.time("removalQueue")}if(b.$transform){for(I.time("transform"),z=0;z<e.length;z++)e.splice(z,1,b.$transform(e[z]));I.time("transform"),I.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(I.time("transformOut"),e=this.transformOut(e),I.time("transformOut")),I.data("results",e.length)}else e=[];if(!b.$aggregate){I.time("scanFields");for(z in b)b.hasOwnProperty(z)&&0!==z.indexOf("$")&&(1===b[z]?O.push(z):0===b[z]&&P.push(z));if(I.time("scanFields"),O.length||P.length){for(I.data("flag.limitFields",!0),I.data("limitFields.on",O),I.data("limitFields.off",P),I.time("limitFields"),z=0;z<e.length;z++){G=e[z];for(A in G)G.hasOwnProperty(A)&&(O.length&&A!==J&&-1===O.indexOf(A)&&delete G[A],P.length&&P.indexOf(A)>-1&&delete G[A])}I.time("limitFields")}if(b.$elemMatch){I.data("flag.elemMatch",!0),I.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(K._match(E[B],b.$elemMatch[z],b,"",{})){D.set(e[A],z,[E[B]]);break}I.time("projection-elemMatch")}if(b.$elemsMatch){I.data("flag.elemsMatch",!0),I.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++)K._match(E[B],b.$elemsMatch[z],b,"",{})&&F.push(E[B]);D.set(e[A],z,F)}I.time("projection-elemsMatch")}}return b.$aggregate&&(I.data("flag.aggregate",!0),I.time("aggregate"),H=new h(b.$aggregate),e=H.value(e),I.time("aggregate")),I.stop(),e.__fdbOp=I,e.$cursor=R,e},o.prototype._resolveDynamicQuery=function(a,b){var c,d,e,f,g,i=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?new h(a.substr(3,a.length-3)).value(b):new h(a).value(b),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]=new h(e.substr(3,e.length-3)).value(b)[0]:c[g]=e;break;case"object":c[g]=i._resolveDynamicQuery(e,b);break;default:c[g]=e}return c},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=[];for(b=0;b<a.length;b++)c[b]=this._transformIn(a[b]);return c}return this._transformIn(a)}return a},o.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},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.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}},o.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r={queriesOn:[this._name],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},s=[],t=[];if(c.time("checkIndexes"),m=new h,n=m.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(o=typeof a[this._primaryKey],("string"===o||"number"===o||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),p=this._primaryIndex.lookup(a,b),r.indexMatch.push({lookup:p,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:n,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(q in this._indexById)if(this._indexById.hasOwnProperty(q)&&(j=this._indexById[q],k=j.name(),c.time("checkIndexMatch: "+k),i=j.match(a,b),i.score>0&&(l=j.lookup(a,b),r.indexMatch.push({lookup:l,keyData:i,index:j})),c.time("checkIndexMatch: "+k),i.score===n))break;c.time("checkIndexes"),r.indexMatch.length>1&&(c.time("findOptimalIndex"),r.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(r.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(s.push(e),"$as"in b.$join[d][e]?t.push(b.$join[d][e].$as):t.push(e));for(g=0;g<t.length;g++)f=this._queryReferencesCollection(a,t[g],""),f&&(r.joinQueries[s[g]]=f,r.queriesJoin=!0);r.joinsOn=s,r.queriesOn=r.queriesOn.concat(s)}return r},o.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},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.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},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,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"}:(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()})},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({"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!"}}),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({"":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},{"./Crc":9,"./IndexBinaryTree":14,"./IndexHashMap":15,"./KeyValueStore":16,"./Metrics":17,"./Overload":30,"./Path":32,"./ReactorIO":36,"./Shared":38}],7:[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"),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=this.decouple(a.data),this._data.remove(a.options.oldData),this._data.insert(a.data);break;case"insert":a.data=this.decouple(a.data),this._data.insert(a.data);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){return a?a instanceof h?a:(this._collectionGroup[a]=this._collectionGroup[a]||new h(a).db(this),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":6,"./Shared":38}],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.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":10,"./Metrics.js":17,"./Overload":30,"./Shared":38}],9:[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}},{}],10:[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("./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._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},{"./Collection.js":6,"./Crc.js":9,"./Metrics.js":17,"./Overload":30,"./Shared":38}],11:[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+'"'))},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){if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document=this._document||{},this._document[a]=this._document[a]||new g(a).db(this),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":6,"./Shared":38}],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._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),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.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={};b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j=e.attr("data-grid-filter"),k=e.attr("data-grid-vartype"),l={},m=e.html(),n=a._db.view("tmpGridFilter_"+a._id+"_"+j);l[j]=1,i={$distinct:l},n.query(i).orderBy(l).from(a._from._from),h=['<div class="dropdown" id="'+a._id+"_"+j+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+j+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',m+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+j+'_dropdownMenu"></ul>'),f.append(g),e.html(f),n.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{:'+j+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox">&nbsp;{^{:'+j+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+j+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=n.query(),d=b.val();d?c[j]=new RegExp(d,"gi"):delete c[j],n.query(c)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=n.query();delete b[j],n.query(b)}),b.on("click","#"+a._id+"_"+j+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),l=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(l.prop("checked",l.prop("checked")),e=l.is(":checked")):(l.prop("checked",!l.prop("checked")),e=l.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[j],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),k){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[j]=d[j]||{$in:[]},f=d[j].$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[j]}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":6,"./CollectionGroup":7,"./ReactorIO":36,"./Shared":38,"./View":40}],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":30,"./Shared":38}],14:[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.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":5,"./Path":32,"./Shared":38}],15:[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.finishModule("IndexHashMap"),b.exports=f},{"./Path":32,"./Shared":38}],16:[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.get(a[b]),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":38}],17:[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":29,"./Shared":38}],18:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],19:[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},{}],20:[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":30,"./Serialiser":37}],21:[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},{}],22:[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":30}],23:[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.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m||"string"!==n&&"number"!==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?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}if("object"==typeof c)return this._match(b,c,d,"and",e);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(this._match(b,l[k],d,"and",e))return!1;return!0}if("object"==typeof c)return this._match(b,c,d,"and",e);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;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!this.db())throw"Cannot operate a "+a+" sub-query on an anonymous collection (one with no db set)!";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!";v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},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}};b.exports=d},{}],24:[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},{}],25:[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},{}],26:[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":30}],27:[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},{}],28:[function(a,b,c){"use strict";var d,e,f,g,h,i=a("./Shared");g=function(){this.init.apply(this,arguments)},g.prototype.init=function(a){var b=this;b._db=a,b._access={}},i.addModule("NodeApiClient",g),i.mixin(g.prototype,"Mixin.Common"),i.mixin(g.prototype,"Mixin.ChainReactor"),d=i.modules.Db,e=d.prototype.init,f=i.modules.Collection,h=i.overload,i.synthesize(g.prototype,"server",function(a){return void 0!==a&&"/"===a.substr(a.length-1,1)&&(a=a.substr(0,a.length-1)),this.$super.call(this,a)}),g.prototype.get=function(a,b){var c=this,d=new XMLHttpRequest;d.onreadystatechange=function(){4===d.readyState&&200===d.status&&b(!1,c.jParse(d.responseText))},d.open("GET",a,!0),d.send(null)},g.prototype.sync=function(a,b,c,d){var e=this,f=new EventSource(this.server()+b+"/_sync");this._db.debug()&&console.log(this._db.logIdentifier()+" Connecting to API server "+this.server()+b),a.__apiConnection=f,f.addEventListener("open",function(c){e.get(e.server()+b,function(b,c){a.upsert(c)})},!1),f.addEventListener("error",function(b){2===f.readyState&&a.unSync()},!1),f.addEventListener("insert",function(b){var c=e.jParse(b.data);a.insert(c)},!1),f.addEventListener("update",function(b){var c=e.jParse(b.data);a.update(c.query,c.update)},!1),f.addEventListener("remove",function(b){var c=e.jParse(b.data);a.remove(c.query)},!1),d&&f.addEventListener("connected",function(a){ d(!1)},!1)},f.prototype.sync=new h({"function":function(a){this.$main.call(this,null,null,a)},$main:function(a,b,c){if(!this._db)throw this.logIdentifier()+" Cannot sync for an anonymous collection! (Collection must be attached to a database)";this.__apiConnection?c&&c(!1):(a||(a="/"+this._db.name()+"/"+this.name()),this._db.api.sync(this,a,b,c))}}),f.prototype.unSync=function(){return this.__apiConnection?(2!==this.__apiConnection.readyState&&this.__apiConnection.close(),delete this.__apiConnection,!0):!1},d.prototype.init=function(){e.apply(this,arguments),this.api=new g(this)},i.finishModule("NodeApiClient"),b.exports=g},{"./Shared":38}],29:[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":32,"./Shared":38}],30:[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",console.log("Overload: ",a),'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},{}],31:[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.privateData(),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.privateData(),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],delete this._name,this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){return a?a instanceof h?a:(this._overview=this._overview||{},this._overview[a]=this._overview[a]||new h(a).db(this),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":6,"./Document":11,"./Shared":38}],32:[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(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":38}],33:[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,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):b.foundData=!1,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):b.foundData=!1,c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){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":6,"./CollectionGroup":7,"./PersistCompress":34,"./PersistCrypto":35,"./Shared":38,async:41,localforage:77}],34:[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":38,pako:78}],35:[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":38,"crypto-js":50}],36:[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),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":38}],37:[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)}),this.registerEncoder("$regexp",function(a){return a instanceof RegExp?{source:a.source,params:""+(a.global?"g":"")+(a.ignoreCase?"i":"")}:void 0}),this.registerDecoder("$regexp",function(a){return new RegExp(a.source,a.params)})},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},{}],38:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.515",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":18,"./Mixin.ChainReactor":19,"./Mixin.Common":20,"./Mixin.Constants":21,"./Mixin.Events":22,"./Mixin.Matching":23,"./Mixin.Sorting":24,"./Mixin.Tags":25,"./Mixin.Triggers":26,"./Mixin.Updating":27,"./Overload":30}],39:[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={}},{}],40:[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._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,!1),this.queryOptions(c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._privateData=new f(this.name()+"_internalPrivate")},d.addModule("View",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.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,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),d.synthesize(l.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),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.find=function(a,b){return this.publicData().find(a,b)},l.prototype.findOne=function(a,b){return this.publicData().findOne(a,b)},l.prototype.findById=function(a,b){return this.publicData().findById(a,b)},l.prototype.findSub=function(a,b,c,d){return this.publicData().findSub(a,b,c,d)},l.prototype.findSubOne=function(a,b,c,d){return this.publicData().findSubOne(a,b,c,d)},l.prototype.data=function(){return this._privateData},l.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a.privateData(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(a,this,function(a){var b,d,e,f,g,h,i;if(c&&!c.isDropped()&&c._querySettings.query){if("insert"===a.type){if(b=a.data,b instanceof Array)for(f=[],i=0;i<b.length;i++)c._privateData._match(b[i],c._querySettings.query,c._querySettings.options,"and",{})&&(f.push(b[i]),g=!0);else c._privateData._match(b,c._querySettings.query,c._querySettings.options,"and",{})&&(f=b,g=!0);return g&&this.chainSend("insert",f),!0}if("update"===a.type){if(d=c._privateData.diff(c._from.subset(c._querySettings.query,c._querySettings.options)),d.insert.length||d.remove.length){if(d.insert.length&&this.chainSend("insert",d.insert),d.update.length)for(h=c._privateData.primaryKey(),i=0;i<d.update.length;i++)e={},e[h]=d.update[i][h],this.chainSend("update",{query:e,update:d.update[i]});if(d.remove.length){h=c._privateData.primaryKey();var j=[],k={query:{$or:j}};for(i=0;i<d.remove.length;i++)j.push({_id:d.remove[i][h]});this.chainSend("remove",k)}return!0}return!1}}return!1});var d=a.find(this._querySettings.query,this._querySettings.options);return this._privateData.primaryKey(a.primaryKey()),this._privateData.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.ensureIndex=function(){return this._privateData.ensureIndex.apply(this._privateData,arguments)},l.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){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._privateData.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._privateData.setData(j);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._privateData.name()+'"'),a.data=this.decouple(a.data),a.data instanceof Array||(a.data=[a.data]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._privateData._insertHandle(a.data,e);else e=this._privateData._data.length,this._privateData._insertHandle(a.data,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._privateData.name()+'"'),g=this._privateData.primaryKey(),f=this._privateData.update(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._privateData._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._privateData._updateSpliceMove(this._privateData._data,i,e);break;case"remove":this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._privateData.name()+'"'),this._privateData.remove(a.data.query,a.options)}},l.prototype.on=function(){return this._privateData.on.apply(this._privateData,arguments)},l.prototype.off=function(){return this._privateData.off.apply(this._privateData,arguments)},l.prototype.emit=function(){return this._privateData.emit.apply(this._privateData,arguments)},l.prototype.distinct=function(a,b,c){var d=this.publicData();return d.distinct.apply(d,arguments)},l.prototype.primaryKey=function(){return this.publicData().primaryKey()},l.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._privateData&&this._privateData.drop(),this._publicData&&this._publicData!==this._privateData&&this._publicData.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._privateData,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},d.synthesize(l.prototype,"db",function(a){return a&&(this.privateData().db(a),this.publicData().db(a),this.debug(a.debug()),this.privateData().debug(a.debug()),this.publicData().debug(a.debug())),this.$super.apply(this,arguments)}),l.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a),void 0!==b&&(this._querySettings.options=b),void 0!==a||void 0!==b?((void 0===c||c===!0)&&this.refresh(),this):this._querySettings},l.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()},l.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()}},l.prototype.query=function(a,b){return void 0!==a?(this._querySettings.query=a,(void 0===b||b===!0)&&this.refresh(),this):this._querySettings.query},l.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},l.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},l.prototype.pageFirst=function(){return this.page(0)},l.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},l.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)}},l.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),this):this._querySettings.options},l.prototype.rebuildActiveBucket=function(a){if(a){var b=this._privateData._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._privateData.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},l.prototype.refresh=function(){if(this._from){var a,b=this.publicData();this._privateData.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor),this._privateData.insert(a),this._privateData._data.$cursor=a.$cursor,b._data.$cursor=a.$cursor}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},l.prototype.count=function(){return this.publicData()?this.publicData().count.apply(this.publicData(),arguments):0},l.prototype.subset=function(){return this.publicData().subset.apply(this._privateData,arguments)},l.prototype.transform=function(a){var b=this;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._transformEnabled?(this._publicData||(this._publicData=new f("__FDB__view_publicData_"+this._name),this._publicData.db(this._privateData._db),this._publicData.transform({enabled:!0,dataIn:this._transformIn,dataOut:this._transformOut}),this._transformIo=new j(this._privateData,this._publicData,function(a){var c=a.data;switch(a.type){case"primaryKey":b._publicData.primaryKey(c),this.chainSend("primaryKey",c);break;case"setData":b._publicData.setData(c),this.chainSend("setData",c);break;case"insert":b._publicData.insert(c),this.chainSend("insert",c);break;case"update":b._publicData.update(c.query,c.update,c.options),this.chainSend("update",c);break;case"remove":b._publicData.remove(c.query,a.options),this.chainSend("remove",c)}})),this._publicData.primaryKey(this.privateData().primaryKey()),this._publicData.setData(this.privateData().find())):this._publicData&&(this._publicData.drop(),delete this._publicData,this._transformIo&&(this._transformIo.drop(),delete this._transformIo)),this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},l.prototype.filter=function(a,b,c){return this.publicData().filter(a,b,c)},l.prototype.privateData=function(){return this._privateData},l.prototype.publicData=function(){return this._transformEnabled?this._publicData:this._privateData},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 l(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 l?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=this._view[a]||new l(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=l},{"./ActiveBucket":3,"./Collection":6,"./CollectionGroup":7,"./ReactorIO":36,"./Shared":38}],41:[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(){if(!j.paused&&g<j.concurrency&&j.tasks.length)for(;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){q.unshift(a)}function f(a){var b=p(q,a);b>=0&&q.splice(b,1)}function g(){j--,k(q.slice(0),function(a){a()})}c||(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=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(s,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](q,l))}for(var j,k=N(a[d])?a[d]:[a[d]],q=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,c(a,e)}else l[d]=b,K.setImmediate(g)}),s=k.slice(0,k.length-1),t=s.length;t--;){if(!(j=a[s[t]]))throw new Error("Has inexistant dependency");if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](q,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(null)});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={};b=b||e;var f=r(function(e){var f=e.pop(),g=b.apply(null,e);g in c?K.setImmediate(function(){f.apply(null,c[g])}):g in d?d[g].push(f):(d[g]=[f],a.apply(null,e.concat([r(function(a){c[g]=a;var b=d[g];delete d[g];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return f.memo=c,f.unmemoized=a,f},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:76}],42:[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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],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){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":44}],44:[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})},{}],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(){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;g[h>>>2]|=(j|k)<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":44}],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(){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":44}],47:[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":44,"./hmac":49,"./sha1":68}],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 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":43,"./core":44}],49:[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":44}],50:[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":42,"./cipher-core":43,"./core":44,"./enc-base64":45,"./enc-utf16":46,"./evpkdf":47,"./format-hex":48,"./hmac":49,"./lib-typedarrays":51,"./md5":52,"./mode-cfb":53,"./mode-ctr":55,"./mode-ctr-gladman":54,"./mode-ecb":56,"./mode-ofb":57,"./pad-ansix923":58,"./pad-iso10126":59,"./pad-iso97971":60,"./pad-nopadding":61,"./pad-zeropadding":62,"./pbkdf2":63,"./rabbit":65,"./rabbit-legacy":64,"./rc4":66,"./ripemd160":67,"./sha1":68,"./sha224":69,"./sha256":70,"./sha3":71,"./sha384":72,"./sha512":73,"./tripledes":74,"./x64-core":75}],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){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":44}],52:[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":44}],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.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":43,"./core":44}],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.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":43,"./core":44}],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.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":43,"./core":44}],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.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":43,"./core":44}],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.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":43,"./core":44}],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.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":43,"./core":44}],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.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":43,"./core":44}],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.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":43,"./core":44}],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.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":43,"./core":44}],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.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":43,"./core":44}],63:[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":44,"./hmac":49,"./sha1":68}],64:[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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],65:[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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],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._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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],67:[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":44}],68:[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":44}],69:[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":44,"./sha256":70}],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(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":44}],71:[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":44,"./x64-core":75}],72:[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":44,"./sha512":73,"./x64-core":75}],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(){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":44,"./x64-core":75}],74:[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":43,"./core":44,"./enc-base64":45,"./evpkdf":47,"./md5":52}],75:[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":44}],76:[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}},{}],77:[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,function(){function a(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=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[h.WEBSQL]=!!a.openDatabase,c[h.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[h.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),m=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},n=function(){function b(a){d(this,b),this.INDEXEDDB=h.INDEXEDDB,this.LOCALSTORAGE=h.LOCALSTORAGE,this.WEBSQL=h.WEBSQL,this._defaultConfig=e({},k),this._config=e({},this._defaultConfig,a),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver)}return b.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},b.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},b.prototype.driver=function(){return this._driver||null},b.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},b.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},b.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},b.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},b.prototype.supports=function(a){return!!l[a]},b.prototype._extend=function(a){e(this,a)},b.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},b.prototype._wrapLibraryMethodsWithReady=function(){for(var b=0;b<j.length;b++)a(this,j[b])},b.prototype.createInstance=function(a){return new b(a)},b}(),o=new n;b["default"]=o}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.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(b){return new Promise(function(c,e){var f=a([""],{type:"image/png"}),g=b.transaction([B],"readwrite");g.objectStore(B).put(f,"key"),g.oncomplete=function(){var a=b.transaction([B],"readwrite"),f=a.objectStore(B).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)})}}})["catch"](function(){return!1})}function f(a){return"boolean"==typeof z?Promise.resolve(z):e(a).then(function(a){return z=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(b){var d=c(atob(b.data));return a([d],{type:b.type})}function i(a){return a&&a.__local_forage_encoded_blob}function j(a){function b(){return Promise.resolve()}var c=this,d={db:null};if(a)for(var e in a)d[e]=a[e];A||(A={});var f=A[d.name];f||(f={forages:[],db:null},A[d.name]=f),f.forages.push(this);for(var g=[],h=0;h<f.forages.length;h++){var i=f.forages[h];i!==this&&g.push(i.ready()["catch"](b))}var j=f.forages.slice(0);return Promise.all(g).then(function(){return d.db=f.db,k(d)}).then(function(a){return d.db=a,n(d,c._defaultConfig.version)?l(d):a}).then(function(a){d.db=f.db=a,c._dbInfo=d;for(var b in j){var e=j[b];e!==c&&(e._dbInfo.db=d.db,e._dbInfo.version=d.version)}})}function k(a){return m(a,!1)}function l(a){return m(a,!0)}function m(a,b){return new Promise(function(c,d){if(a.db){if(!b)return c(a.db);a.db.close()}var e=[a.name];b&&e.push(a.version);var f=y.open.apply(y,e);b&&(f.onupgradeneeded=function(b){var c=f.result;try{c.createObjectStore(a.storeName),b.oldVersion<=1&&c.createObjectStore(B)}catch(d){if("ConstraintError"!==d.name)throw d;x.console.warn('The database "'+a.name+'" has been upgraded from version '+b.oldVersion+" to version "+b.newVersion+', but the storage "'+a.storeName+'" already exists.')}}),f.onerror=function(){d(f.error)},f.onsuccess=function(){c(f.result)}})}function n(a,b){if(!a.db)return!0;var c=!a.db.objectStoreNames.contains(a.storeName),d=a.version<a.db.version,e=a.version>a.db.version;if(d&&(a.version!==b&&x.console.warn('The database "'+a.name+"\" can't be downgraded from version "+a.db.version+" to version "+a.version+"."),a.version=a.db.version),e||c){if(c){var f=a.db.version+1;f>a.version&&(a.version=f)}return!0}return!1}function o(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var 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.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),i(a)&&(a=h(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return w(d,b),d}function p(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 w(d,b),d}function q(a,b,c){var d=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){var h;d.ready().then(function(){return h=d._dbInfo,f(h.db)}).then(function(a){return!a&&b instanceof Blob?g(b):b}).then(function(b){var d=h.db.transaction(h.storeName,"readwrite"),f=d.objectStore(h.storeName);null===b&&(b=void 0);var g=f.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=g.error?g.error:g.transaction.error;e(a)}})["catch"](e)});return w(e,c),e}function r(a,b){var c=this;"string"!=typeof a&&(x.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(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 w(d,b),d}function s(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 w(c,a),c}function t(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 w(c,a),c}function u(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 w(d,b),d}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,"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 w(c,a),c}function w(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var x=this,y=y||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(y){var z,A,B="local-forage-detect-blob-support",C={_driver:"asyncStorage",_initStorage:j,iterate:p,getItem:o,setItem:q,removeItem:r,clear:s,length:t,key:u,keys:v};b["default"]=C}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(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=n.length-1;c>=0;c--){var d=n.key(c);0===d.indexOf(a)&&n.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(m.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=n.getItem(b.keyPrefix+a);return d&&(d=b.serializer.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,d=b.keyPrefix,e=d.length,f=n.length,g=1,h=0;f>h;h++){var i=n.key(h);if(0===i.indexOf(d)){var j=n.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=n.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=n.length,d=[],e=0;c>e;e++)0===n.key(e).indexOf(a.keyPrefix)&&d.push(n.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&&(m.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;n.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(m.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 Promise(function(e,f){var g=d._dbInfo;g.serializer.serialize(b,function(b,d){if(d)f(d);else try{n.setItem(g.keyPrefix+a,b),e(c)}catch(h){("QuotaExceededError"===h.name||"NS_ERROR_DOM_QUOTA_REACHED"===h.name)&&f(h),f(h)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m=this,n=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;n=this.localStorage}catch(o){return}var p={_driver:"localStorageWrapper",_initStorage:a,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};b["default"]=p}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,function(){function a(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=x.BlobBuilder||x.MSBlobBuilder||x.MozBlobBuilder||x.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.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(b){if(b.substring(0,k)!==j)return JSON.parse(b);var c,d=b.substring(w),f=b.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 a([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=this,y={serialize:c,deserialize:d,stringToBuffer:e,bufferToString:f};b["default"]=y}.call("undefined"!=typeof window?window:self),a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0,function(){function a(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(c,e){try{d.db=n(d.name,String(d.version),d.description,d.size)}catch(f){return b.setDriver(b.LOCALSTORAGE).then(function(){return b._initStorage(a)}).then(c)["catch"](e)}d.db.transaction(function(a){a.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){b._dbInfo=d,c()},function(a,b){e(b)})})});return new Promise(function(a,b){a(c(3))}).then(function(a){return d.serializer=a,f})}function d(a,b){var c=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var 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+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=e.serializer.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 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(a,b,c){var d=this;"string"!=typeof a&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new Promise(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b,g=d._dbInfo;g.serializer.serialize(b,function(b,d){d?e(d):g.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+g.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&&(m.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new Promise(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 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=this,n=this.openDatabase;if(n){var o={_driver:"webSQLStorage",_initStorage:a,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};b["default"]=o}}.call("undefined"!=typeof window?window:self),a.exports=b["default"]}])})}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:76}],78:[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":79,"./lib/inflate":80,"./lib/utils/common":81,"./lib/zlib/constants":84}],79:[function(a,b,c){"use strict";function d(a,b){var c=new u(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}function f(a,b){return b=b||{},b.gzip=!0,d(a,b)}var g=a("./zlib/deflate.js"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=Object.prototype.toString,m=0,n=4,o=0,p=1,q=2,r=-1,s=0,t=8,u=function(a){this.options=h.assign({level:r,method:t,chunkSize:16384,windowBits:15,memLevel:8,strategy:s,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 k,this.strm.avail_out=0;var c=g.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==o)throw new Error(j[c]);b.header&&g.deflateSetHeader(this.strm,b.header)};u.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?n:m,"string"==typeof a?e.input=i.string2buf(a):"[object ArrayBuffer]"===l.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 h.Buf8(f),e.next_out=0,e.avail_out=f),c=g.deflate(e,d),c!==p&&c!==o)return this.onEnd(c),this.ended=!0,!1;(0===e.avail_out||0===e.avail_in&&(d===n||d===q))&&("string"===this.options.to?this.onData(i.buf2binstring(h.shrinkBuf(e.output,e.next_out))):this.onData(h.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==p);return d===n?(c=g.deflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===o):d===q?(this.onEnd(o),e.avail_out=0,!0):!0},u.prototype.onData=function(a){this.chunks.push(a)},u.prototype.onEnd=function(a){a===o&&("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.Deflate=u,c.deflate=d,c.deflateRaw=e,c.gzip=f},{"./utils/common":81,"./utils/strings":82,"./zlib/deflate.js":86,"./zlib/messages":91,"./zlib/zstream":93}],80:[function(a,b,c){"use strict";function d(a,b){var c=new n(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function e(a,b){return b=b||{},b.raw=!0,d(a,b)}var f=a("./zlib/inflate.js"),g=a("./utils/common"),h=a("./utils/strings"),i=a("./zlib/constants"),j=a("./zlib/messages"),k=a("./zlib/zstream"),l=a("./zlib/gzheader"),m=Object.prototype.toString,n=function(a){this.options=g.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 k,this.strm.avail_out=0;var c=f.inflateInit2(this.strm,b.windowBits);if(c!==i.Z_OK)throw new Error(j[c]);this.header=new l,f.inflateGetHeader(this.strm,this.header)};n.prototype.push=function(a,b){var c,d,e,j,k,l=this.strm,n=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?i.Z_FINISH:i.Z_NO_FLUSH,"string"==typeof a?l.input=h.binstring2buf(a):"[object ArrayBuffer]"===m.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 g.Buf8(n),l.next_out=0,l.avail_out=n),c=f.inflate(l,i.Z_NO_FLUSH),c===i.Z_BUF_ERROR&&o===!0&&(c=i.Z_OK,o=!1),c!==i.Z_STREAM_END&&c!==i.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0===l.avail_out||c===i.Z_STREAM_END||0===l.avail_in&&(d===i.Z_FINISH||d===i.Z_SYNC_FLUSH))&&("string"===this.options.to?(e=h.utf8border(l.output,l.next_out),j=l.next_out-e,k=h.buf2string(l.output,e),l.next_out=j,l.avail_out=n-j,j&&g.arraySet(l.output,l.output,e,j,0),this.onData(k)):this.onData(g.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!==i.Z_STREAM_END);return c===i.Z_STREAM_END&&(d=i.Z_FINISH),d===i.Z_FINISH?(c=f.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===i.Z_OK):d===i.Z_SYNC_FLUSH?(this.onEnd(i.Z_OK),l.avail_out=0,!0):!0},n.prototype.onData=function(a){this.chunks.push(a)},n.prototype.onEnd=function(a){a===i.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=g.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=n,c.inflate=d,c.inflateRaw=e,c.ungzip=d},{"./utils/common":81,"./utils/strings":82,"./zlib/constants":84,"./zlib/gzheader":87,"./zlib/inflate.js":89,"./zlib/messages":91,"./zlib/zstream":93}],81:[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)},{}],82:[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":81}],83:[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},{}],84:[function(a,b,c){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}},{}],85:[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^a;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],86:[function(a,b,c){"use strict";function d(a,b){return a.msg=G[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&&(C.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){D._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,C.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=E(a.adler,b,e,c):2===a.state.wrap&&(a.adler=F(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-ja?a.strstart-(a.w_size-ja):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ia,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=ia-(m-f),f=m-ia,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-ja)){C.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>=ha)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+ha-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<ha)););}while(a.lookahead<ja&&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===H)return sa;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 sa;if(a.strstart-a.block_start>=a.w_size-ja&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?sa:sa}function o(a,b){for(var c,d;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-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-ja&&(a.match_length=l(a,c)),a.match_length>=ha)if(d=D._tr_tally(a,a.strstart-a.match_start,a.match_length-ha),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ha){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-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=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function p(a,b){for(var c,d,e;;){if(a.lookahead<ja){if(m(a),a.lookahead<ja&&b===H)return sa;if(0===a.lookahead)break}if(c=0,a.lookahead>=ha&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ha-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=ha-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ja&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===S||a.match_length===ha&&a.strstart-a.match_start>4096)&&(a.match_length=ha-1)),a.prev_length>=ha&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ha,d=D._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ha),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+ha-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=ha-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return sa}else if(a.match_available){if(d=D._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return sa}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=D._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ha-1?a.strstart:ha-1,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ia){if(m(a),a.lookahead<=ia&&b===H)return sa;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ha&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ia;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=ia-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ha?(c=D._tr_tally(a,1,a.match_length-ha),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===H)return sa;break}if(a.match_length=0,c=D._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return sa}return a.insert=0,b===K?(h(a,!0),0===a.strm.avail_out?ua:va):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?sa:ta}function s(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=B[a.level].max_lazy,a.good_match=B[a.level].good_length,a.nice_match=B[a.level].nice_length,a.max_chain_length=B[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ha-1,a.match_available=0,a.ins_h=0}function t(){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=Y,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 C.Buf16(2*fa),this.dyn_dtree=new C.Buf16(2*(2*da+1)),this.bl_tree=new C.Buf16(2*(2*ea+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 C.Buf16(ga+1),this.heap=new C.Buf16(2*ca+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new C.Buf16(2*ca+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 u(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=X,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?la:qa,a.adler=2===b.wrap?0:1,b.last_flush=H,D._tr_init(b),M):d(a,O)}function v(a){var b=u(a);return b===M&&s(a.state),b}function w(a,b){return a&&a.state?2!==a.state.wrap?O:(a.state.gzhead=b,M):O}function x(a,b,c,e,f,g){if(!a)return O;var h=1;if(b===R&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>Z||c!==Y||8>e||e>15||0>b||b>9||0>g||g>V)return d(a,O);8===e&&(e=9);var i=new t;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+ha-1)/ha),i.window=new C.Buf8(2*i.w_size),i.head=new C.Buf16(i.hash_size),i.prev=new C.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new C.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,v(a)}function y(a,b){return x(a,b,Y,$,_,W)}function z(a,b){var c,h,k,l;if(!a||!a.state||b>L||0>b)return a?d(a,O):O;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===ra&&b!==K)return d(a,0===a.avail_out?Q:O);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===la)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>=T||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=F(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=ma):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=T||h.level<2?4:0),i(h,wa),h.status=qa);else{var m=Y+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=T||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=ka),m+=31-m%31,h.status=qa,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===ma)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=F(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=F(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=na)}else h.status=na;if(h.status===na)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(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=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=F(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=F(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=pa)}else h.status=pa;if(h.status===pa&&(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=qa)):h.status=qa),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,M}else if(0===a.avail_in&&e(b)<=e(c)&&b!==K)return d(a,Q);if(h.status===ra&&0!==a.avail_in)return d(a,Q);if(0!==a.avail_in||0!==h.lookahead||b!==H&&h.status!==ra){var o=h.strategy===T?r(h,b):h.strategy===U?q(h,b):B[h.level].func(h,b);if((o===ua||o===va)&&(h.status=ra),o===sa||o===ua)return 0===a.avail_out&&(h.last_flush=-1),M;if(o===ta&&(b===I?D._tr_align(h):b!==L&&(D._tr_stored_block(h,0,0,!1),b===J&&(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,M}return b!==K?M:h.wrap<=0?N:(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?M:N)}function A(a){var b;return a&&a.state?(b=a.state.status,b!==la&&b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra?d(a,O):(a.state=null,b===qa?d(a,P):M)):O}var B,C=a("../utils/common"),D=a("./trees"),E=a("./adler32"),F=a("./crc32"),G=a("./messages"),H=0,I=1,J=3,K=4,L=5,M=0,N=1,O=-2,P=-3,Q=-5,R=-1,S=1,T=2,U=3,V=4,W=0,X=2,Y=8,Z=9,$=15,_=8,aa=29,ba=256,ca=ba+1+aa,da=30,ea=19,fa=2*ca+1,ga=15,ha=3,ia=258,ja=ia+ha+1,ka=32,la=42,ma=69,na=73,oa=91,pa=103,qa=113,ra=666,sa=1,ta=2,ua=3,va=4,wa=3,xa=function(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e};B=[new xa(0,0,0,0,n),new xa(4,4,8,4,o),new xa(4,5,16,8,o),new xa(4,6,32,32,o),new xa(4,4,16,16,p),new xa(8,16,32,32,p),new xa(8,16,128,128,p),new xa(8,32,128,256,p),new xa(32,128,258,1024,p),new xa(32,258,258,4096,p)],c.deflateInit=y,c.deflateInit2=x,c.deflateReset=v,c.deflateResetKeep=u,c.deflateSetHeader=w,c.deflate=z,c.deflateEnd=A,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":81,"./adler32":83,"./crc32":85,"./messages":91,"./trees":92}],87:[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},{}],88:[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}},{}],89:[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":81,"./adler32":83,"./crc32":85,"./inffast":88,"./inftrees":90}],90:[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":81}],91:[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"}},{}],92:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a){return 256>a?ga[a]:ga[256+(a>>>7)]}function f(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function g(a,b,c){a.bi_valid>V-c?(a.bi_buf|=b<<a.bi_valid&65535,f(a,a.bi_buf),a.bi_buf=b>>V-a.bi_valid,a.bi_valid+=c-V):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function h(a,b,c){g(a,c[2*b],c[2*b+1])}function i(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function j(a){16===a.bi_valid?(f(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 k(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;U>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;T>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 l(a,b,c){var d,e,f=new Array(U+1),g=0;for(d=1;U>=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]=i(f[h]++,h))}}function m(){var a,b,c,d,e,f=new Array(U+1);for(c=0,d=0;O-1>d;d++)for(ia[d]=c,a=0;a<1<<_[d];a++)ha[c++]=d;for(ha[c-1]=d,e=0,d=0;16>d;d++)for(ja[d]=e,a=0;a<1<<aa[d];a++)ga[e++]=d;for(e>>=7;R>d;d++)for(ja[d]=e<<7,a=0;a<1<<aa[d]-7;a++)ga[256+e++]=d;for(b=0;U>=b;b++)f[b]=0;for(a=0;143>=a;)ea[2*a+1]=8,a++,f[8]++;for(;255>=a;)ea[2*a+1]=9,a++,f[9]++;for(;279>=a;)ea[2*a+1]=7,a++,f[7]++;for(;287>=a;)ea[2*a+1]=8,a++,f[8]++;for(l(ea,Q+1,f),a=0;R>a;a++)fa[2*a+1]=5,fa[2*a]=i(a,5);ka=new na(ea,_,P+1,Q,U),la=new na(fa,aa,0,R,U),ma=new na(new Array(0),ba,0,S,W)}function n(a){var b;for(b=0;Q>b;b++)a.dyn_ltree[2*b]=0;for(b=0;R>b;b++)a.dyn_dtree[2*b]=0;for(b=0;S>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*X]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function o(a){a.bi_valid>8?f(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 p(a,b,c,d){o(a),d&&(f(a,c),f(a,~c)),E.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function q(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 r(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&q(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!q(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function s(a,b,c){var d,f,i,j,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],f=a.pending_buf[a.l_buf+k],k++,0===d?h(a,f,b):(i=ha[f],h(a,i+P+1,b),j=_[i],0!==j&&(f-=ia[i],g(a,f,j)),d--,i=e(d),h(a,i,c),j=aa[i],0!==j&&(d-=ja[i],g(a,d,j)));while(k<a.last_lit);h(a,X,b)}function t(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=T,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--)r(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],r(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++,r(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],k(a,b),l(f,j,a.bl_count)}function u(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*Y]++):10>=h?a.bl_tree[2*Z]++:a.bl_tree[2*$]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function v(a,b,c){var d,e,f=-1,i=b[1],j=0,k=7,l=4;for(0===i&&(k=138,l=3),d=0;c>=d;d++)if(e=i,i=b[2*(d+1)+1],!(++j<k&&e===i)){if(l>j){do h(a,e,a.bl_tree);while(0!==--j)}else 0!==e?(e!==f&&(h(a,e,a.bl_tree),j--),h(a,Y,a.bl_tree),g(a,j-3,2)):10>=j?(h(a,Z,a.bl_tree),g(a,j-3,3)):(h(a,$,a.bl_tree),g(a,j-11,7));j=0,f=e,0===i?(k=138,l=3):e===i?(k=6,l=3):(k=7,l=4)}}function w(a){var b;for(u(a,a.dyn_ltree,a.l_desc.max_code),u(a,a.dyn_dtree,a.d_desc.max_code),t(a,a.bl_desc),b=S-1;b>=3&&0===a.bl_tree[2*ca[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function x(a,b,c,d){var e;for(g(a,b-257,5),g(a,c-1,5),g(a,d-4,4),e=0;d>e;e++)g(a,a.bl_tree[2*ca[e]+1],3);v(a,a.dyn_ltree,b-1),v(a,a.dyn_dtree,c-1)}function y(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return G;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return H;for(b=32;P>b;b++)if(0!==a.dyn_ltree[2*b])return H;return G}function z(a){pa||(m(),pa=!0),a.l_desc=new oa(a.dyn_ltree,ka),a.d_desc=new oa(a.dyn_dtree,la),a.bl_desc=new oa(a.bl_tree,ma),a.bi_buf=0,a.bi_valid=0,n(a)}function A(a,b,c,d){g(a,(J<<1)+(d?1:0),3),p(a,b,c,!0)}function B(a){g(a,K<<1,3),h(a,X,ea),j(a)}function C(a,b,c,d){var e,f,h=0;a.level>0?(a.strm.data_type===I&&(a.strm.data_type=y(a)),t(a,a.l_desc),t(a,a.d_desc),h=w(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?A(a,b,c,d):a.strategy===F||f===e?(g(a,(K<<1)+(d?1:0),3),s(a,ea,fa)):(g(a,(L<<1)+(d?1:0),3),x(a,a.l_desc.max_code+1,a.d_desc.max_code+1,h+1),s(a,a.dyn_ltree,a.dyn_dtree)),n(a),d&&o(a)}function D(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*(ha[c]+P+1)]++,a.dyn_dtree[2*e(b)]++),a.last_lit===a.lit_bufsize-1}var E=a("../utils/common"),F=4,G=0,H=1,I=2,J=0,K=1,L=2,M=3,N=258,O=29,P=256,Q=P+1+O,R=30,S=19,T=2*Q+1,U=15,V=16,W=7,X=256,Y=16,Z=17,$=18,_=[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],aa=[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],ba=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],da=512,ea=new Array(2*(Q+2));d(ea);var fa=new Array(2*R);d(fa);var ga=new Array(da);d(ga);var ha=new Array(N-M+1);d(ha);var ia=new Array(O);d(ia);var ja=new Array(R);d(ja);var ka,la,ma,na=function(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},oa=function(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b},pa=!1;c._tr_init=z,c._tr_stored_block=A,c._tr_flush_block=C,c._tr_tally=D,c._tr_align=B},{"../utils/common":81}],93:[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},{}]},{},[1]);
client/app/routes/main-routes.js
weisuke/react-redux-sinatra-boilerplate
/** * Created by wliuhuiz on 9/13/15. */ import React from 'react' import {Router, Route, IndexRoute} from 'react-router'; import MainApp from '../containers/MainApp' import Dashboard from "../containers/Dashboard" import Builds from "../containers/Builds" export default function renderRoutes (history) { return ( <Router history={history}> <Route path="/" component={MainApp} > <IndexRoute component={Dashboard} /> <Route path="dashboard" component={Dashboard} /> <Route path="builds" component={Builds} /> </Route> </Router> ) }
public/js/14.js
ritchieanesco/frontendmastersreact
/* Details page */ import React from 'react' import { render } from 'react-dom' import { BrowserRouter, Match } from 'react-router' import Landing from './14B' import Search from './14C' import Details from './14E' // centralise data to share with components import preload from '../../public/data.json' import '../normalize.css' import '../style.css' // this view will be available on all pages.. consider this the layout view // see nav and footer below which will available on all pages // any pattern matches will load that page // pass properties and data to components // <Match // pattern='/search' // shows={preload.shows} // component={(props) => <Search {...props} />} // /> // props is passing the browser router properties to components const App = React.createClass({ render () { return ( <BrowserRouter> <div className='app'> {/* <nav></nav> */} <Match exactly pattern='/' component={Landing} /> <Match pattern='/search' component={(props) => <Search shows={preload.shows} {...props} />} /> <Match pattern='/details/:id' component={(props) => { const shows = preload.shows.filter((show) => props.params.id === show.imdbID) return <Details show={shows[0]} {...props} /> }} /> {/* <footer></footer> */} </div> </BrowserRouter> ) } }) // <App /> short for react.createElement render(<App />, document.getElementById('app'))