code
stringlengths
2
1.05M
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":6,"../lib/Shim.IE8":30}],2:[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":26,"./Shared":29}],3:[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; },{}],4:[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); } // 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 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.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; // 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.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. * @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 = 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 = 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 = 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.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; },{"./Condition":5,"./Index2d":9,"./IndexBinaryTree":10,"./IndexHashMap":11,"./KeyValueStore":12,"./Metrics":13,"./Overload":25,"./Path":26,"./ReactorIO":27,"./Shared":29}],5:[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":29}],6:[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":7,"./Metrics.js":13,"./Overload":25,"./Shared":29}],7:[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":3,"./Collection.js":4,"./Metrics.js":13,"./Overload":25,"./Shared":29}],8:[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 - rob@irrelon.com "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; } },{}],9:[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":2,"./GeoHash":8,"./Path":26,"./Shared":29}],10:[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":2,"./Path":26,"./Shared":29}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; 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":26,"./Shared":29}],12:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} 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":29}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":24,"./Shared":29}],14:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],15:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides 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; },{}],16:[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":25,"./Serialiser":28}],17:[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; },{}],18:[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":25}],19:[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; },{}],20:[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; },{}],21:[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; },{}],22:[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":25}],23:[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; },{}],24:[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":26,"./Shared":29}],25:[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; },{}],26:[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":29}],27:[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":29}],28:[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; },{}],29:[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.823', 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":14,"./Mixin.ChainReactor":15,"./Mixin.Common":16,"./Mixin.Constants":17,"./Mixin.Events":18,"./Mixin.Matching":19,"./Mixin.Sorting":20,"./Mixin.Tags":21,"./Mixin.Triggers":22,"./Mixin.Updating":23,"./Overload":25}],30:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}]},{},[1]);
/** * Plupload - multi-runtime File Uploader * v2.3.1 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2017-02-06 */ ;(function (global, factory) { var extract = function() { var ctx = {}; factory.apply(ctx, arguments); return ctx.plupload; }; if (typeof define === "function" && define.amd) { define("plupload", ['./moxie'], extract); } else if (typeof module === "object" && module.exports) { module.exports = extract(require('./moxie')); } else { global.plupload = extract(global.moxie); } }(this || window, function(moxie) { /** * Plupload.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ ;(function(exports, o, undef) { var delay = window.setTimeout; var fileFilters = {}; var u = o.core.utils; var Runtime = o.runtime.Runtime; // convert plupload features to caps acceptable by mOxie function normalizeCaps(settings) { var features = settings.required_features, caps = {}; function resolve(feature, value, strict) { // Feature notation is deprecated, use caps (this thing here is required for backward compatibility) var map = { chunks: 'slice_blob', jpgresize: 'send_binary_string', pngresize: 'send_binary_string', progress: 'report_upload_progress', multi_selection: 'select_multiple', dragdrop: 'drag_and_drop', drop_element: 'drag_and_drop', headers: 'send_custom_headers', urlstream_upload: 'send_binary_string', canSendBinary: 'send_binary', triggerDialog: 'summon_file_dialog' }; if (map[feature]) { caps[map[feature]] = value; } else if (!strict) { caps[feature] = value; } } if (typeof(features) === 'string') { plupload.each(features.split(/\s*,\s*/), function(feature) { resolve(feature, true); }); } else if (typeof(features) === 'object') { plupload.each(features, function(value, feature) { resolve(feature, value); }); } else if (features === true) { // check settings for required features if (settings.chunk_size && settings.chunk_size > 0) { caps.slice_blob = true; } if (!plupload.isEmptyObj(settings.resize) || settings.multipart === false) { caps.send_binary_string = true; } if (settings.http_method) { caps.use_http_method = settings.http_method; } plupload.each(settings, function(value, feature) { resolve(feature, !!value, true); // strict check }); } return caps; } /** * @module plupload * @static */ var plupload = { /** * Plupload version will be replaced on build. * * @property VERSION * @for Plupload * @static * @final */ VERSION : '2.3.1', /** * The state of the queue before it has started and after it has finished * * @property STOPPED * @static * @final */ STOPPED : 1, /** * Upload process is running * * @property STARTED * @static * @final */ STARTED : 2, /** * File is queued for upload * * @property QUEUED * @static * @final */ QUEUED : 1, /** * File is being uploaded * * @property UPLOADING * @static * @final */ UPLOADING : 2, /** * File has failed to be uploaded * * @property FAILED * @static * @final */ FAILED : 4, /** * File has been uploaded successfully * * @property DONE * @static * @final */ DONE : 5, // Error constants used by the Error event /** * Generic error for example if an exception is thrown inside Silverlight. * * @property GENERIC_ERROR * @static * @final */ GENERIC_ERROR : -100, /** * HTTP transport error. For example if the server produces a HTTP status other than 200. * * @property HTTP_ERROR * @static * @final */ HTTP_ERROR : -200, /** * Generic I/O error. For example if it wasn't possible to open the file stream on local machine. * * @property IO_ERROR * @static * @final */ IO_ERROR : -300, /** * @property SECURITY_ERROR * @static * @final */ SECURITY_ERROR : -400, /** * Initialization error. Will be triggered if no runtime was initialized. * * @property INIT_ERROR * @static * @final */ INIT_ERROR : -500, /** * File size error. If the user selects a file that is too large it will be blocked and an error of this type will be triggered. * * @property FILE_SIZE_ERROR * @static * @final */ FILE_SIZE_ERROR : -600, /** * File extension error. If the user selects a file that isn't valid according to the filters setting. * * @property FILE_EXTENSION_ERROR * @static * @final */ FILE_EXTENSION_ERROR : -601, /** * Duplicate file error. If prevent_duplicates is set to true and user selects the same file again. * * @property FILE_DUPLICATE_ERROR * @static * @final */ FILE_DUPLICATE_ERROR : -602, /** * Runtime will try to detect if image is proper one. Otherwise will throw this error. * * @property IMAGE_FORMAT_ERROR * @static * @final */ IMAGE_FORMAT_ERROR : -700, /** * While working on files runtime may run out of memory and will throw this error. * * @since 2.1.2 * @property MEMORY_ERROR * @static * @final */ MEMORY_ERROR : -701, /** * Each runtime has an upper limit on a dimension of the image it can handle. If bigger, will throw this error. * * @property IMAGE_DIMENSIONS_ERROR * @static * @final */ IMAGE_DIMENSIONS_ERROR : -702, /** * Mime type lookup table. * * @property mimeTypes * @type Object * @final */ mimeTypes : u.Mime.mimes, /** * In some cases sniffing is the only way around :( */ ua: u.Env, /** * Gets the true type of the built-in object (better version of typeof). * @credits Angus Croll (http://javascriptweblog.wordpress.com/) * * @method typeOf * @static * @param {Object} o Object to check. * @return {String} Object [[Class]] */ typeOf: u.Basic.typeOf, /** * Extends the specified object with another object. * * @method extend * @static * @param {Object} target Object to extend. * @param {Object..} obj Multiple objects to extend with. * @return {Object} Same as target, the extended object. */ extend : u.Basic.extend, /** * Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers. * The only way a user would be able to get the same ID is if the two persons at the same exact millisecond manages * to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique. * It's more probable for the earth to be hit with an asteriod. You can also if you want to be 100% sure set the plupload.guidPrefix property * to an user unique key. * * @method guid * @static * @return {String} Virtually unique id. */ guid : u.Basic.guid, /** * Get array of DOM Elements by their ids. * * @method get * @param {String} id Identifier of the DOM Element * @return {Array} */ getAll : function get(ids) { var els = [], el; if (plupload.typeOf(ids) !== 'array') { ids = [ids]; } var i = ids.length; while (i--) { el = plupload.get(ids[i]); if (el) { els.push(el); } } return els.length ? els : null; }, /** Get DOM element by id @method get @param {String} id Identifier of the DOM Element @return {Node} */ get: u.Dom.get, /** * Executes the callback function for each item in array/object. If you return false in the * callback it will break the loop. * * @method each * @static * @param {Object} obj Object to iterate. * @param {function} callback Callback function to execute for each item. */ each : u.Basic.each, /** * Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields. * * @method getPos * @static * @param {Element} node HTML element or element id to get x, y position from. * @param {Element} root Optional root element to stop calculations at. * @return {object} Absolute position of the specified element object with x, y fields. */ getPos : u.Dom.getPos, /** * Returns the size of the specified node in pixels. * * @method getSize * @static * @param {Node} node Node to get the size of. * @return {Object} Object with a w and h property. */ getSize : u.Dom.getSize, /** * Encodes the specified string. * * @method xmlEncode * @static * @param {String} s String to encode. * @return {String} Encoded string. */ xmlEncode : function(str) { var xmlEncodeChars = {'<' : 'lt', '>' : 'gt', '&' : 'amp', '"' : 'quot', '\'' : '#39'}, xmlEncodeRegExp = /[<>&\"\']/g; return str ? ('' + str).replace(xmlEncodeRegExp, function(chr) { return xmlEncodeChars[chr] ? '&' + xmlEncodeChars[chr] + ';' : chr; }) : str; }, /** * Forces anything into an array. * * @method toArray * @static * @param {Object} obj Object with length field. * @return {Array} Array object containing all items. */ toArray : u.Basic.toArray, /** * Find an element in array and return its index if present, otherwise return -1. * * @method inArray * @static * @param {mixed} needle Element to find * @param {Array} array * @return {Int} Index of the element, or -1 if not found */ inArray : u.Basic.inArray, /** Recieve an array of functions (usually async) to call in sequence, each function receives a callback as first argument that it should call, when it completes. Finally, after everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the sequence and invoke main callback immediately. @method inSeries @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of error */ inSeries: u.Basic.inSeries, /** * Extends the language pack object with new items. * * @method addI18n * @static * @param {Object} pack Language pack items to add. * @return {Object} Extended language pack object. */ addI18n : o.core.I18n.addI18n, /** * Translates the specified string by checking for the english string in the language pack lookup. * * @method translate * @static * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ translate : o.core.I18n.translate, /** * Pseudo sprintf implementation - simple way to replace tokens with specified values. * * @param {String} str String with tokens * @return {String} String with replaced tokens */ sprintf : u.Basic.sprintf, /** * Checks if object is empty. * * @method isEmptyObj * @static * @param {Object} obj Object to check. * @return {Boolean} */ isEmptyObj : u.Basic.isEmptyObj, /** * Checks if specified DOM element has specified class. * * @method hasClass * @static * @param {Object} obj DOM element like object to add handler to. * @param {String} name Class name */ hasClass : u.Dom.hasClass, /** * Adds specified className to specified DOM element. * * @method addClass * @static * @param {Object} obj DOM element like object to add handler to. * @param {String} name Class name */ addClass : u.Dom.addClass, /** * Removes specified className from specified DOM element. * * @method removeClass * @static * @param {Object} obj DOM element like object to add handler to. * @param {String} name Class name */ removeClass : u.Dom.removeClass, /** * Returns a given computed style of a DOM element. * * @method getStyle * @static * @param {Object} obj DOM element like object. * @param {String} name Style you want to get from the DOM element */ getStyle : u.Dom.getStyle, /** * Adds an event handler to the specified object and store reference to the handler * in objects internal Plupload registry (@see removeEvent). * * @method addEvent * @static * @param {Object} obj DOM element like object to add handler to. * @param {String} name Name to add event listener to. * @param {Function} callback Function to call when event occurs. * @param {String} (optional) key that might be used to add specifity to the event record. */ addEvent : u.Events.addEvent, /** * Remove event handler from the specified object. If third argument (callback) * is not specified remove all events with the specified name. * * @method removeEvent * @static * @param {Object} obj DOM element to remove event listener(s) from. * @param {String} name Name of event listener to remove. * @param {Function|String} (optional) might be a callback or unique key to match. */ removeEvent: u.Events.removeEvent, /** * Remove all kind of events from the specified object * * @method removeAllEvents * @static * @param {Object} obj DOM element to remove event listeners from. * @param {String} (optional) unique key to match, when removing events. */ removeAllEvents: u.Events.removeAllEvents, /** * Cleans the specified name from national characters (diacritics). The result will be a name with only a-z, 0-9 and _. * * @method cleanName * @static * @param {String} s String to clean up. * @return {String} Cleaned string. */ cleanName : function(name) { var i, lookup; // Replace diacritics lookup = [ /[\300-\306]/g, 'A', /[\340-\346]/g, 'a', /\307/g, 'C', /\347/g, 'c', /[\310-\313]/g, 'E', /[\350-\353]/g, 'e', /[\314-\317]/g, 'I', /[\354-\357]/g, 'i', /\321/g, 'N', /\361/g, 'n', /[\322-\330]/g, 'O', /[\362-\370]/g, 'o', /[\331-\334]/g, 'U', /[\371-\374]/g, 'u' ]; for (i = 0; i < lookup.length; i += 2) { name = name.replace(lookup[i], lookup[i + 1]); } // Replace whitespace name = name.replace(/\s+/g, '_'); // Remove anything else name = name.replace(/[^a-z0-9_\-\.]+/gi, ''); return name; }, /** * Builds a full url out of a base URL and an object with items to append as query string items. * * @method buildUrl * @static * @param {String} url Base URL to append query string items to. * @param {Object} items Name/value object to serialize as a querystring. * @return {String} String with url + serialized query string items. */ buildUrl: function(url, items) { var query = ''; plupload.each(items, function(value, name) { query += (query ? '&' : '') + encodeURIComponent(name) + '=' + encodeURIComponent(value); }); if (query) { url += (url.indexOf('?') > 0 ? '&' : '?') + query; } return url; }, /** * Formats the specified number as a size string for example 1024 becomes 1 KB. * * @method formatSize * @static * @param {Number} size Size to format as string. * @return {String} Formatted size string. */ formatSize : function(size) { if (size === undef || /\D/.test(size)) { return plupload.translate('N/A'); } function round(num, precision) { return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision); } var boundary = Math.pow(1024, 4); // TB if (size > boundary) { return round(size / boundary, 1) + " " + plupload.translate('tb'); } // GB if (size > (boundary/=1024)) { return round(size / boundary, 1) + " " + plupload.translate('gb'); } // MB if (size > (boundary/=1024)) { return round(size / boundary, 1) + " " + plupload.translate('mb'); } // KB if (size > 1024) { return Math.round(size / 1024) + " " + plupload.translate('kb'); } return size + " " + plupload.translate('b'); }, /** * Parses the specified size string into a byte value. For example 10kb becomes 10240. * * @method parseSize * @static * @param {String|Number} size String to parse or number to just pass through. * @return {Number} Size in bytes. */ parseSize : u.Basic.parseSizeStr, /** * A way to predict what runtime will be choosen in the current environment with the * specified settings. * * @method predictRuntime * @static * @param {Object|String} config Plupload settings to check * @param {String} [runtimes] Comma-separated list of runtimes to check against * @return {String} Type of compatible runtime */ predictRuntime : function(config, runtimes) { var up, runtime; up = new plupload.Uploader(config); runtime = Runtime.thatCan(up.getOption().required_features, runtimes || config.runtimes); up.destroy(); return runtime; }, /** * Registers a filter that will be executed for each file added to the queue. * If callback returns false, file will not be added. * * Callback receives two arguments: a value for the filter as it was specified in settings.filters * and a file to be filtered. Callback is executed in the context of uploader instance. * * @method addFileFilter * @static * @param {String} name Name of the filter by which it can be referenced in settings.filters * @param {String} cb Callback - the actual routine that every added file must pass */ addFileFilter: function(name, cb) { fileFilters[name] = cb; } }; plupload.addFileFilter('mime_types', function(filters, file, cb) { if (filters.length && !filters.regexp.test(file.name)) { this.trigger('Error', { code : plupload.FILE_EXTENSION_ERROR, message : plupload.translate('File extension error.'), file : file }); cb(false); } else { cb(true); } }); plupload.addFileFilter('max_file_size', function(maxSize, file, cb) { var undef; maxSize = plupload.parseSize(maxSize); // Invalid file size if (file.size !== undef && maxSize && file.size > maxSize) { this.trigger('Error', { code : plupload.FILE_SIZE_ERROR, message : plupload.translate('File size error.'), file : file }); cb(false); } else { cb(true); } }); plupload.addFileFilter('prevent_duplicates', function(value, file, cb) { if (value) { var ii = this.files.length; while (ii--) { // Compare by name and size (size might be 0 or undefined, but still equivalent for both) if (file.name === this.files[ii].name && file.size === this.files[ii].size) { this.trigger('Error', { code : plupload.FILE_DUPLICATE_ERROR, message : plupload.translate('Duplicate file error.'), file : file }); cb(false); return; } } } cb(true); }); /** @class Uploader @constructor @param {Object} settings For detailed information about each option check documentation. @param {String|DOMElement} settings.browse_button id of the DOM element or DOM element itself to use as file dialog trigger. @param {Number|String} [settings.chunk_size=0] Chunk size in bytes to slice the file into. Shorcuts with b, kb, mb, gb, tb suffixes also supported. `e.g. 204800 or "204800b" or "200kb"`. By default - disabled. @param {String|DOMElement} [settings.container] id of the DOM element or DOM element itself that will be used to wrap uploader structures. Defaults to immediate parent of the `browse_button` element. @param {String|DOMElement} [settings.drop_element] id of the DOM element or DOM element itself to use as a drop zone for Drag-n-Drop. @param {String} [settings.file_data_name="file"] Name for the file field in Multipart formated message. @param {Object} [settings.filters={}] Set of file type filters. @param {String|Number} [settings.filters.max_file_size=0] Maximum file size that the user can pick, in bytes. Optionally supports b, kb, mb, gb, tb suffixes. `e.g. "10mb" or "1gb"`. By default - not set. Dispatches `plupload.FILE_SIZE_ERROR`. @param {Array} [settings.filters.mime_types=[]] List of file types to accept, each one defined by title and list of extensions. `e.g. {title : "Image files", extensions : "jpg,jpeg,gif,png"}`. Dispatches `plupload.FILE_EXTENSION_ERROR` @param {Boolean} [settings.filters.prevent_duplicates=false] Do not let duplicates into the queue. Dispatches `plupload.FILE_DUPLICATE_ERROR`. @param {String} [settings.flash_swf_url] URL of the Flash swf. @param {Object} [settings.headers] Custom headers to send with the upload. Hash of name/value pairs. @param {String} [settings.http_method="POST"] HTTP method to use during upload (only PUT or POST allowed). @param {Number} [settings.max_retries=0] How many times to retry the chunk or file, before triggering Error event. @param {Boolean} [settings.multipart=true] Whether to send file and additional parameters as Multipart formated message. @param {Object} [settings.multipart_params] Hash of key/value pairs to send with every file upload. @param {Boolean} [settings.multi_selection=true] Enable ability to select multiple files at once in file dialog. @param {String|Object} [settings.required_features] Either comma-separated list or hash of required features that chosen runtime should absolutely possess. @param {Object} [settings.resize] Enable resizng of images on client-side. Applies to `image/jpeg` and `image/png` only. `e.g. {width : 200, height : 200, quality : 90, crop: true}` @param {Number} [settings.resize.width] If image is bigger, it will be resized. @param {Number} [settings.resize.height] If image is bigger, it will be resized. @param {Number} [settings.resize.quality=90] Compression quality for jpegs (1-100). @param {Boolean} [settings.resize.crop=false] Whether to crop images to exact dimensions. By default they will be resized proportionally. @param {String} [settings.runtimes="html5,flash,silverlight,html4"] Comma separated list of runtimes, that Plupload will try in turn, moving to the next if previous fails. @param {String} [settings.silverlight_xap_url] URL of the Silverlight xap. @param {Boolean} [settings.send_chunk_number=true] Whether to send chunks and chunk numbers, or total and offset bytes. @param {Boolean} [settings.send_file_name=true] Whether to send file name as additional argument - 'name' (required for chunked uploads and some other cases where file name cannot be sent via normal ways). @param {String} settings.url URL of the server-side upload handler. @param {Boolean} [settings.unique_names=false] If true will generate unique filenames for uploaded files. */ plupload.Uploader = function(options) { /** Fires when the current RunTime has been initialized. @event Init @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** Fires after the init event incase you need to perform actions there. @event PostInit @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** Fires when the option is changed in via uploader.setOption(). @event OptionChanged @since 2.1 @param {plupload.Uploader} uploader Uploader instance sending the event. @param {String} name Name of the option that was changed @param {Mixed} value New value for the specified option @param {Mixed} oldValue Previous value of the option */ /** Fires when the silverlight/flash or other shim needs to move. @event Refresh @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** Fires when the overall state is being changed for the upload queue. @event StateChanged @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** Fires when browse_button is clicked and browse dialog shows. @event Browse @since 2.1.2 @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** Fires for every filtered file before it is added to the queue. @event FileFiltered @since 2.1 @param {plupload.Uploader} uploader Uploader instance sending the event. @param {plupload.File} file Another file that has to be added to the queue. */ /** Fires when the file queue is changed. In other words when files are added/removed to the files array of the uploader instance. @event QueueChanged @param {plupload.Uploader} uploader Uploader instance sending the event. */ /** Fires after files were filtered and added to the queue. @event FilesAdded @param {plupload.Uploader} uploader Uploader instance sending the event. @param {Array} files Array of file objects that were added to queue by the user. */ /** Fires when file is removed from the queue. @event FilesRemoved @param {plupload.Uploader} uploader Uploader instance sending the event. @param {Array} files Array of files that got removed. */ /** Fires just before a file is uploaded. Can be used to cancel the upload for the specified file by returning false from the handler. @event BeforeUpload @param {plupload.Uploader} uploader Uploader instance sending the event. @param {plupload.File} file File to be uploaded. */ /** Fires when a file is to be uploaded by the runtime. @event UploadFile @param {plupload.Uploader} uploader Uploader instance sending the event. @param {plupload.File} file File to be uploaded. */ /** Fires while a file is being uploaded. Use this event to update the current file upload progress. @event UploadProgress @param {plupload.Uploader} uploader Uploader instance sending the event. @param {plupload.File} file File that is currently being uploaded. */ /** * Fires just before a chunk is uploaded. This event enables you to override settings * on the uploader instance before the chunk is uploaded. * * @event BeforeChunkUpload * @param {plupload.Uploader} uploader Uploader instance sending the event. * @param {plupload.File} file File to be uploaded. * @param {Object} args POST params to be sent. * @param {Blob} chunkBlob Current blob. * @param {offset} offset Current offset. */ /** Fires when file chunk is uploaded. @event ChunkUploaded @param {plupload.Uploader} uploader Uploader instance sending the event. @param {plupload.File} file File that the chunk was uploaded for. @param {Object} result Object with response properties. @param {Number} result.offset The amount of bytes the server has received so far, including this chunk. @param {Number} result.total The size of the file. @param {String} result.response The response body sent by the server. @param {Number} result.status The HTTP status code sent by the server. @param {String} result.responseHeaders All the response headers as a single string. */ /** Fires when a file is successfully uploaded. @event FileUploaded @param {plupload.Uploader} uploader Uploader instance sending the event. @param {plupload.File} file File that was uploaded. @param {Object} result Object with response properties. @param {String} result.response The response body sent by the server. @param {Number} result.status The HTTP status code sent by the server. @param {String} result.responseHeaders All the response headers as a single string. */ /** Fires when all files in a queue are uploaded. @event UploadComplete @param {plupload.Uploader} uploader Uploader instance sending the event. @param {Array} files Array of file objects that was added to queue/selected by the user. */ /** Fires when a error occurs. @event Error @param {plupload.Uploader} uploader Uploader instance sending the event. @param {Object} error Contains code, message and sometimes file and other details. @param {Number} error.code The plupload error code. @param {String} error.message Description of the error (uses i18n). */ /** Fires when destroy method is called. @event Destroy @param {plupload.Uploader} uploader Uploader instance sending the event. */ var uid = plupload.guid() , settings , files = [] , preferred_caps = {} , fileInputs = [] , fileDrops = [] , startTime , total , disabled = false , xhr ; // Private methods function uploadNext() { var file, count = 0, i; if (this.state == plupload.STARTED) { // Find first QUEUED file for (i = 0; i < files.length; i++) { if (!file && files[i].status == plupload.QUEUED) { file = files[i]; if (this.trigger("BeforeUpload", file)) { file.status = plupload.UPLOADING; this.trigger("UploadFile", file); } } else { count++; } } // All files are DONE or FAILED if (count == files.length) { if (this.state !== plupload.STOPPED) { this.state = plupload.STOPPED; this.trigger("StateChanged"); } this.trigger("UploadComplete", files); } } } function calcFile(file) { file.percent = file.size > 0 ? Math.ceil(file.loaded / file.size * 100) : 100; calc(); } function calc() { var i, file; var loaded; var loadedDuringCurrentSession = 0; // Reset stats total.reset(); // Check status, size, loaded etc on all files for (i = 0; i < files.length; i++) { file = files[i]; if (file.size !== undef) { // We calculate totals based on original file size total.size += file.origSize; // Since we cannot predict file size after resize, we do opposite and // interpolate loaded amount to match magnitude of total loaded = file.loaded * file.origSize / file.size; if (!file.completeTimestamp || file.completeTimestamp > startTime) { loadedDuringCurrentSession += loaded; } total.loaded += loaded; } else { total.size = undef; } if (file.status == plupload.DONE) { total.uploaded++; } else if (file.status == plupload.FAILED) { total.failed++; } else { total.queued++; } } // If we couldn't calculate a total file size then use the number of files to calc percent if (total.size === undef) { total.percent = files.length > 0 ? Math.ceil(total.uploaded / files.length * 100) : 0; } else { total.bytesPerSec = Math.ceil(loadedDuringCurrentSession / ((+new Date() - startTime || 1) / 1000.0)); total.percent = total.size > 0 ? Math.ceil(total.loaded / total.size * 100) : 0; } } function getRUID() { var ctrl = fileInputs[0] || fileDrops[0]; if (ctrl) { return ctrl.getRuntime().uid; } return false; } function runtimeCan(file, cap) { if (file.ruid) { var info = Runtime.getInfo(file.ruid); if (info) { return info.can(cap); } } return false; } function bindEventListeners() { this.bind('FilesAdded FilesRemoved', function(up) { up.trigger('QueueChanged'); up.refresh(); }); this.bind('CancelUpload', onCancelUpload); this.bind('BeforeUpload', onBeforeUpload); this.bind('UploadFile', onUploadFile); this.bind('UploadProgress', onUploadProgress); this.bind('StateChanged', onStateChanged); this.bind('QueueChanged', calc); this.bind('Error', onError); this.bind('FileUploaded', onFileUploaded); this.bind('Destroy', onDestroy); } function initControls(settings, cb) { var self = this, inited = 0, queue = []; // common settings var options = { runtime_order: settings.runtimes, required_caps: settings.required_features, preferred_caps: preferred_caps, swf_url: settings.flash_swf_url, xap_url: settings.silverlight_xap_url }; // add runtime specific options if any plupload.each(settings.runtimes.split(/\s*,\s*/), function(runtime) { if (settings[runtime]) { options[runtime] = settings[runtime]; } }); // initialize file pickers - there can be many if (settings.browse_button) { plupload.each(settings.browse_button, function(el) { queue.push(function(cb) { var fileInput = new o.file.FileInput(plupload.extend({}, options, { accept: settings.filters.mime_types, name: settings.file_data_name, multiple: settings.multi_selection, container: settings.container, browse_button: el })); fileInput.onready = function() { var info = Runtime.getInfo(this.ruid); // for backward compatibility plupload.extend(self.features, { chunks: info.can('slice_blob'), multipart: info.can('send_multipart'), multi_selection: info.can('select_multiple') }); inited++; fileInputs.push(this); cb(); }; fileInput.onchange = function() { self.addFile(this.files); }; fileInput.bind('mouseenter mouseleave mousedown mouseup', function(e) { if (!disabled) { if (settings.browse_button_hover) { if ('mouseenter' === e.type) { plupload.addClass(el, settings.browse_button_hover); } else if ('mouseleave' === e.type) { plupload.removeClass(el, settings.browse_button_hover); } } if (settings.browse_button_active) { if ('mousedown' === e.type) { plupload.addClass(el, settings.browse_button_active); } else if ('mouseup' === e.type) { plupload.removeClass(el, settings.browse_button_active); } } } }); fileInput.bind('mousedown', function() { self.trigger('Browse'); }); fileInput.bind('error runtimeerror', function() { fileInput = null; cb(); }); fileInput.init(); }); }); } // initialize drop zones if (settings.drop_element) { plupload.each(settings.drop_element, function(el) { queue.push(function(cb) { var fileDrop = new o.file.FileDrop(plupload.extend({}, options, { drop_zone: el })); fileDrop.onready = function() { var info = Runtime.getInfo(this.ruid); // for backward compatibility plupload.extend(self.features, { chunks: info.can('slice_blob'), multipart: info.can('send_multipart'), dragdrop: info.can('drag_and_drop') }); inited++; fileDrops.push(this); cb(); }; fileDrop.ondrop = function() { self.addFile(this.files); }; fileDrop.bind('error runtimeerror', function() { fileDrop = null; cb(); }); fileDrop.init(); }); }); } plupload.inSeries(queue, function() { if (typeof(cb) === 'function') { cb(inited); } }); } function resizeImage(blob, params, cb) { var img = new o.image.Image(); try { img.onload = function() { // no manipulation required if... if (params.width > this.width && params.height > this.height && params.quality === undef && params.preserve_headers && !params.crop ) { this.destroy(); return cb(blob); } // otherwise downsize img.downsize(params.width, params.height, params.crop, params.preserve_headers); }; img.onresize = function() { cb(this.getAsBlob(blob.type, params.quality)); this.destroy(); }; img.onerror = function() { cb(blob); }; img.load(blob); } catch(ex) { cb(blob); } } function setOption(option, value, init) { var self = this, reinitRequired = false; function _setOption(option, value, init) { var oldValue = settings[option]; switch (option) { case 'max_file_size': if (option === 'max_file_size') { settings.max_file_size = settings.filters.max_file_size = value; } break; case 'chunk_size': if (value = plupload.parseSize(value)) { settings[option] = value; settings.send_file_name = true; } break; case 'multipart': settings[option] = value; if (!value) { settings.send_file_name = true; } break; case 'http_method': settings[option] = value.toUpperCase() === 'PUT' ? 'PUT' : 'POST'; break; case 'unique_names': settings[option] = value; if (value) { settings.send_file_name = true; } break; case 'filters': // for sake of backward compatibility if (plupload.typeOf(value) === 'array') { value = { mime_types: value }; } if (init) { plupload.extend(settings.filters, value); } else { settings.filters = value; } // if file format filters are being updated, regenerate the matching expressions if (value.mime_types) { if (plupload.typeOf(value.mime_types) === 'string') { value.mime_types = o.core.utils.Mime.mimes2extList(value.mime_types); } value.mime_types.regexp = (function(filters) { var extensionsRegExp = []; plupload.each(filters, function(filter) { plupload.each(filter.extensions.split(/,/), function(ext) { if (/^\s*\*\s*$/.test(ext)) { extensionsRegExp.push('\\.*'); } else { extensionsRegExp.push('\\.' + ext.replace(new RegExp('[' + ('/^$.*+?|()[]{}\\'.replace(/./g, '\\$&')) + ']', 'g'), '\\$&')); } }); }); return new RegExp('(' + extensionsRegExp.join('|') + ')$', 'i'); }(value.mime_types)); settings.filters.mime_types = value.mime_types; } break; case 'resize': if (value) { settings.resize = plupload.extend({ preserve_headers: true, crop: false }, value); } else { settings.resize = false; } break; case 'prevent_duplicates': settings.prevent_duplicates = settings.filters.prevent_duplicates = !!value; break; // options that require reinitialisation case 'container': case 'browse_button': case 'drop_element': value = 'container' === option ? plupload.get(value) : plupload.getAll(value) ; case 'runtimes': case 'multi_selection': case 'flash_swf_url': case 'silverlight_xap_url': settings[option] = value; if (!init) { reinitRequired = true; } break; default: settings[option] = value; } if (!init) { self.trigger('OptionChanged', option, value, oldValue); } } if (typeof(option) === 'object') { plupload.each(option, function(value, option) { _setOption(option, value, init); }); } else { _setOption(option, value, init); } if (init) { // Normalize the list of required capabilities settings.required_features = normalizeCaps(plupload.extend({}, settings)); // Come up with the list of capabilities that can affect default mode in a multi-mode runtimes preferred_caps = normalizeCaps(plupload.extend({}, settings, { required_features: true })); } else if (reinitRequired) { self.trigger('Destroy'); initControls.call(self, settings, function(inited) { if (inited) { self.runtime = Runtime.getInfo(getRUID()).type; self.trigger('Init', { runtime: self.runtime }); self.trigger('PostInit'); } else { self.trigger('Error', { code : plupload.INIT_ERROR, message : plupload.translate('Init error.') }); } }); } } // Internal event handlers function onBeforeUpload(up, file) { // Generate unique target filenames if (up.settings.unique_names) { var matches = file.name.match(/\.([^.]+)$/), ext = "part"; if (matches) { ext = matches[1]; } file.target_name = file.id + '.' + ext; } } function onUploadFile(up, file) { var url = up.settings.url , chunkSize = up.settings.chunk_size , retries = up.settings.max_retries , features = up.features , offset = 0 , blob ; // make sure we start at a predictable offset if (file.loaded) { offset = file.loaded = chunkSize ? chunkSize * Math.floor(file.loaded / chunkSize) : 0; } function handleError() { if (retries-- > 0) { delay(uploadNextChunk, 1000); } else { file.loaded = offset; // reset all progress up.trigger('Error', { code : plupload.HTTP_ERROR, message : plupload.translate('HTTP Error.'), file : file, response : xhr.responseText, status : xhr.status, responseHeaders: xhr.getAllResponseHeaders() }); } } function uploadNextChunk() { var chunkBlob, args = {}, curChunkSize; // make sure that file wasn't cancelled and upload is not stopped in general if (file.status !== plupload.UPLOADING || up.state === plupload.STOPPED) { return; } // send additional 'name' parameter only if required if (up.settings.send_file_name) { args.name = file.target_name || file.name; } if (chunkSize && features.chunks && blob.size > chunkSize) { // blob will be of type string if it was loaded in memory curChunkSize = Math.min(chunkSize, blob.size - offset); chunkBlob = blob.slice(offset, offset + curChunkSize); } else { curChunkSize = blob.size; chunkBlob = blob; } // If chunking is enabled add corresponding args, no matter if file is bigger than chunk or smaller if (chunkSize && features.chunks) { // Setup query string arguments if (up.settings.send_chunk_number) { args.chunk = Math.ceil(offset / chunkSize); args.chunks = Math.ceil(blob.size / chunkSize); } else { // keep support for experimental chunk format, just in case args.offset = offset; args.total = blob.size; } } if (up.trigger('BeforeChunkUpload', file, args, chunkBlob, offset)) { uploadChunk(args, chunkBlob, curChunkSize); } } function uploadChunk(args, chunkBlob, curChunkSize) { var formData; xhr = new o.xhr.XMLHttpRequest(); // Do we have upload progress support if (xhr.upload) { xhr.upload.onprogress = function(e) { file.loaded = Math.min(file.size, offset + e.loaded); up.trigger('UploadProgress', file); }; } xhr.onload = function() { // check if upload made itself through if (xhr.status >= 400) { handleError(); return; } retries = up.settings.max_retries; // reset the counter // Handle chunk response if (curChunkSize < blob.size) { chunkBlob.destroy(); offset += curChunkSize; file.loaded = Math.min(offset, blob.size); up.trigger('ChunkUploaded', file, { offset : file.loaded, total : blob.size, response : xhr.responseText, status : xhr.status, responseHeaders: xhr.getAllResponseHeaders() }); // stock Android browser doesn't fire upload progress events, but in chunking mode we can fake them if (plupload.ua.browser === 'Android Browser') { // doesn't harm in general, but is not required anywhere else up.trigger('UploadProgress', file); } } else { file.loaded = file.size; } chunkBlob = formData = null; // Free memory // Check if file is uploaded if (!offset || offset >= blob.size) { // If file was modified, destory the copy if (file.size != file.origSize) { blob.destroy(); blob = null; } up.trigger('UploadProgress', file); file.status = plupload.DONE; file.completeTimestamp = +new Date(); up.trigger('FileUploaded', file, { response : xhr.responseText, status : xhr.status, responseHeaders: xhr.getAllResponseHeaders() }); } else { // Still chunks left delay(uploadNextChunk, 1); // run detached, otherwise event handlers interfere } }; xhr.onerror = function() { handleError(); }; xhr.onloadend = function() { this.destroy(); xhr = null; }; // Build multipart request if (up.settings.multipart && features.multipart) { xhr.open(up.settings.http_method, url, true); // Set custom headers plupload.each(up.settings.headers, function(value, name) { xhr.setRequestHeader(name, value); }); formData = new o.xhr.FormData(); // Add multipart params plupload.each(plupload.extend(args, up.settings.multipart_params), function(value, name) { formData.append(name, value); }); // Add file and send it formData.append(up.settings.file_data_name, chunkBlob); xhr.send(formData, { runtime_order: up.settings.runtimes, required_caps: up.settings.required_features, preferred_caps: preferred_caps, swf_url: up.settings.flash_swf_url, xap_url: up.settings.silverlight_xap_url }); } else { // if no multipart, send as binary stream url = plupload.buildUrl(up.settings.url, plupload.extend(args, up.settings.multipart_params)); xhr.open(up.settings.http_method, url, true); // Set custom headers plupload.each(up.settings.headers, function(value, name) { xhr.setRequestHeader(name, value); }); // do not set Content-Type, if it was defined previously (see #1203) if (!xhr.hasRequestHeader('Content-Type')) { xhr.setRequestHeader('Content-Type', 'application/octet-stream'); // Binary stream header } xhr.send(chunkBlob, { runtime_order: up.settings.runtimes, required_caps: up.settings.required_features, preferred_caps: preferred_caps, swf_url: up.settings.flash_swf_url, xap_url: up.settings.silverlight_xap_url }); } } blob = file.getSource(); // Start uploading chunks if (!plupload.isEmptyObj(up.settings.resize) && runtimeCan(blob, 'send_binary_string') && plupload.inArray(blob.type, ['image/jpeg', 'image/png']) !== -1) { // Resize if required resizeImage.call(this, blob, up.settings.resize, function(resizedBlob) { blob = resizedBlob; file.size = resizedBlob.size; uploadNextChunk(); }); } else { uploadNextChunk(); } } function onUploadProgress(up, file) { calcFile(file); } function onStateChanged(up) { if (up.state == plupload.STARTED) { // Get start time to calculate bps startTime = (+new Date()); } else if (up.state == plupload.STOPPED) { // Reset currently uploading files for (var i = up.files.length - 1; i >= 0; i--) { if (up.files[i].status == plupload.UPLOADING) { up.files[i].status = plupload.QUEUED; calc(); } } } } function onCancelUpload() { if (xhr) { xhr.abort(); } } function onFileUploaded(up) { calc(); // Upload next file but detach it from the error event // since other custom listeners might want to stop the queue delay(function() { uploadNext.call(up); }, 1); } function onError(up, err) { if (err.code === plupload.INIT_ERROR) { up.destroy(); } // Set failed status if an error occured on a file else if (err.code === plupload.HTTP_ERROR) { err.file.status = plupload.FAILED; err.file.completeTimestamp = +new Date(); calcFile(err.file); // Upload next file but detach it from the error event // since other custom listeners might want to stop the queue if (up.state == plupload.STARTED) { // upload in progress up.trigger('CancelUpload'); delay(function() { uploadNext.call(up); }, 1); } } } function onDestroy(up) { up.stop(); // Purge the queue plupload.each(files, function(file) { file.destroy(); }); files = []; if (fileInputs.length) { plupload.each(fileInputs, function(fileInput) { fileInput.destroy(); }); fileInputs = []; } if (fileDrops.length) { plupload.each(fileDrops, function(fileDrop) { fileDrop.destroy(); }); fileDrops = []; } preferred_caps = {}; disabled = false; startTime = xhr = null; total.reset(); } // Default settings settings = { chunk_size: 0, file_data_name: 'file', filters: { mime_types: [], prevent_duplicates: false, max_file_size: 0 }, flash_swf_url: 'js/Moxie.swf', http_method: 'POST', max_retries: 0, multipart: true, multi_selection: true, resize: false, runtimes: Runtime.order, send_file_name: true, send_chunk_number: true, silverlight_xap_url: 'js/Moxie.xap' }; setOption.call(this, options, null, true); // Inital total state total = new plupload.QueueProgress(); // Add public methods plupload.extend(this, { /** * Unique id for the Uploader instance. * * @property id * @type String */ id : uid, uid : uid, // mOxie uses this to differentiate between event targets /** * Current state of the total uploading progress. This one can either be plupload.STARTED or plupload.STOPPED. * These states are controlled by the stop/start methods. The default value is STOPPED. * * @property state * @type Number */ state : plupload.STOPPED, /** * Map of features that are available for the uploader runtime. Features will be filled * before the init event is called, these features can then be used to alter the UI for the end user. * Some of the current features that might be in this map is: dragdrop, chunks, jpgresize, pngresize. * * @property features * @type Object */ features : {}, /** * Current runtime name. * * @property runtime * @type String */ runtime : null, /** * Current upload queue, an array of File instances. * * @property files * @type Array * @see plupload.File */ files : files, /** * Object with name/value settings. * * @property settings * @type Object */ settings : settings, /** * Total progess information. How many files has been uploaded, total percent etc. * * @property total * @type plupload.QueueProgress */ total : total, /** * Initializes the Uploader instance and adds internal event listeners. * * @method init */ init : function() { var self = this, opt, preinitOpt, err; preinitOpt = self.getOption('preinit'); if (typeof(preinitOpt) == "function") { preinitOpt(self); } else { plupload.each(preinitOpt, function(func, name) { self.bind(name, func); }); } bindEventListeners.call(self); // Check for required options plupload.each(['container', 'browse_button', 'drop_element'], function(el) { if (self.getOption(el) === null) { err = { code : plupload.INIT_ERROR, message : plupload.sprintf(plupload.translate("%s specified, but cannot be found."), el) } return false; } }); if (err) { return self.trigger('Error', err); } if (!settings.browse_button && !settings.drop_element) { return self.trigger('Error', { code : plupload.INIT_ERROR, message : plupload.translate("You must specify either browse_button or drop_element.") }); } initControls.call(self, settings, function(inited) { var initOpt = self.getOption('init'); if (typeof(initOpt) == "function") { initOpt(self); } else { plupload.each(initOpt, function(func, name) { self.bind(name, func); }); } if (inited) { self.runtime = Runtime.getInfo(getRUID()).type; self.trigger('Init', { runtime: self.runtime }); self.trigger('PostInit'); } else { self.trigger('Error', { code : plupload.INIT_ERROR, message : plupload.translate('Init error.') }); } }); }, /** * Set the value for the specified option(s). * * @method setOption * @since 2.1 * @param {String|Object} option Name of the option to change or the set of key/value pairs * @param {Mixed} [value] Value for the option (is ignored, if first argument is object) */ setOption: function(option, value) { setOption.call(this, option, value, !this.runtime); // until runtime not set we do not need to reinitialize }, /** * Get the value for the specified option or the whole configuration, if not specified. * * @method getOption * @since 2.1 * @param {String} [option] Name of the option to get * @return {Mixed} Value for the option or the whole set */ getOption: function(option) { if (!option) { return settings; } return settings[option]; }, /** * Refreshes the upload instance by dispatching out a refresh event to all runtimes. * This would for example reposition flash/silverlight shims on the page. * * @method refresh */ refresh : function() { if (fileInputs.length) { plupload.each(fileInputs, function(fileInput) { fileInput.trigger('Refresh'); }); } this.trigger('Refresh'); }, /** * Starts uploading the queued files. * * @method start */ start : function() { if (this.state != plupload.STARTED) { this.state = plupload.STARTED; this.trigger('StateChanged'); uploadNext.call(this); } }, /** * Stops the upload of the queued files. * * @method stop */ stop : function() { if (this.state != plupload.STOPPED) { this.state = plupload.STOPPED; this.trigger('StateChanged'); this.trigger('CancelUpload'); } }, /** * Disables/enables browse button on request. * * @method disableBrowse * @param {Boolean} disable Whether to disable or enable (default: true) */ disableBrowse : function() { disabled = arguments[0] !== undef ? arguments[0] : true; if (fileInputs.length) { plupload.each(fileInputs, function(fileInput) { fileInput.disable(disabled); }); } this.trigger('DisableBrowse', disabled); }, /** * Returns the specified file object by id. * * @method getFile * @param {String} id File id to look for. * @return {plupload.File} File object or undefined if it wasn't found; */ getFile : function(id) { var i; for (i = files.length - 1; i >= 0; i--) { if (files[i].id === id) { return files[i]; } } }, /** * Adds file to the queue programmatically. Can be native file, instance of Plupload.File, * instance of mOxie.File, input[type="file"] element, or array of these. Fires FilesAdded, * if any files were added to the queue. Otherwise nothing happens. * * @method addFile * @since 2.0 * @param {plupload.File|mOxie.File|File|Node|Array} file File or files to add to the queue. * @param {String} [fileName] If specified, will be used as a name for the file */ addFile : function(file, fileName) { var self = this , queue = [] , filesAdded = [] , ruid ; function filterFile(file, cb) { var queue = []; plupload.each(self.settings.filters, function(rule, name) { if (fileFilters[name]) { queue.push(function(cb) { fileFilters[name].call(self, rule, file, function(res) { cb(!res); }); }); } }); plupload.inSeries(queue, cb); } /** * @method resolveFile * @private * @param {moxie.file.File|moxie.file.Blob|plupload.File|File|Blob|input[type="file"]} file */ function resolveFile(file) { var type = plupload.typeOf(file); // moxie.file.File if (file instanceof o.file.File) { if (!file.ruid && !file.isDetached()) { if (!ruid) { // weird case return false; } file.ruid = ruid; file.connectRuntime(ruid); } resolveFile(new plupload.File(file)); } // moxie.file.Blob else if (file instanceof o.file.Blob) { resolveFile(file.getSource()); file.destroy(); } // plupload.File - final step for other branches else if (file instanceof plupload.File) { if (fileName) { file.name = fileName; } queue.push(function(cb) { // run through the internal and user-defined filters, if any filterFile(file, function(err) { if (!err) { // make files available for the filters by updating the main queue directly files.push(file); // collect the files that will be passed to FilesAdded event filesAdded.push(file); self.trigger("FileFiltered", file); } delay(cb, 1); // do not build up recursions or eventually we might hit the limits }); }); } // native File or blob else if (plupload.inArray(type, ['file', 'blob']) !== -1) { resolveFile(new o.file.File(null, file)); } // input[type="file"] else if (type === 'node' && plupload.typeOf(file.files) === 'filelist') { // if we are dealing with input[type="file"] plupload.each(file.files, resolveFile); } // mixed array of any supported types (see above) else if (type === 'array') { fileName = null; // should never happen, but unset anyway to avoid funny situations plupload.each(file, resolveFile); } } ruid = getRUID(); resolveFile(file); if (queue.length) { plupload.inSeries(queue, function() { // if any files left after filtration, trigger FilesAdded if (filesAdded.length) { self.trigger("FilesAdded", filesAdded); } }); } }, /** * Removes a specific file. * * @method removeFile * @param {plupload.File|String} file File to remove from queue. */ removeFile : function(file) { var id = typeof(file) === 'string' ? file : file.id; for (var i = files.length - 1; i >= 0; i--) { if (files[i].id === id) { return this.splice(i, 1)[0]; } } }, /** * Removes part of the queue and returns the files removed. This will also trigger the FilesRemoved and QueueChanged events. * * @method splice * @param {Number} start (Optional) Start index to remove from. * @param {Number} length (Optional) Lengh of items to remove. * @return {Array} Array of files that was removed. */ splice : function(start, length) { // Splice and trigger events var removed = files.splice(start === undef ? 0 : start, length === undef ? files.length : length); // if upload is in progress we need to stop it and restart after files are removed var restartRequired = false; if (this.state == plupload.STARTED) { // upload in progress plupload.each(removed, function(file) { if (file.status === plupload.UPLOADING) { restartRequired = true; // do not restart, unless file that is being removed is uploading return false; } }); if (restartRequired) { this.stop(); } } this.trigger("FilesRemoved", removed); // Dispose any resources allocated by those files plupload.each(removed, function(file) { file.destroy(); }); if (restartRequired) { this.start(); } return removed; }, /** Dispatches the specified event name and its arguments to all listeners. @method trigger @param {String} name Event name to fire. @param {Object..} Multiple arguments to pass along to the listener functions. */ // override the parent method to match Plupload-like event logic dispatchEvent: function(type) { var list, args, result; type = type.toLowerCase(); list = this.hasEventListener(type); if (list) { // sort event list by priority list.sort(function(a, b) { return b.priority - a.priority; }); // first argument should be current plupload.Uploader instance args = [].slice.call(arguments); args.shift(); args.unshift(this); for (var i = 0; i < list.length; i++) { // Fire event, break chain if false is returned if (list[i].fn.apply(list[i].scope, args) === false) { return false; } } } return true; }, /** Check whether uploader has any listeners to the specified event. @method hasEventListener @param {String} name Event name to check for. */ /** Adds an event listener by name. @method bind @param {String} name Event name to listen for. @param {function} fn Function to call ones the event gets fired. @param {Object} [scope] Optional scope to execute the specified function in. @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first */ bind: function(name, fn, scope, priority) { // adapt moxie EventTarget style to Plupload-like plupload.Uploader.prototype.bind.call(this, name, fn, priority, scope); }, /** Removes the specified event listener. @method unbind @param {String} name Name of event to remove. @param {function} fn Function to remove from listener. */ /** Removes all event listeners. @method unbindAll */ /** * Destroys Plupload instance and cleans after itself. * * @method destroy */ destroy : function() { this.trigger('Destroy'); settings = total = null; // purge these exclusively this.unbindAll(); } }); }; plupload.Uploader.prototype = o.core.EventTarget.instance; /** * Constructs a new file instance. * * @class File * @constructor * * @param {Object} file Object containing file properties * @param {String} file.name Name of the file. * @param {Number} file.size File size. */ plupload.File = (function() { var filepool = {}; function PluploadFile(file) { plupload.extend(this, { /** * File id this is a globally unique id for the specific file. * * @property id * @type String */ id: plupload.guid(), /** * File name for example "myfile.gif". * * @property name * @type String */ name: file.name || file.fileName, /** * File type, `e.g image/jpeg` * * @property type * @type String */ type: file.type || '', /** * File size in bytes (may change after client-side manupilation). * * @property size * @type Number */ size: file.size || file.fileSize, /** * Original file size in bytes. * * @property origSize * @type Number */ origSize: file.size || file.fileSize, /** * Number of bytes uploaded of the files total size. * * @property loaded * @type Number */ loaded: 0, /** * Number of percentage uploaded of the file. * * @property percent * @type Number */ percent: 0, /** * Status constant matching the plupload states QUEUED, UPLOADING, FAILED, DONE. * * @property status * @type Number * @see plupload */ status: plupload.QUEUED, /** * Date of last modification. * * @property lastModifiedDate * @type {String} */ lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString(), // Thu Aug 23 2012 19:40:00 GMT+0400 (GET) /** * Set when file becomes plupload.DONE or plupload.FAILED. Is used to calculate proper plupload.QueueProgress.bytesPerSec. * @private * @property completeTimestamp * @type {Number} */ completeTimestamp: 0, /** * Returns native window.File object, when it's available. * * @method getNative * @return {window.File} or null, if plupload.File is of different origin */ getNative: function() { var file = this.getSource().getSource(); return plupload.inArray(plupload.typeOf(file), ['blob', 'file']) !== -1 ? file : null; }, /** * Returns mOxie.File - unified wrapper object that can be used across runtimes. * * @method getSource * @return {mOxie.File} or null */ getSource: function() { if (!filepool[this.id]) { return null; } return filepool[this.id]; }, /** * Destroys plupload.File object. * * @method destroy */ destroy: function() { var src = this.getSource(); if (src) { src.destroy(); delete filepool[this.id]; } } }); filepool[this.id] = file; } return PluploadFile; }()); /** * Constructs a queue progress. * * @class QueueProgress * @constructor */ plupload.QueueProgress = function() { var self = this; // Setup alias for self to reduce code size when it's compressed /** * Total queue file size. * * @property size * @type Number */ self.size = 0; /** * Total bytes uploaded. * * @property loaded * @type Number */ self.loaded = 0; /** * Number of files uploaded. * * @property uploaded * @type Number */ self.uploaded = 0; /** * Number of files failed to upload. * * @property failed * @type Number */ self.failed = 0; /** * Number of files yet to be uploaded. * * @property queued * @type Number */ self.queued = 0; /** * Total percent of the uploaded bytes. * * @property percent * @type Number */ self.percent = 0; /** * Bytes uploaded per second. * * @property bytesPerSec * @type Number */ self.bytesPerSec = 0; /** * Resets the progress to its initial values. * * @method reset */ self.reset = function() { self.size = self.loaded = self.uploaded = self.failed = self.queued = self.percent = self.bytesPerSec = 0; }; }; exports.plupload = plupload; }(this, moxie)); }));
/*! * inferno-dom v0.5.14 * (c) 2016 Dominic Gannaway * Released under the MPL-2.0 License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.InfernoDOM = factory()); }(this, function () { 'use strict'; var babelHelpers_typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var babelHelpers_extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var recyclingEnabled$1 = true; function pool(item) { var key = item.key; var tree = item.tree.dom; if (key === null) { tree.pool.push(item); } else { var keyedPool = tree.keyedPool; // TODO rename (keyedPool[key] || (keyedPool[key] = [])).push(item); } } function recycle(tree, item, treeLifecycle, context) { // TODO use depth as key var key = item.key; var recyclableItem = undefined; // TODO faster to check pool size first? if (key !== null) { var keyPool = tree.keyedPool[key]; recyclableItem = keyPool && keyPool.pop(); } else { recyclableItem = tree.pool.pop(); } if (recyclableItem) { tree.update(recyclableItem, item, treeLifecycle, context); return item.rootNode; } } function isRecyclingEnabled() { return recyclingEnabled$1; } var isVoid = (function (x) { return x === null || x === undefined; }) var isStringOrNumber = (function (x) { return typeof x === 'string' || typeof x === 'number'; }) // To be compat with React, we support at least the same SVG elements function isSVGElement(nodeName) { return nodeName === 'svg' || nodeName === 'clipPath' || nodeName === 'circle' || nodeName === 'defs' || nodeName === 'desc' || nodeName === 'ellipse' || nodeName === 'filter' || nodeName === 'g' || nodeName === 'line' || nodeName === 'linearGradient' || nodeName === 'mask' || nodeName === 'marker' || nodeName === 'metadata' || nodeName === 'mpath' || nodeName === 'path' || nodeName === 'pattern' || nodeName === 'polygon' || nodeName === 'polyline' || nodeName === 'pattern' || nodeName === 'radialGradient' || nodeName === 'rect' || nodeName === 'set' || nodeName === 'stop' || nodeName === 'symbol' || nodeName === 'switch' || nodeName === 'text' || nodeName === 'tspan' || nodeName === 'use' || nodeName === 'view'; } function isMathMLElement(nodeName) { return nodeName === 'mo' || nodeName === 'mover' || nodeName === 'mn' || nodeName === 'maction' || nodeName === 'menclose' || nodeName === 'merror' || nodeName === 'mfrac' || nodeName === 'mi' || nodeName === 'mmultiscripts' || nodeName === 'mpadded' || nodeName === 'mphantom' || nodeName === 'mroot' || nodeName === 'mrow' || nodeName === 'ms' || nodeName === 'mtd' || nodeName === 'mtable' || nodeName === 'munder' || nodeName === 'msub' || nodeName === 'msup' || nodeName === 'msubsup' || nodeName === 'mtr' || nodeName === 'mtext'; } var isArray = (function (x) { return x.constructor === Array; }) var ObjectTypes = { VARIABLE: 1 }; var ValueTypes = { TEXT: 0, ARRAY: 1, TREE: 2, EMPTY_OBJECT: 3, FUNCTION: 4, FRAGMENT: 5 }; function getValueWithIndex(item, index) { return index < 2 ? index === 0 ? item.v0 : item.v1 : item.values[index - 2]; } function getTypeFromValue(value) { if (isStringOrNumber(value) || isVoid(value)) { return ValueTypes.TEXT; } else if (isArray(value)) { return ValueTypes.ARRAY; } else if ((typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value)) === 'object' && value.create) { return ValueTypes.TREE; } else if ((typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value)) === 'object' && Object.keys(value).length === 0) { return ValueTypes.EMPTY_OBJECT; } else if ((typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value)) === 'object' && value.tree.dom) { return ValueTypes.FRAGMENT; } else if (typeof value === 'function') { return ValueTypes.FUNCTION; } } function getValueForProps(props, item) { var newProps = {}; if (props.index) { return getValueWithIndex(item, props.index); } for (var name in props) { var val = props[name]; if (val && val.index) { newProps[name] = getValueWithIndex(item, val.index); } else { newProps[name] = val; } if (name === 'children') { newProps[name].overrideItem = item; } } return newProps; } function removeValueTree(value, treeLifecycle) { if (isVoid(value)) { return; } if (isArray(value)) { for (var i = 0; i < value.length; i++) { var child = value[i]; removeValueTree(child, treeLifecycle); } } else if ((typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value)) === 'object') { var tree = value.tree; tree.dom.remove(value, treeLifecycle); } } var canUseDOM = !!(typeof window !== 'undefined' && // Nwjs doesn't add document as a global in their node context, but does have it on window.document, // As a workaround, check if document is undefined typeof document !== 'undefined' && window.document.createElement); var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!window.addEventListener, canUseViewport: canUseDOM && !!window.screen, canUseSymbol: typeof Symbol === 'function' && typeof Symbol['for'] === 'function' }; var isSVG = undefined; if (ExecutionEnvironment.canUseDOM) { var _document = document; var implementation = _document.implementation; isSVG = implementation && implementation.hasFeature && implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1'); } var isSVG$1 = isSVG; function inArray(arr, item) { var len = arr.length; var i = 0; while (i < len) { if (arr[i++] === item) { return true; } } return false; } var noop = (function () {}) var HOOK = {}; var reDash = /\-./g; /* eslint-disable quote-props */ var unitlessProperties = { 'animation-iteration-count': true, 'box-flex': true, 'box-flex-group': true, 'column-count': true, 'counter-increment': true, 'fill-opacity': true, 'flex': true, 'flex-grow': true, 'flex-order': true, 'flex-positive': true, 'flex-shrink': true, 'float': true, 'font-weight': true, 'grid-column': true, 'line-height': true, 'line-clamp': true, 'opacity': true, 'order': true, 'orphans': true, 'stop-opacity': true, 'stroke-dashoffset': true, 'stroke-opacity': true, 'stroke-width': true, 'tab-size': true, 'transform': true, 'transform-origin': true, 'widows': true, 'z-index': true, 'zoom': true }; /* eslint-enable quote-props */ var directions = ['Top', 'Right', 'Bottom', 'Left']; var dirMap = function dirMap(prefix, postfix) { return directions.map(function (dir) { return (prefix || '') + dir + (postfix || ''); }); }; var shortCuts = { // rely on cssText font: [/* font-style font-variant font-weight font-size/line-height font-family|caption|icon|menu|message-box|small-caption|status-bar|initial|inherit; */], padding: dirMap('padding'), margin: dirMap('margin'), 'border-width': dirMap('border', 'Width'), 'border-style': dirMap('border', 'Style') }; var cssToJSName = function cssToJSName(cssName) { return cssName.replace(reDash, function (str) { return str[1].toUpperCase(); }); }; // Don't execute this in nodejS if (ExecutionEnvironment.canUseDOM) { (function () { // get browser supported CSS properties var documentElement = document.documentElement; var computed = window.getComputedStyle(documentElement); var props = Array.prototype.slice.call(computed, 0); for (var key in documentElement.style) { if (!computed[key]) { props.push(key); } } props.forEach(function (propName) { var prefix = propName[0] === '-' ? propName.substr(1, propName.indexOf('-', 1) - 1) : null; var stylePropName = cssToJSName(propName); HOOK[stylePropName] = { unPrefixed: prefix ? propName.substr(prefix.length + 2) : propName, unitless: unitlessProperties[propName] ? true : false, shorthand: null }; }); var lenMap = { 1: function _(values, props, style) { return props.forEach(function (prop) { return style[prop] = values[0]; }); }, 2: function _(values, props, style) { return values.forEach(function (value, index) { style[props[index]] = style[props[index + 2]] = value; }); }, 4: function _(values, props, style) { return props.forEach(function (prop, index) { style[prop] = values[index]; }); } }; // normalize property shortcuts Object.keys(shortCuts).forEach(function (propName) { var stylePropName = cssToJSName(propName); HOOK[stylePropName] = { unPrefixed: propName, unitless: false, shorthand: function shorthand(value, style) { var type = typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value); if (type === 'number') { value += 'px'; } if (!value) { return; } if ('cssText' in style) { // normalize setting complex property across browsers style.cssText += ';' + propName + ':' + value; } else { var values = value.split(' '); (lenMap[values.length] || noop)(values, shortCuts[propName], style); } } }; }); })(); } /* eslint eqeqeq:0 */ function isValidAttribute(strings) { var i = 0; var character = undefined; while (i <= strings.length) { character = strings[i]; if (!isNaN(character * 1)) { return false; } else { if (character == character.toUpperCase()) { return false; } if (character === character.toLowerCase()) { return true; } } i++; } return false; } /** * DOM registry * */ var PROPERTY = 0x1; var BOOLEAN = 0x2; var NUMERIC_VALUE = 0x4; var POSITIVE_NUMERIC_VALUE = 0x6 | 0x4; var xlink = 'http://www.w3.org/1999/xlink'; var xml = 'http://www.w3.org/XML/1998/namespace'; var DOMAttributeNamespaces = { // None-JSX compat 'xlink:actuate': xlink, 'xlink:arcrole': xlink, 'xlink:href': xlink, 'xlink:role': xlink, 'xlink:show': xlink, 'xlink:title': xlink, 'xlink:type': xlink, 'xml:base': xml, 'xml:lang': xml, 'xml:space': xml, // JSX compat xlinkActuate: xlink, xlinkArcrole: xlink, xlinkHref: xlink, xlinkRole: xlink, xlinkShow: xlink, xlinkTitle: xlink, xlinkType: xlink }; var DOMAttributeNames = { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv', // SVG clipPath: 'clip-path', fillOpacity: 'fill-opacity', fontFamily: 'font-family', fontSize: 'font-size', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strokeDasharray: 'stroke-dasharray', strokeLinecap: 'stroke-linecap', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', viewBox: 'viewBox', // Edge case. The letter 'b' need to be uppercase // JSX compat xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlLang: 'xml:lang', xmlSpace: 'xml:space' }; var DOMPropertyNames = { autoComplete: 'autocomplete', autoFocus: 'autofocus', autoSave: 'autosave' }; // This 'whitelist' contains edge cases such as attributes // that should be seen as a property or boolean property. // ONLY EDIT THIS IF YOU KNOW WHAT YOU ARE DOING!! var Whitelist = { allowFullScreen: BOOLEAN, async: BOOLEAN, autoFocus: BOOLEAN, autoPlay: BOOLEAN, capture: BOOLEAN, checked: PROPERTY | BOOLEAN, controls: BOOLEAN, currentTime: PROPERTY | POSITIVE_NUMERIC_VALUE, default: BOOLEAN, defaultChecked: BOOLEAN, defaultMuted: BOOLEAN, defaultSelected: BOOLEAN, defer: BOOLEAN, disabled: PROPERTY | BOOLEAN, download: BOOLEAN, enabled: BOOLEAN, formNoValidate: BOOLEAN, hidden: PROPERTY | BOOLEAN, // 3.2.5 - Global attributes loop: BOOLEAN, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: PROPERTY | BOOLEAN, muted: PROPERTY | BOOLEAN, mediaGroup: PROPERTY, noValidate: BOOLEAN, noShade: PROPERTY | BOOLEAN, noResize: BOOLEAN, noWrap: BOOLEAN, typeMustMatch: BOOLEAN, open: BOOLEAN, paused: PROPERTY, playbackRate: PROPERTY | NUMERIC_VALUE, readOnly: BOOLEAN, required: PROPERTY | BOOLEAN, reversed: BOOLEAN, radioGroup: PROPERTY, icon: PROPERTY, draggable: BOOLEAN, // 3.2.5 - Global attributes dropzone: null, // 3.2.5 - Global attributes scoped: PROPERTY | BOOLEAN, visible: BOOLEAN, trueSpeed: BOOLEAN, sandbox: null, sortable: BOOLEAN, inert: BOOLEAN, indeterminate: BOOLEAN, nohref: BOOLEAN, compact: BOOLEAN, declare: BOOLEAN, ismap: PROPERTY | BOOLEAN, pauseOnExit: PROPERTY | BOOLEAN, seamless: BOOLEAN, translate: BOOLEAN, // 3.2.5 - Global attributes selected: PROPERTY | BOOLEAN, srcLang: PROPERTY, srcObject: PROPERTY, value: PROPERTY, volume: PROPERTY | POSITIVE_NUMERIC_VALUE, itemScope: BOOLEAN, // 3.2.5 - Global attributes className: null, tabindex: PROPERTY | NUMERIC_VALUE, /** * React compat for non-working JSX namespace support */ xlinkActuate: null, xlinkArcrole: null, xlinkHref: null, xlinkRole: null, xlinkShow: null, xlinkTitle: null, xlinkType: null, xmlBase: null, xmlLang: null, xmlSpace: null, /** * SVG */ clipPath: null, fillOpacity: null, fontFamily: null, fontSize: null, markerEnd: null, markerMid: null, markerStart: null, stopColor: null, stopOpacity: null, strokeDasharray: null, strokeLinecap: null, strokeOpacity: null, strokeWidth: null, textAnchor: null, /** * Numeric attributes */ cols: POSITIVE_NUMERIC_VALUE, rows: NUMERIC_VALUE, rowspan: NUMERIC_VALUE, size: POSITIVE_NUMERIC_VALUE, sizes: NUMERIC_VALUE, start: NUMERIC_VALUE, /** * Namespace attributes */ 'xlink:actuate': null, 'xlink:arcrole': null, 'xlink:href': null, 'xlink:role': null, 'xlink:show': null, 'xlink:title': null, 'xlink:type': null, 'xml:base': null, 'xml:lang': null, 'xml:space': null, /** * 3.2.5 - Global attributes */ id: null, dir: null, title: null, /** * Properties that MUST be set as attributes, due to: * * - browser bug * - strange spec outlier * * Nothing bad with this. This properties get a performance boost * compared to custom attributes because they are skipping the * validation check. */ // Force 'autocorrect' and 'autoCapitalize' to be set as an attribute // to fix issues with Mobile Safari on iOS devices autocorrect: null, // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: null, // Some version of IE (like IE9) actually throw an exception // if you set input.type = 'something-unknown' type: null, /** * Form */ form: null, formAction: null, formEncType: null, formMethod: null, formTarget: null, frameBorder: null, /** * Internet Explorer / Edge */ // IE-only attribute that controls focus behavior unselectable: null, /** * Firefox */ continuous: BOOLEAN, /** * Others */ srcSet: null, inlist: null, minLength: null, marginWidth: null, marginHeight: null, list: null, keyType: null, is: null, inputMode: null, height: null, width: null, dateTime: null, contenteditable: null, // 3.2.5 - Global attributes contextMenu: null, classID: null, cellPadding: null, cellSpacing: null, charSet: null, allowTransparency: null, spellcheck: null, // 3.2.5 - Global attributes srcDoc: PROPERTY }; var HTMLPropsContainer = {}; function checkBitmask(value, bitmask) { return bitmask !== null && (value & bitmask) === bitmask; } for (var propName in Whitelist) { var propConfig = Whitelist[propName]; HTMLPropsContainer[propName] = { attributeName: DOMAttributeNames[propName] || propName.toLowerCase(), attributeNamespace: DOMAttributeNamespaces[propName] ? DOMAttributeNamespaces[propName] : null, propertyName: DOMPropertyNames[propName] || propName, mustUseProperty: checkBitmask(propConfig, PROPERTY), hasBooleanValue: checkBitmask(propConfig, BOOLEAN), hasNumericValue: checkBitmask(propConfig, NUMERIC_VALUE), hasPositiveNumericValue: checkBitmask(propConfig, POSITIVE_NUMERIC_VALUE) }; } var template = { /** * Sets the value for a property on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setProperty: function setProperty(vNode, domNode, name, value, useProperties) { var propertyInfo = HTMLPropsContainer[name] || null; if (propertyInfo) { if (isVoid(value) || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && value !== value || propertyInfo.hasPositiveNumericValue && value < 1 || value.length === 0) { template.removeProperty(vNode, domNode, name, useProperties); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propName === 'value' && (!isVoid(vNode) && vNode.tag === 'select' || domNode.tagName === 'SELECT')) { template.setSelectValueForProperty(vNode, domNode, value, useProperties); } else if (useProperties) { if ('' + domNode[propName] !== '' + value) { domNode[propName] = value; } } else { if (propertyInfo.hasBooleanValue && (value === true || value === 'true')) { value = propName; } domNode.setAttribute(propName, value); } } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; if (namespace) { domNode.setAttributeNS(namespace, attributeName, '' + value); } else { // if 'truthy' value, and boolean, it will be 'propName=propName' if (propertyInfo.hasBooleanValue && value === true) { value = attributeName; } domNode.setAttribute(attributeName, '' + value); } } } else { if (isValidAttribute(name)) { if (isVoid(value)) { domNode.removeAttribute(name); } else if (name) { domNode.setAttribute(name, value); } } } }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {vNode} virtual node * @param {DOMElement} node * @param {object} styles */ setCSS: function setCSS(vNode, domNode, styles, useProperties) { for (var styleName in styles) { var styleValue = styles[styleName]; var style = domNode.style; if (isVoid(styleValue) || typeof styleValue === 'boolean') { // Todo! Should we check for typeof boolean? style[styleName] = ''; } else { // The 'hook' contains all browser supported CSS properties. // No 'custom-css' are allowed or will work. var hook = HOOK[styleName]; if (hook) { if (hook.shorthand) { hook.shorthand(styleValue, style); } else { if (!hook.unitless) { if (typeof styleValue !== 'string') { styleValue = styleValue + 'px'; } } style[hook.unPrefixed] = styleValue; } } } } }, /** * Removes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ removeProperty: function removeProperty(vNode, domNode, name, useProperties) { var propertyInfo = HTMLPropsContainer[name]; if (propertyInfo) { if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; // Make sure we remove select / select multiiple properly if (name === 'value' && (vNode !== null && vNode.tag === 'select' || domNode.tagName === 'SELECT')) { template.removeSelectValueForProperty(vNode, domNode); } else { if (useProperties) { if (propertyInfo.hasBooleanValue) { domNode[propName] = false; } else if ('' + domNode[propName] !== '') { domNode[propName] = ''; } } else { domNode.removeAttribute(propName); } } } else { domNode.removeAttribute(propertyInfo.attributeName); } } else { // HTML attributes and custom attributes domNode.removeAttribute(name); } }, /** * Set the value for a select / select multiple on a node. * * @param {DOMElement} node * @param {string} name */ setSelectValueForProperty: function setSelectValueForProperty(vNode, domNode, value, useProperties) { var isMultiple = isArray(value); var options = domNode.options; var len = options.length; value = typeof value === 'number' ? '' + value : value; var i = 0, optionNode = undefined; while (i < len) { optionNode = options[i++]; if (useProperties) { optionNode.selected = !isVoid(value) && (isMultiple ? inArray(value, optionNode.value) : optionNode.value === value); } else { if (!isVoid(value) && (isMultiple ? inArray(value, optionNode.value) : optionNode.value === value)) { optionNode.setAttribute('selected', 'selected'); } else { optionNode.removeAttribute('selected'); } } } }, removeSelectValueForProperty: function removeSelectValueForProperty(vNode, domNode /* , propName */) { var options = domNode.options; var len = options.length; var i = 0; while (i < len) { options[i++].selected = false; } } }; var standardNativeEventMapping = { onBlur: 'blur', onChange: 'change', onClick: 'click', onCompositionEnd: 'compositionend', onCompositionStart: 'compositionstart', onCompositionUpdate: 'compositionupdate', onContextMenu: 'contextmenu', onCopy: 'copy', onCut: 'cut', onDoubleClick: 'dblclick', onDrag: 'drag', onDragEnd: 'dragend', onDragEnter: 'dragenter', onDragExit: 'dragexit', onDragLeave: 'dragleave', onDragOver: 'dragover', onDragStart: 'dragstart', onDrop: 'drop', onFocus: 'focus', onFocusIn: 'focusin', onFocusOut: 'focusout', onInput: 'input', onKeyDown: 'keydown', onKeyPress: 'keypress', onKeyUp: 'keyup', onMouseDown: 'mousedown', onMouseMove: 'mousemove', onMouseOut: 'mouseout', onMouseOver: 'mouseover', onMouseUp: 'mouseup', onMouseWheel: 'mousewheel', onPaste: 'paste', onReset: 'reset', onSelect: 'select', onSelectionChange: 'selectionchange', onSelectStart: 'selectstart', onShow: 'show', onSubmit: 'submit', onTextInput: 'textInput', onTouchCancel: 'touchcancel', onTouchEnd: 'touchend', onTouchMove: 'touchmove', onTouchStart: 'touchstart', onWheel: 'wheel' }; var nonBubbleableEventMapping = { onAbort: 'abort', onBeforeUnload: 'beforeunload', onCanPlay: 'canplay', onCanPlayThrough: 'canplaythrough', onDurationChange: 'durationchange', onEmptied: 'emptied', onEnded: 'ended', onError: 'error', onInput: 'input', onInvalid: 'invalid', onLoad: 'load', onLoadedData: 'loadeddata', onLoadedMetadata: 'loadedmetadata', onLoadStart: 'loadstart', onMouseEnter: 'mouseenter', onMouseLeave: 'mouseleave', onOrientationChange: 'orientationchange', onPause: 'pause', onPlay: 'play', onPlaying: 'playing', onProgress: 'progress', onRateChange: 'ratechange', onResize: 'resize', onScroll: 'scroll', onSeeked: 'seeked', onSeeking: 'seeking', onSelect: 'select', onStalled: 'stalled', onSuspend: 'suspend', onTimeUpdate: 'timeupdate', onUnload: 'unload', onVolumeChange: 'volumechange', onWaiting: 'waiting' }; var propertyToEventType = {}; [standardNativeEventMapping, nonBubbleableEventMapping].forEach(function (mapping) { Object.keys(mapping).reduce(function (state, property) { state[property] = mapping[property]; return state; }, propertyToEventType); }); var INFERNO_PROP = '__Inferno__id__'; var counter = 1; function infernoNodeID(node, get) { return node[INFERNO_PROP] || (get ? 0 : node[INFERNO_PROP] = counter++); } /** * Internal store for event listeners * DOMNodeId -> type -> listener */ var listenersStorage = {}; var focusEvents = { focus: 'focusin', // DOM L3 blur: 'focusout' // DOM L3 }; var eventHooks = {}; /** * Creates a wrapped handler that hooks into the Inferno * eventHooks system based on the type of event being * attached. * * @param {string} type * @param {Function} handler * @return {Function} wrapped handler */ function setHandler(type, handler) { var hook = eventHooks[type]; if (hook) { var hooked = hook(handler); hooked.originalHandler = handler; return hooked; } return { handler: handler, originalHandler: handler }; } var standardNativeEvents = Object.keys(standardNativeEventMapping).map(function (key) { return standardNativeEventMapping[key]; }); var nonBubbleableEvents = Object.keys(nonBubbleableEventMapping).map(function (key) { return nonBubbleableEventMapping[key]; }); var EventRegistry = {}; function getFocusBlur(nativeFocus) { if (typeof getFocusBlur.fn === 'undefined') { getFocusBlur.fn = nativeFocus ? function () { var _type = this._type; var handler = setHandler(_type, function (e) { addRootListener(e, _type); }).handler; document.addEventListener(focusEvents[_type], handler); } : function () { var _type = this._type; document.addEventListener(_type, setHandler(_type, addRootListener).handler, true); }; } return getFocusBlur.fn; } if (ExecutionEnvironment.canUseDOM) { var i = 0; var type = undefined; var nativeFocus = 'onfocusin' in document.documentElement; for (; i < standardNativeEvents.length; i++) { type = standardNativeEvents[i]; EventRegistry[type] = { _type: type, _bubbles: true, _counter: 0, _enabled: false }; // 'focus' and 'blur' if (focusEvents[type]) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html EventRegistry[type]._focusBlur = getFocusBlur(nativeFocus); } } // For non-bubbleable events - e.g. scroll - we are setting the events directly on the node for (i = 0; i < nonBubbleableEvents.length; i++) { type = nonBubbleableEvents[i]; EventRegistry[type] = { _type: type, _bubbles: false, _enabled: false }; } } /* eslint no-invalid-this:0 */ function stopPropagation() { this._isPropagationStopped = true; if (this._stopPropagation) { this._stopPropagation(); } else { this.cancelBubble = true; } } function isPropagationStopped() { return this._isPropagationStopped; } function stopImmediatePropagation() { this._isImmediatePropagationStopped = true; this._isPropagationStopped = true; if (this._stopImmediatePropagation) { this._stopImmediatePropagation(); } else { this.cancelBubble = true; } } function isImmediatePropagationStopped() { return this._isImmediatePropagationStopped; } function preventDefault() { this._isDefaultPrevented = true; if (this._preventDefault) { this._preventDefault(); } else { this.returnValue = false; } } function isDefaultPrevented() { return this._isDefaultPrevented; } function eventInterface(nativeEvent) { // Extend nativeEvent nativeEvent._stopPropagation = nativeEvent.stopPropagation; nativeEvent.stopPropagation = stopPropagation; nativeEvent.isPropagationStopped = isPropagationStopped; nativeEvent._stopImmediatePropagation = nativeEvent.stopImmediatePropagation; nativeEvent.stopImmediatePropagation = stopImmediatePropagation; nativeEvent.isImmediatePropagationStopped = isImmediatePropagationStopped; nativeEvent._preventDefault = nativeEvent.preventDefault; nativeEvent.preventDefault = preventDefault; nativeEvent.isDefaultPrevented = isDefaultPrevented; return nativeEvent; } function isFormElement(nodeName) { return nodeName === 'form' || nodeName === 'input' || nodeName === 'textarea' || nodeName === 'label' || nodeName === 'fieldset' || nodeName === 'legend' || nodeName === 'select' || nodeName === 'optgroup' || nodeName === 'option' || nodeName === 'button' || nodeName === 'datalist' || nodeName === 'keygen' || nodeName === 'output'; } function getFormElementType(node) { var name = node.nodeName.toLowerCase(); if (name !== 'input') { if (name === 'select' && node.multiple) { return 'select-multiple'; } return name; } var type = node.getAttribute('type'); if (!type) { return 'text'; } return type.toLowerCase(); } function selectValues(node) { var result = []; var index = node.selectedIndex; var options = node.options; var length = options.length; var option = undefined; var i = index < 0 ? length : 0; for (; i < length; i++) { option = options[i]; var selected = option.selected || option.getAttribute('selected'); // IMPORTANT! IE9 doesn't update selected after form reset if ((option.selected || i === index) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && (!option.parentNode.disabled || option.parentNode.nodeName !== 'OPTGROUP')) { result.push(option.value); } } if (result.length < 2) { return result[0]; } return result; } function getFormElementValues(node) { if (isVoid(node)) { return null; } var name = getFormElementType(node); switch (name) { case 'checkbox': case 'radio': var checked = node.getAttribute('checked') || node.checked; if (!isVoid(checked)) { return checked !== false && checked !== 'false'; } return false; case 'select-multiple': return selectValues(node); default: return node.value; } } // type -> node -> function(target, event) var setupHooks = {}; function createListenerArguments(target, event) { var type = event.type; var nodeName = target.nodeName.toLowerCase(); var tagHooks = undefined; if (tagHooks = setupHooks[type]) { var hook = tagHooks[nodeName]; if (hook) { return hook(target, event); } } // Default behavior: // Form elements with a value attribute will have the arguments: // [event, value] if (isFormElement(nodeName)) { return [event, getFormElementValues(target)]; } // Fallback to just event return [event]; } function addRootListener(e, type) { if (!type) { type = e.type; } var registry = EventRegistry[type]; // Support: Safari 6-8+ // Target should not be a text node if (e.target.nodeType === 3) { e.target = e.target.parentNode; } var target = e.target, listenersCount = registry._counter, listeners = undefined, listener = undefined, nodeID = undefined, event = undefined, args = undefined, defaultArgs = undefined; if (listenersCount > 0) { event = eventInterface(e, type); defaultArgs = args = [event]; } // NOTE: Only the event blubbling phase is modeled. This is done because // handlers specified on props can not specify they are handled on the // capture phase. while (target !== null && listenersCount > 0 && target !== document.parentNode) { if (nodeID = infernoNodeID(target, true)) { listeners = listenersStorage[nodeID]; if (listeners && listeners[type]) { listener = listeners[type]; // lazily instantiate additional arguments in the case // where an event handler takes more than one argument // listener is a function, and length is the number of // arguments that function takes var numArgs = listener.originalHandler.length; args = defaultArgs; if (numArgs > 1) { args = createListenerArguments(target, event); } // 'this' on an eventListener is the element handling the event // event.currentTarget is unwriteable, and since these are // native events, will always refer to the document. Therefore // 'this' is the only supported way of referring to the element // whose listener is handling the current event listener.handler.apply(target, args); // Check if progagation stopped. There is only one listener per // type, so we do not need to check immediate propagation. if (event.isPropagationStopped()) { break; } --listenersCount; } } target = target.parentNode; } } function createEventListener(type) { return function (e) { var target = e.target; var listener = listenersStorage[infernoNodeID(target)][type]; var args = listener.originalHandler.length > 1 ? createListenerArguments(target, e) : [e]; listener.originalHandler.apply(target, args); }; } function addListener(vNode, domNode, type, listener) { if (!domNode) { return null; // TODO! Should we throw? } var registry = EventRegistry[type]; // only add listeners for registered events if (registry) { if (!registry._enabled) { // handle focus / blur events if (registry._focusBlur) { registry._focusBlur(); } else if (registry._bubbles) { var handler = setHandler(type, addRootListener).handler; document.addEventListener(type, handler, false); } registry._enabled = true; } var nodeID = infernoNodeID(domNode); var listeners = undefined; if (listenersStorage[nodeID]) { listeners = listenersStorage[nodeID]; } else { listenersStorage[nodeID] = {}; listeners = listenersStorage[nodeID]; } if (listeners[type]) { if (listeners[type].destroy) { listeners[type].destroy(); } } if (registry._bubbles) { if (!listeners[type]) { ++registry._counter; } listeners[type] = { handler: listener, originalHandler: listener }; } else { listeners[type] = setHandler(type, createEventListener(type)); listeners[type].originalHandler = listener; domNode.addEventListener(type, listeners[type].handler, false); } } else { throw Error('Inferno Error: ' + type + ' has not been registered, and therefor not supported.'); } } var eventListener = {}; // import focusEvents from '../../shared/focusEvents'; /** * Remove event listeners from a node */ function removeListener(node, type) { if (!node) { return null; // TODO! Should we throw? } var nodeID = infernoNodeID(node, true); if (nodeID) { var listeners = listenersStorage[nodeID]; if (listeners && listeners[type]) { if (listeners[type] && listeners[type].destroy) { listeners[type].destroy(); } listeners[type] = null; var registry = EventRegistry[type]; if (registry) { if (registry._bubbles) { --registry._counter; // TODO Run tests and check if this works, or code should be removed // } else if (registry._focusBlur) { // node.removeEventListener(type, eventListener[focusEvents[type]]); } else { node.removeEventListener(type, eventListener[type]); } } } } } var hookTypes = { // DOM nodes onCreated: true, onAttached: true, onDetached: true, onWillUpdate: true, onDidUpdate: true, // Components onComponentWillMount: true, onComponentDidMount: true, onComponentWillUnmount: true, onComponentWillUpdate: true, onComponentDidUpdate: true }; /** * Set HTML attributes on the template * @param{ HTMLElement } node * @param{ Object } attrs */ function addDOMStaticAttributes(vNode, domNode, attrs) { var styleUpdates = undefined; for (var attrName in attrs) { var attrVal = attrs[attrName]; if (attrVal) { if (attrName === 'style') { styleUpdates = attrVal; } else if (!hookTypes[attrName]) { template.setProperty(vNode, domNode, attrName, attrVal, false); } } } if (styleUpdates) { template.setCSS(vNode, domNode, styleUpdates, false); } } // A fast className setter as its the most common property to regularly change function fastPropSet(attrName, attrVal, domNode) { if (attrName === 'class' || attrName === 'className') { if (!isVoid(attrVal)) { if (isSVG$1) { domNode.setAttribute('class', attrVal); } else { domNode.className = attrVal; } } return true; } else if (attrName === 'ref') { if ("development" === 'development') { if (isVoid(attrVal)) { throw 'Inferno Error: Inferno.createRef() can not be null or undefined'; } } if (typeof attrVal.element === 'undefined') { throw Error('Inferno Error: Invalid ref object passed, expected InfernoDOM.createRef() object.'); } attrVal.element = domNode; return true; } return false; } function handleHooks(item, dynamicAttrs, domNode, hookEvent) { var event = dynamicAttrs[hookEvent]; if (event !== undefined) { var hookCallback = getValueWithIndex(item, event); if (hookCallback && typeof hookCallback === 'function') { hookCallback(domNode); } } } function addDOMDynamicAttributes(item, domNode, dynamicAttrs, node, hookEvent) { var styleUpdates = undefined; if (dynamicAttrs.index !== undefined) { dynamicAttrs = getValueWithIndex(item, dynamicAttrs.index); addDOMStaticAttributes(item, domNode, dynamicAttrs); return; } for (var attrName in dynamicAttrs) { if (!isVoid(attrName)) { if (hookEvent && hookTypes[attrName]) { handleHooks(item, dynamicAttrs, domNode, hookEvent); } else { var attrVal = getValueWithIndex(item, dynamicAttrs[attrName]); if (attrVal !== undefined) { if (attrName === 'style') { styleUpdates = attrVal; } else { if (fastPropSet(attrName, attrVal, domNode) === false) { if (propertyToEventType[attrName]) { addListener(item, domNode, propertyToEventType[attrName], attrVal); } else { template.setProperty(null, domNode, attrName, attrVal, true); } } } } } } } if (styleUpdates) { template.setCSS(item, domNode, styleUpdates, true); } } function clearListeners(item, domNode, dynamicAttrs) { for (var attrName in dynamicAttrs) { if (!hookTypes[attrName]) { var attrVal = getValueWithIndex(item, dynamicAttrs[attrName]); if (attrVal !== undefined && propertyToEventType[attrName]) { removeListener(item, domNode, propertyToEventType[attrName], attrVal); } } } } /** * NOTE!! This function is probably the single most * critical path for performance optimization. */ function updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs) { if (dynamicAttrs.index !== undefined) { var nextDynamicAttrs = getValueWithIndex(nextItem, dynamicAttrs.index); if (isVoid(nextDynamicAttrs)) { var lastDynamicAttrs = getValueWithIndex(lastItem, dynamicAttrs.index); for (var attrName in lastDynamicAttrs) { if (!hookTypes[attrName]) { template.removeProperty(null, domNode, attrName, true); } } return; } addDOMStaticAttributes(nextItem, domNode, nextDynamicAttrs); return; } /** * TODO: Benchmark areas that can be improved with caching. */ var styleUpdates = {}; var styleName = undefined; for (var attrName in dynamicAttrs) { var lastAttrVal = getValueWithIndex(lastItem, dynamicAttrs[attrName]); var nextAttrVal = getValueWithIndex(nextItem, dynamicAttrs[attrName]); if (!hookTypes[attrName]) { if (!isVoid(lastAttrVal)) { if (isVoid(nextAttrVal)) { if (attrName === 'style') { for (styleName in lastAttrVal) { if (!nextAttrVal || !nextAttrVal[styleName]) { styleUpdates[styleName] = ''; } } } else if (propertyToEventType[attrName]) { removeListener(nextItem, domNode, propertyToEventType[attrName], nextAttrVal); } else { template.removeProperty(null, domNode, attrName, true); } } else if (attrName === 'style') { // Unset styles on `lastAttrVal` but not on `nextAttrVal`. for (styleName in lastAttrVal) { if (lastAttrVal[styleName] && (!nextAttrVal || !nextAttrVal[styleName])) { styleUpdates[styleName] = ''; } } // Update styles that changed since `lastAttrVal`. for (styleName in nextAttrVal) { if (!nextAttrVal[styleName] || lastAttrVal[styleName] !== nextAttrVal[styleName]) { styleUpdates[styleName] = nextAttrVal[styleName]; } } } else if (lastAttrVal !== nextAttrVal) { if (fastPropSet(attrName, nextAttrVal, domNode) === false) { if (propertyToEventType[attrName]) { addListener(nextItem, domNode, propertyToEventType[attrName], nextAttrVal); // TODO! Write tests for this! } else { template.setProperty(null, domNode, attrName, nextAttrVal, true); } } } } else if (!isVoid(nextAttrVal)) { if (attrName === 'style') { styleUpdates = nextAttrVal; } else { if (fastPropSet(attrName, nextAttrVal, domNode) === false) { if (propertyToEventType[attrName]) { addListener(nextItem, domNode, propertyToEventType[attrName], nextAttrVal); } else { template.setProperty(null, domNode, attrName, nextAttrVal, true); } } } } } } if (styleUpdates) { template.setCSS(domNode, domNode, styleUpdates, true); } } function recreateRootNode(lastItem, nextItem, node, treeLifecycle, context) { var lastDomNode = lastItem.rootNode; var lastTree = lastItem.tree.dom; lastTree.remove(lastItem, treeLifecycle); var domNode = node.create(nextItem, treeLifecycle, context); var parentNode = lastDomNode.parentNode; if (parentNode) { parentNode.replaceChild(domNode, lastDomNode); } nextItem.rootNode = domNode; return domNode; } function recreateRootNodeFromHydration(hydrateNode, nextItem, node, treeLifecycle, context) { var lastDomNode = hydrateNode; var domNode = node.create(nextItem, treeLifecycle, context); var parentNode = lastDomNode.parentNode; if (parentNode) { parentNode.replaceChild(domNode, lastDomNode); } nextItem.rootNode = domNode; return domNode; } function createRootNodeWithDynamicText(templateNode, valueIndex, dynamicAttrs, recyclingEnabled) { var node = { pool: [], keyedPool: [], overrideItem: null, create: function create(item, treeLifecycle) { var domNode = undefined; if (recyclingEnabled) { domNode = recycle(node, item); if (domNode) { return domNode; } } domNode = templateNode.cloneNode(false); var value = getValueWithIndex(item, valueIndex); if (!isVoid(value)) { if ("development" !== 'production') { if (!isStringOrNumber(value)) { throw Error('Inferno Error: Template nodes with TEXT must only have a StringLiteral or NumericLiteral as a value, this is intended for low-level optimisation purposes.'); } } if (value === '') { domNode.appendChild(document.createTextNode('')); } else { domNode.textContent = value; } } if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, node, 'onCreated'); } if (dynamicAttrs && dynamicAttrs.onAttached) { treeLifecycle.addTreeSuccessListener(function () { handleHooks(item, dynamicAttrs, domNode, 'onAttached'); }); } item.rootNode = domNode; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle) { if (node !== lastItem.tree.dom) { recreateRootNode(lastItem, nextItem, node, treeLifecycle); } else { var domNode = lastItem.rootNode; nextItem.id = lastItem.id; nextItem.rootNode = domNode; var nextValue = getValueWithIndex(nextItem, valueIndex); var lastValue = getValueWithIndex(lastItem, valueIndex); if (dynamicAttrs && dynamicAttrs.onWillUpdate) { handleHooks(nextItem, dynamicAttrs, domNode, 'onWillUpdate'); } if (nextValue !== lastValue) { if (isVoid(nextValue)) { if (isVoid(lastValue)) { domNode.firstChild.nodeValue = ''; } else { domNode.textContent = ''; } } else { if ("development" !== 'production') { if (!isStringOrNumber(nextValue)) { throw Error('Inferno Error: Template nodes with TEXT must only have a StringLiteral or NumericLiteral as a value, this is intended for low-level optimisation purposes.'); } } if (isVoid(lastValue)) { domNode.textContent = nextValue; } else { domNode.firstChild.nodeValue = nextValue; } } } if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } if (dynamicAttrs && dynamicAttrs.onDidUpdate) { handleHooks(nextItem, dynamicAttrs, domNode, 'onDidUpdate'); } } }, remove: function remove(item) { if (dynamicAttrs) { var domNode = item.rootNode; if (dynamicAttrs.onDetached) { handleHooks(item, dynamicAttrs, domNode, 'onDetached'); } clearListeners(item, item.rootNode, dynamicAttrs); } } }; return node; } var errorMsg = 'Inferno Error: Template nodes with TEXT must only have a StringLiteral or NumericLiteral as a value, this is intended for low-level optimisation purposes.'; function createNodeWithDynamicText(templateNode, valueIndex, dynamicAttrs) { var domNodeMap = {}; var node = { overrideItem: null, create: function create(item, treeLifecycle) { var domNode = templateNode.cloneNode(false); var value = getValueWithIndex(item, valueIndex); if (!isVoid(value)) { if ("development" !== 'production') { if (!isStringOrNumber(value)) { throw Error(errorMsg); } } if (value === '') { domNode.appendChild(document.createTextNode('')); } else { domNode.textContent = value; } } if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, node, 'onCreated'); } if (dynamicAttrs && dynamicAttrs.onAttached) { treeLifecycle.addTreeSuccessListener(function () { handleHooks(item, dynamicAttrs, domNode, 'onAttached'); }); } domNodeMap[item.id] = domNode; return domNode; }, update: function update(lastItem, nextItem) { var domNode = domNodeMap[lastItem.id]; var nextValue = getValueWithIndex(nextItem, valueIndex); var lastValue = getValueWithIndex(lastItem, valueIndex); if (dynamicAttrs && dynamicAttrs.onWillUpdate) { handleHooks(nextItem, dynamicAttrs, domNode, 'onWillUpdate'); } if (nextValue !== lastValue) { if (isVoid(nextValue)) { if (isVoid(lastValue)) { domNode.firstChild.nodeValue = ''; } else { domNode.textContent = ''; } } else { if ("development" !== 'production') { if (!isStringOrNumber(nextValue)) { throw Error(errorMsg); } } if (isVoid(lastValue)) { domNode.textContent = nextValue; } else { domNode.firstChild.nodeValue = nextValue; } } } if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } if (dynamicAttrs && dynamicAttrs.onDidUpdate) { handleHooks(nextItem, dynamicAttrs, domNode, 'onDidUpdate'); } }, remove: function remove(item) { var domNode = domNodeMap[item.id]; if (dynamicAttrs) { if (dynamicAttrs.onDetached) { handleHooks(item, dynamicAttrs, domNode, 'onDetached'); } clearListeners(item, domNode, dynamicAttrs); } } }; return node; } function createRootNodeWithStaticChild(templateNode, dynamicAttrs, recyclingEnabled) { var node = { pool: [], keyedPool: [], overrideItem: null, create: function create(item) { var domNode = undefined; if (recyclingEnabled) { domNode = recycle(node, item); if (domNode) { return domNode; } } domNode = templateNode.cloneNode(true); if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, node); } item.rootNode = domNode; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle) { if (node !== lastItem.tree.dom) { recreateRootNode(lastItem, nextItem, node, treeLifecycle); return; } var domNode = lastItem.rootNode; nextItem.rootNode = domNode; nextItem.id = lastItem.id; if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } }, remove: function remove(item) { if (dynamicAttrs) { clearListeners(item, item.rootNode, dynamicAttrs); } } }; return node; } function createNodeWithStaticChild(templateNode, dynamicAttrs) { var domNodeMap = {}; var node = { overrideItem: null, create: function create(item) { var domNode = templateNode.cloneNode(true); if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, null); } domNodeMap[item.id] = domNode; return domNode; }, update: function update(lastItem, nextItem) { var domNode = domNodeMap[lastItem.id]; if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } }, remove: function remove(item) { var domNode = domNodeMap[item.id]; if (dynamicAttrs) { clearListeners(item, domNode, dynamicAttrs); } } }; return node; } function updateAndAppendDynamicChildren(domNode, nextValue) { for (var i = 0; i < nextValue.length; i++) { if (isStringOrNumber(nextValue[i])) { domNode.appendChild(document.createTextNode(nextValue[i])); } else { // Do nothing for now } } } function appendText(domNode, value) { var firstChild = domNode.firstChild; if (firstChild) { firstChild.nodeValue = value; } else { domNode.textContent = value; } } function removeChild(domNode) { var firstChild = domNode.firstChild; if (firstChild) { domNode.removeChild(firstChild); } } function replaceChild(domNode, childNode) { var replaceNode = domNode.firstChild; if (replaceNode) { domNode.replaceChild(childNode, domNode.firstChild); } else { domNode.appendChild(childNode); } } var recyclingEnabled$2 = isRecyclingEnabled(); var infernoBadTemplate = 'Inferno Error: A valid template node must be returned. You may have returned undefined, an array or some other invalid object.'; function updateKeyed(items, oldItems, parentNode, parentNextNode, treeLifecycle, context) { var stop = false; var startIndex = 0; var oldStartIndex = 0; var itemsLength = items.length; var oldItemsLength = oldItems.length; var startItem = itemsLength > 0 && items[startIndex]; // Edge case! In cases where someone try to update from [null] to [null], 'startitem' will be null. // Also in cases where someone try to update from [{}] to [{}] (empty object to empty object) // We solve that with avoiding going into the iteration loop. if (isVoid(startItem) && isVoid(startItem.tree)) { return; } // TODO only if there are no other children if (itemsLength === 0 && oldItemsLength >= 5) { if (recyclingEnabled$2) { for (var i = 0; i < oldItemsLength; i++) { pool(oldItems[i]); } } parentNode.textContent = ''; return; } var endIndex = itemsLength - 1; var oldEndIndex = oldItemsLength - 1; var oldStartItem = oldItemsLength > 0 && oldItems[oldStartIndex]; var endItem = undefined; var oldEndItem = undefined; var nextNode = undefined; var oldItem = undefined; var item = undefined; // TODO don't read key too often outer: while (!stop && startIndex <= endIndex && oldStartIndex <= oldEndIndex) { stop = true; while (startItem.key === oldStartItem.key) { startItem.tree.dom.update(oldStartItem, startItem, treeLifecycle, context); startIndex++; oldStartIndex++; if (startIndex > endIndex || oldStartIndex > oldEndIndex) { break outer; } else { startItem = items[startIndex]; oldStartItem = oldItems[oldStartIndex]; stop = false; } } endItem = items[endIndex]; oldEndItem = oldItems[oldEndIndex]; while (endItem.key === oldEndItem.key) { endItem.tree.dom.update(oldEndItem, endItem, treeLifecycle, context); endIndex--; oldEndIndex--; if (startIndex > endIndex || oldStartIndex > oldEndIndex) { break outer; } else { endItem = items[endIndex]; oldEndItem = oldItems[oldEndIndex]; stop = false; } } while (endItem.key === oldStartItem.key) { nextNode = endIndex + 1 < itemsLength ? items[endIndex + 1].rootNode : parentNextNode; endItem.tree.dom.update(oldStartItem, endItem, treeLifecycle, context); insertOrAppend(parentNode, endItem.rootNode, nextNode); endIndex--; oldStartIndex++; if (startIndex > endIndex || oldStartIndex > oldEndIndex) { break outer; } else { endItem = items[endIndex]; oldStartItem = oldItems[oldStartIndex]; stop = false; } } while (startItem.key === oldEndItem.key) { nextNode = oldItems[oldStartIndex].rootNode; startItem.tree.dom.update(oldEndItem, startItem, treeLifecycle, context); insertOrAppend(parentNode, startItem.rootNode, nextNode); startIndex++; oldEndIndex--; if (startIndex > endIndex || oldStartIndex > oldEndIndex) { break outer; } else { startItem = items[startIndex]; oldEndItem = oldItems[oldEndIndex]; stop = false; } } } if (oldStartIndex > oldEndIndex) { if (startIndex <= endIndex) { nextNode = endIndex + 1 < itemsLength ? items[endIndex + 1].rootNode : parentNextNode; for (; startIndex <= endIndex; startIndex++) { item = items[startIndex]; insertOrAppend(parentNode, item.tree.dom.create(item, treeLifecycle, context), nextNode); } } } else if (startIndex > endIndex) { for (; oldStartIndex <= oldEndIndex; oldStartIndex++) { oldItem = oldItems[oldStartIndex]; remove(oldItem, parentNode); } } else { var oldItemsMap = {}; var oldNextItem = oldEndIndex + 1 < oldItemsLength ? oldItems[oldEndIndex + 1] : null; for (var i = oldEndIndex; i >= oldStartIndex; i--) { oldItem = oldItems[i]; oldItem.nextItem = oldNextItem; oldItemsMap[oldItem.key] = oldItem; oldNextItem = oldItem; } var nextItem = endIndex + 1 < itemsLength ? items[endIndex + 1] : null; for (var i = endIndex; i >= startIndex; i--) { item = items[i]; var key = item.key; oldItem = oldItemsMap[key]; if (oldItem) { oldItemsMap[key] = null; oldNextItem = oldItem.nextItem; item.tree.dom.update(oldItem, item, treeLifecycle, context); /* eslint eqeqeq:0 */ // TODO optimise if (item.rootNode.nextSibling != (nextItem && nextItem.rootNode)) { nextNode = nextItem && nextItem.rootNode || parentNextNode; insertOrAppend(parentNode, item.rootNode, nextNode); } } else { nextNode = nextItem && nextItem.rootNode || parentNextNode; insertOrAppend(parentNode, item.tree.dom.create(item, treeLifecycle, context), nextNode); } nextItem = item; } for (var i = oldStartIndex; i <= oldEndIndex; i++) { oldItem = oldItems[i]; if (oldItemsMap[oldItem.key] !== null) { oldItem = oldItems[oldStartIndex]; remove(item, parentNode); } } } } // TODO can we improve performance here? function updateNonKeyed(items, oldItems, domNodeList, parentNode, parentNextNode, treeLifecycle, context) { var itemsLength = undefined; // We can't calculate length of 0 in the cases either items or oldItems is 0. // In this cases we need workaround if (items && oldItems) { itemsLength = Math.max(items.length, oldItems.length); } else if (items) { itemsLength = items = itemsLength; } else if (oldItems) { itemsLength = oldItems = itemsLength; } for (var i = 0; i < itemsLength; i++) { var item = items[i]; var oldItem = oldItems[i]; if (item !== oldItem) { if (!isVoid(item)) { if (!isVoid(oldItem)) { if (isStringOrNumber(item)) { var domNode = domNodeList[i]; if (domNode) { domNode.nodeValue = item; } } else if ((typeof item === 'undefined' ? 'undefined' : babelHelpers_typeof(item)) === 'object') { item.tree.dom.update(oldItem, item, treeLifecycle, context); } } else { if (isStringOrNumber(item)) { var childNode = document.createTextNode(item); domNodeList[i] = childNode; insertOrAppend(parentNode, childNode, parentNextNode); } } } else { if (domNodeList[i]) { parentNode.removeChild(domNodeList[i]); domNodeList.splice(i, 1); } } } } } function insertOrAppend(parentNode, newNode, nextNode) { if (nextNode) { parentNode.insertBefore(newNode, nextNode); } else { parentNode.appendChild(newNode); } } function remove(item, parentNode) { var rootNode = item.rootNode; if (isVoid(rootNode) || !rootNode.nodeType) { return null; } if (rootNode === parentNode) { parentNode.innerHTML = ''; } else { parentNode.removeChild(item.rootNode); if (recyclingEnabled$2) { pool(item); } } } function createVirtualList(value, item, childNodeList, treeLifecycle, context) { var domNode = document.createDocumentFragment(); var keyedChildren = true; if (isVoid(value)) { return; } for (var i = 0; i < value.length; i++) { var childNode = value[i]; var childType = getTypeFromValue(childNode); var childDomNode = undefined; switch (childType) { case ValueTypes.TEXT: childDomNode = document.createTextNode(childNode); childNodeList.push(childDomNode); domNode.appendChild(childDomNode); keyedChildren = false; break; case ValueTypes.TREE: keyedChildren = false; childDomNode = childNode.create(item, treeLifecycle, context); childNodeList.push(childDomNode); if ("development" !== 'production') { if (childDomNode === undefined) { throw Error('Inferno Error: Children must be provided as templates.'); } } domNode.appendChild(childDomNode); break; case ValueTypes.FRAGMENT: if (childNode.key === undefined) { keyedChildren = false; } childDomNode = childNode.tree.dom.create(childNode, treeLifecycle, context); childNodeList.push(childDomNode); domNode.appendChild(childDomNode); break; case ValueTypes.EMPTY_OBJECT: if ("development" !== 'production') { throw Error(infernoBadTemplate); } return; case ValueTypes.FUNCTION: if ("development" !== 'production') { throw Error(infernoBadTemplate); } return; case ValueTypes.ARRAY: if ("development" !== 'production') { throw Error('Inferno Error: Deep nested arrays are not supported as a valid template values - e.g. [[[1, 2, 3]]]. Only shallow nested arrays are supported - e.g. [[1, 2, 3]].'); } return; } } return { domNode: domNode, keyedChildren: keyedChildren }; } function updateVirtualList(lastValue, nextValue, childNodeList, domNode, nextDomNode, keyedChildren, treeLifecycle, context) { if (isVoid(lastValue)) { return null; } // NOTE: if someone switches from keyed to non-keyed, the node order won't be right... if (isArray(lastValue)) { if (keyedChildren) { updateKeyed(nextValue, lastValue, domNode, nextDomNode, treeLifecycle, context); } else { updateNonKeyed(nextValue, lastValue, childNodeList, domNode, nextDomNode, treeLifecycle, context); } } else { // TODO } } function createRootNodeWithDynamicChild(templateNode, valueIndex, dynamicAttrs, recyclingEnabled) { var keyedChildren = true; var childNodeList = []; var node = { pool: [], keyedPool: [], overrideItem: null, create: function create(item, treeLifecycle, context) { var domNode = undefined; if (recyclingEnabled) { domNode = recycle(node, item, treeLifecycle, context); if (domNode) { return domNode; } } domNode = templateNode.cloneNode(false); var value = getValueWithIndex(item, valueIndex); if (!isVoid(value)) { if (isArray(value)) { for (var i = 0; i < value.length; i++) { var childItem = value[i]; // catches edge case where we e.g. have [null, null, null] as a starting point if (!isVoid(childItem) && (typeof childItem === 'undefined' ? 'undefined' : babelHelpers_typeof(childItem)) === 'object') { var tree = childItem && childItem.tree; if (tree) { var childNode = childItem.tree.dom.create(childItem, treeLifecycle, context); if (childItem.key === undefined) { keyedChildren = false; } childNodeList.push(childNode); domNode.appendChild(childNode); } } else if (isStringOrNumber(childItem)) { var textNode = document.createTextNode(childItem); domNode.appendChild(textNode); childNodeList.push(textNode); keyedChildren = false; } } } else if ((typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value)) === 'object') { var tree = value && value.tree; if (tree) { domNode.appendChild(value.tree.dom.create(value, treeLifecycle, context)); } } else if (isStringOrNumber(value)) { domNode.textContent = value; } } if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, node); } item.rootNode = domNode; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle, context) { if (node !== lastItem.tree.dom) { childNodeList = []; recreateRootNode(lastItem, nextItem, node, treeLifecycle, context); return; } var domNode = lastItem.rootNode; nextItem.rootNode = domNode; nextItem.id = lastItem.id; var nextValue = getValueWithIndex(nextItem, valueIndex); var lastValue = getValueWithIndex(lastItem, valueIndex); if (nextValue && isVoid(lastValue)) { if ((typeof nextValue === 'undefined' ? 'undefined' : babelHelpers_typeof(nextValue)) === 'object') { if (isArray(nextValue)) { updateAndAppendDynamicChildren(domNode, nextValue); } else { recreateRootNode(lastItem, nextItem, node, treeLifecycle, context); } } else { domNode.appendChild(document.createTextNode(nextValue)); } } else if (lastValue && isVoid(nextValue)) { if (isArray(lastValue)) { for (var i = 0; i < lastValue.length; i++) { if (!isVoid(domNode.childNodes[i])) { domNode.removeChild(domNode.childNodes[i]); } else { removeChild(domNode); } } } else { removeChild(domNode); } } else if (nextValue !== lastValue) { if (isStringOrNumber(nextValue)) { appendText(domNode, nextValue); } else if (isVoid(nextValue)) { if (domNode !== null) { replaceChild(domNode, document.createTextNode('')); } // if we update from undefined, we will have an array with zero length. // If we check if it's an array, it will throw 'x' is undefined. } else if (isArray(nextValue)) { if (isArray(lastValue)) { if (keyedChildren) { updateKeyed(nextValue, lastValue, domNode, null, treeLifecycle, context); } else { updateNonKeyed(nextValue, lastValue, childNodeList, domNode, null, treeLifecycle, context); } } else { updateNonKeyed(nextValue, [], childNodeList, domNode, null, treeLifecycle, context); } } else if ((typeof nextValue === 'undefined' ? 'undefined' : babelHelpers_typeof(nextValue)) === 'object') { // Sometimes 'nextValue' can be an empty array or nothing at all, then it will // throw ': nextValue.tree is undefined'. var tree = nextValue && nextValue.tree; if (!isVoid(tree)) { if (!isVoid(lastValue)) { // If we update from 'null', there will be no 'tree', and the code will throw. var oldTree = lastValue && lastValue.tree; if (!isVoid(oldTree)) { tree.dom.update(lastValue, nextValue, treeLifecycle, context); } else { recreateRootNode(lastItem, nextItem, node, treeLifecycle, context); } } else { replaceChild(domNode, tree.dom.create(nextValue, treeLifecycle, context)); } } else { // Edge case! If we update from e.g object literal - {} - from a existing value, the // value will not be unset removeChild(domNode); } } } if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } }, remove: function remove(item, treeLifecycle) { removeValueTree(getValueWithIndex(item, valueIndex), treeLifecycle); if (dynamicAttrs) { clearListeners(item, item.rootNode, dynamicAttrs); } } }; return node; } function recreateNode(lastDomNode, nextItem, node, treeLifecycle, context) { var domNode = node.create(nextItem, treeLifecycle, context); lastDomNode.parentNode.replaceChild(domNode, lastDomNode); // TODO recycle old node } function createNodeWithDynamicChild(templateNode, valueIndex, dynamicAttrs) { var keyedChildren = true; var domNodeMap = {}; var childNodeList = []; var node = { overrideItem: null, create: function create(item, treeLifecycle, context) { var domNode = templateNode.cloneNode(false); var value = getValueWithIndex(item, valueIndex); if (!isVoid(value)) { if (isArray(value)) { for (var i = 0; i < value.length; i++) { var childItem = value[i]; // catches edge case where we e.g. have [null, null, null] as a starting point if (!isVoid(childItem) && (typeof childItem === 'undefined' ? 'undefined' : babelHelpers_typeof(childItem)) === 'object') { var tree = childItem && childItem.tree; if (tree) { var childNode = childItem.tree.dom.create(childItem, treeLifecycle, context); if (childItem.key === undefined) { keyedChildren = false; } childNodeList.push(childNode); domNode.appendChild(childNode); } } else if (isStringOrNumber(childItem)) { var textNode = document.createTextNode(childItem); domNode.appendChild(textNode); childNodeList.push(textNode); keyedChildren = false; } } } else if ((typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value)) === 'object') { var tree = value && value.tree; if (tree) { domNode.appendChild(value.tree.dom.create(value, treeLifecycle, context)); } } else if (isStringOrNumber(value)) { domNode.textContent = value; } } if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, null); } domNodeMap[item.id] = domNode; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle, context) { var domNode = domNodeMap[lastItem.id]; var nextValue = getValueWithIndex(nextItem, valueIndex); var lastValue = getValueWithIndex(lastItem, valueIndex); if (nextValue && isVoid(lastValue)) { if ((typeof nextValue === 'undefined' ? 'undefined' : babelHelpers_typeof(nextValue)) === 'object') { if (isArray(nextValue)) { updateAndAppendDynamicChildren(domNode, nextValue); } else { recreateNode(lastItem, nextItem, node, treeLifecycle, context); } } else { domNode.appendChild(document.createTextNode(nextValue)); } } else if (lastValue && isVoid(nextValue)) { if (isArray(lastValue)) { for (var i = 0; i < lastValue.length; i++) { if (!isVoid(domNode.childNodes[i])) { domNode.removeChild(domNode.childNodes[i]); } else { removeChild(domNode); } } } else { removeChild(domNode); } } else if (nextValue !== lastValue) { if (isStringOrNumber(nextValue)) { appendText(domNode, nextValue); } else if (isVoid(nextValue)) { removeChild(domNode); // if we update from undefined, we will have an array with zero length. // If we check if it's an array, it will throw 'x' is undefined. } else if (nextValue.length !== 0 && isArray(nextValue)) { if (lastValue && isArray(lastValue)) { if (keyedChildren) { updateKeyed(nextValue, lastValue, domNode, null, treeLifecycle, context); } else { updateNonKeyed(nextValue, lastValue, childNodeList, domNode, null, treeLifecycle, context); } } else { // lastValue is undefined, so set it to an empty array and update updateNonKeyed(nextValue, [], childNodeList, domNode, null, treeLifecycle, context); } } else if ((typeof nextValue === 'undefined' ? 'undefined' : babelHelpers_typeof(nextValue)) === 'object') { // Sometimes 'nextValue' can be an empty array or nothing at all, then it will // throw ': nextValue.tree is undefined'. var tree = nextValue && nextValue.tree; if (!isVoid(tree)) { // If we update from 'null', there will be no 'tree', and the code will throw. var _tree = lastValue && lastValue.tree; if (!isVoid(_tree)) { _tree.dom.update(lastValue, nextValue, treeLifecycle, context); } else { // TODO implement // NOTE There will be no 'tree' if we update from a null value } } else { // Edge case! If we update from e.g object literal - {} - from a existing value, the // value will not be unset removeChild(domNode); } } } if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } }, remove: function remove(item, treeLifecycle) { var domNode = domNodeMap[item.id]; removeValueTree(getValueWithIndex(item, valueIndex), treeLifecycle); if (dynamicAttrs) { clearListeners(item, domNode, dynamicAttrs); } } }; return node; } function addShapeChildren(domNode, subTreeForChildren, item, treeLifecycle, context) { if (!isVoid(subTreeForChildren)) { if (isArray(subTreeForChildren)) { for (var i = 0; i < subTreeForChildren.length; i++) { var subTree = subTreeForChildren[i]; var childNode = subTree.create(item, treeLifecycle, context); domNode.appendChild(childNode); } } else if ((typeof subTreeForChildren === 'undefined' ? 'undefined' : babelHelpers_typeof(subTreeForChildren)) === 'object') { domNode.appendChild(subTreeForChildren.create(item, treeLifecycle, context)); } } } function createRootNodeWithDynamicSubTreeForChildren(templateNode, subTreeForChildren, dynamicAttrs, recyclingEnabled) { var node = { pool: [], keyedPool: [], overrideItem: null, create: function create(item, treeLifecycle, context) { var domNode = undefined; if (recyclingEnabled) { domNode = recycle(node, item, treeLifecycle, context); if (domNode) { return domNode; } } domNode = templateNode.cloneNode(false); addShapeChildren(domNode, subTreeForChildren, item, treeLifecycle, context); if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, node); } item.rootNode = domNode; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle, context) { nextItem.id = lastItem.id; if (node !== lastItem.tree.dom) { var newDomNode = recreateRootNode(lastItem, nextItem, node, treeLifecycle, context); nextItem.rootNode = newDomNode; return newDomNode; } var domNode = lastItem.rootNode; nextItem.rootNode = domNode; if (!isVoid(subTreeForChildren)) { if (isArray(subTreeForChildren)) { for (var i = 0; i < subTreeForChildren.length; i++) { var subTree = subTreeForChildren[i]; subTree.update(lastItem, nextItem, treeLifecycle, context); } } else if ((typeof subTreeForChildren === 'undefined' ? 'undefined' : babelHelpers_typeof(subTreeForChildren)) === 'object') { subTreeForChildren.update(lastItem, nextItem, treeLifecycle, context); } } if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } }, remove: function remove(item, treeLifecycle) { if (!isVoid(subTreeForChildren)) { if (isArray(subTreeForChildren)) { for (var i = 0; i < subTreeForChildren.length; i++) { var subTree = subTreeForChildren[i]; subTree.remove(item, treeLifecycle); } } else if ((typeof subTreeForChildren === 'undefined' ? 'undefined' : babelHelpers_typeof(subTreeForChildren)) === 'object') { subTreeForChildren.remove(item, treeLifecycle); } } if (dynamicAttrs) { clearListeners(item, item.rootNode, dynamicAttrs); } } }; return node; } function createNodeWithDynamicSubTreeForChildren(templateNode, subTreeForChildren, dynamicAttrs) { var domNodeMap = {}; var node = { overrideItem: null, create: function create(item, treeLifecycle, context) { var domNode = templateNode.cloneNode(false); addShapeChildren(domNode, subTreeForChildren, item, treeLifecycle, context); if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, null); } domNodeMap[item.id] = domNode; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle, context) { var domNode = domNodeMap[lastItem.id]; if (!isVoid(subTreeForChildren)) { if (isArray(subTreeForChildren)) { for (var i = 0; i < subTreeForChildren.length; i++) { var subTree = subTreeForChildren[i]; subTree.update(lastItem, nextItem, treeLifecycle, context); } } else if ((typeof subTreeForChildren === 'undefined' ? 'undefined' : babelHelpers_typeof(subTreeForChildren)) === 'object') { var newDomNode = subTreeForChildren.update(lastItem, nextItem, treeLifecycle, context); if (newDomNode) { replaceChild(domNode, newDomNode); } } } if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } }, remove: function remove(item, treeLifecycle) { var domNode = domNodeMap[item.id]; if (!isVoid(subTreeForChildren)) { if (isArray(subTreeForChildren)) { for (var i = 0; i < subTreeForChildren.length; i++) { var subTree = subTreeForChildren[i]; subTree.remove(item, treeLifecycle); } } else if ((typeof subTreeForChildren === 'undefined' ? 'undefined' : babelHelpers_typeof(subTreeForChildren)) === 'object') { subTreeForChildren.remove(item, treeLifecycle); } } if (dynamicAttrs) { clearListeners(item, domNode, dynamicAttrs); } } }; return node; } function createDynamicNode(valueIndex) { var domNodeMap = {}; var childNodeList = []; var keyedChildren = true; var nextDomNode = undefined; var node = { overrideItem: null, create: function create(item, treeLifecycle, context) { var value = getValueWithIndex(item, valueIndex); var domNode = undefined; var type = getTypeFromValue(value); switch (type) { case ValueTypes.TEXT: // Testing the length property are actually faster than testing the // string against '', because the interpreter won't have to create a String // object from the string literal. if (isVoid(value) || value.length === 0) { value = ''; } domNode = document.createTextNode(value); break; case ValueTypes.ARRAY: var virtualList = createVirtualList(value, item, childNodeList, treeLifecycle, context); domNode = virtualList.domNode; keyedChildren = virtualList.keyedChildren; treeLifecycle.addTreeSuccessListener(function () { if (childNodeList.length > 0) { nextDomNode = childNodeList[childNodeList.length - 1].nextSibling || null; domNode = childNodeList[0].parentNode; } }); break; case ValueTypes.TREE: domNode = value.create(item, treeLifecycle, context); break; case ValueTypes.EMPTY_OBJECT: if ("development" !== 'production') { throw Error('Inferno Error: A valid template node must be returned. You may have returned undefined, an array or some other invalid object.'); } break; case ValueTypes.FUNCTION: if ("development" !== 'production') { throw Error('Inferno Error: A valid template node must be returned. You may have returned undefined, an array or some other invalid object.'); } break; case ValueTypes.FRAGMENT: domNode = value.tree.dom.create(value, treeLifecycle, context); break; } domNodeMap[item.id] = domNode; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle, context) { var domNode = domNodeMap[lastItem.id]; var nextValue = getValueWithIndex(nextItem, valueIndex); var lastValue = getValueWithIndex(lastItem, valueIndex); if (nextValue !== lastValue) { var nextType = getTypeFromValue(nextValue); var lastType = getTypeFromValue(lastValue); if (lastType !== nextType) { recreateNode(domNode, nextItem, node, treeLifecycle, context); return; } switch (nextType) { case ValueTypes.TEXT: // Testing the length property are actually faster than testing the // string against '', because the interpreter won't have to create a String // object from the string literal. if (isVoid(nextValue) || nextValue.length === 0) { nextValue = ''; } domNode.nodeValue = nextValue; break; case ValueTypes.ARRAY: updateVirtualList(lastValue, nextValue, childNodeList, domNode, nextDomNode, keyedChildren, treeLifecycle, context); break; case ValueTypes.TREE: // TODO break; case ValueTypes.FRAGMENT: nextValue.tree.dom.update(lastValue, nextValue, treeLifecycle, context); break; default: break; } } }, remove: function remove(item, treeLifecycle) { var value = getValueWithIndex(item, valueIndex); var type = getTypeFromValue(value); if (type === ValueTypes.TREE) { value.remove(item, treeLifecycle); } else if (type === ValueTypes.FRAGMENT) { value.tree.dom.remove(value, treeLifecycle); } } }; return node; } function createRootNodeWithComponent(componentIndex, props, recyclingEnabled) { var currentItem = undefined; var statelessRender = undefined; var instanceMap = {}; var node = { pool: [], keyedPool: [], overrideItem: null, create: function create(item, treeLifecycle, context) { var instance = undefined; var domNode = undefined; var toUseItem = item; if (node.overrideItem !== null) { toUseItem = node.overrideItem; } if (recyclingEnabled) { domNode = recycle(node, item, treeLifecycle, context); if (domNode) { return domNode; } } var Component = getValueWithIndex(toUseItem, componentIndex); currentItem = item; if (isVoid(Component)) { // bad component, make a text node domNode = document.createTextNode(''); item.rootNode = domNode; instance = null; return domNode; } else if (typeof Component === 'function') { // stateless component if (!Component.prototype.render) { var nextRender = Component(getValueForProps(props, toUseItem), context); nextRender.parent = item; domNode = nextRender.tree.dom.create(nextRender, treeLifecycle, context); statelessRender = nextRender; item.rootNode = domNode; } else { (function () { instance = new Component(getValueForProps(props, toUseItem)); instance.context = context; instance.componentWillMount(); var nextRender = instance.render(); var childContext = instance.getChildContext(); var fragmentFirstChild = undefined; if (childContext) { context = babelHelpers_extends({}, context, childContext); } nextRender.parent = item; domNode = nextRender.tree.dom.create(nextRender, treeLifecycle, context); item.rootNode = domNode; instance._lastRender = nextRender; if (domNode instanceof DocumentFragment) { fragmentFirstChild = domNode.childNodes[0]; } treeLifecycle.addTreeSuccessListener(function () { if (fragmentFirstChild) { domNode = fragmentFirstChild.parentNode; item.rootNode = domNode; } instance.componentDidMount(); }); instance.forceUpdate = function () { instance.context = context; var nextRender = instance.render.call(instance); var childContext = instance.getChildContext(); if (childContext) { context = babelHelpers_extends({}, context, childContext); } nextRender.parent = currentItem; nextRender.tree.dom.update(instance._lastRender, nextRender, treeLifecycle, context); currentItem.rootNode = nextRender.rootNode; instance._lastRender = nextRender; }; })(); } } instanceMap[item.id] = instance; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle, context) { var Component = getValueWithIndex(nextItem, componentIndex); var instance = instanceMap[lastItem.id]; nextItem.id = lastItem.id; currentItem = nextItem; if (!Component) { recreateRootNode(lastItem, nextItem, node, treeLifecycle, context); return; } if (typeof Component === 'function') { if (!Component.prototype.render) { var nextRender = Component(getValueForProps(props, nextItem), context); nextRender.parent = currentItem; if (!isVoid(statelessRender)) { var newDomNode = nextRender.tree.dom.update(statelessRender || instance._lastRender, nextRender, treeLifecycle, context); if (newDomNode) { if (nextRender.rootNode.parentNode) { nextRender.rootNode.parentNode.replaceChild(newDomNode, nextRender.rootNode); } else { lastItem.rootNode.parentNode.replaceChild(newDomNode, lastItem.rootNode); } currentItem.rootNode = newDomNode; } else { var _newDomNode = nextRender.tree.dom.create(statelessRender, treeLifecycle, context); if (_newDomNode) { if (nextRender.rootNode.parentNode) { nextRender.rootNode.parentNode.replaceChild(_newDomNode, nextRender.rootNode); } else { lastItem.rootNode.parentNode.replaceChild(_newDomNode, lastItem.rootNode); } currentItem.rootNode = _newDomNode; } else { currentItem.rootNode = nextRender.rootNode; } } } else { recreateRootNode(lastItem, nextItem, node, treeLifecycle, context); return; } statelessRender = nextRender; } else { if (!instance || node !== lastItem.tree.dom || Component !== instance.constructor) { recreateRootNode(lastItem, nextItem, node, treeLifecycle, context); return; } var domNode = lastItem.rootNode; var prevProps = instance.props; var prevState = instance.state; var nextState = instance.state; var nextProps = getValueForProps(props, nextItem); nextItem.rootNode = domNode; instance._updateComponent(prevState, nextState, prevProps, nextProps); } } }, remove: function remove(item, treeLifecycle) { var instance = instanceMap[item.id]; if (instance) { instance._lastRender.tree.dom.remove(instance._lastRender, treeLifecycle); instance.componentWillUnmount(); instanceMap[item.id] = null; } } }; return node; } function createNodeWithComponent(componentIndex, props) { var domNode = undefined; var currentItem = undefined; var statelessRender = undefined; var instanceMap = {}; var node = { overrideItem: null, create: function create(item, treeLifecycle, context) { var toUseItem = item; var nextRender = undefined; var instance = node.instance; if (node.overrideItem !== null) { toUseItem = node.overrideItem; } var Component = getValueWithIndex(toUseItem, componentIndex); currentItem = item; if (isVoid(Component)) { domNode = document.createTextNode(''); instance = null; return domNode; } else if (typeof Component === 'function') { // stateless component if (!Component.prototype.render) { nextRender = Component(getValueForProps(props, toUseItem), context); nextRender.parent = item; domNode = nextRender.tree.dom.create(nextRender, treeLifecycle, context); statelessRender = nextRender; } else { (function () { instance = new Component(getValueForProps(props, toUseItem)); instance.context = context; instance.componentWillMount(); nextRender = instance.render(); var childContext = instance.getChildContext(); var fragmentFirstChild = undefined; if (childContext) { context = babelHelpers_extends({}, context, childContext); } nextRender.parent = item; domNode = nextRender.tree.dom.create(nextRender, treeLifecycle, context); instance._lastRender = nextRender; if (domNode instanceof DocumentFragment) { fragmentFirstChild = domNode.childNodes[0]; } treeLifecycle.addTreeSuccessListener(function () { if (fragmentFirstChild) { domNode = fragmentFirstChild.parentNode; } instance.componentDidMount(); }); instance.forceUpdate = function () { instance.context = context; var nextRender = instance.render.call(instance); var childContext = instance.getChildContext(); if (childContext) { context = babelHelpers_extends({}, context, childContext); } nextRender.parent = currentItem; var newDomNode = nextRender.tree.dom.update(instance._lastRender, nextRender, treeLifecycle, context); if (newDomNode) { domNode = newDomNode; instance._lastRender.rootNode = domNode; instance._lastRender = nextRender; return domNode; } else { instance._lastRender = nextRender; } }; })(); } } instanceMap[item.id] = instance; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle, context) { var Component = getValueWithIndex(nextItem, componentIndex); var instance = instanceMap[lastItem.id]; currentItem = nextItem; if (!Component) { recreateNode(domNode, nextItem, node, treeLifecycle, context); if (instance) { instance._lastRender.rootNode = domNode; } return domNode; } if (typeof Component === 'function') { // stateless component if (!Component.prototype.render) { var nextRender = Component(getValueForProps(props, nextItem), context); var newDomNode = undefined; nextRender.parent = currentItem; // Edge case. If we update from a stateless component with a null value, we need to re-create it, not update it // E.g. start with 'render(template(null), container); ' will cause this. if (!isVoid(statelessRender)) { newDomNode = nextRender.tree.dom.update(statelessRender || instance._lastRender, nextRender, treeLifecycle, context); } else { recreateNode(domNode, nextItem, node, treeLifecycle, context); return; } statelessRender = nextRender; if (!isVoid(newDomNode)) { if (domNode.parentNode) { domNode.parentNode.replaceChild(newDomNode, domNode); } domNode = newDomNode; return domNode; } } else { if (!instance || Component !== instance.constructor) { recreateNode(domNode, nextItem, node, treeLifecycle, context); return domNode; } var prevProps = instance.props; var prevState = instance.state; var nextState = instance.state; var nextProps = getValueForProps(props, nextItem); return instance._updateComponent(prevState, nextState, prevProps, nextProps); } } }, remove: function remove(item, treeLifecycle) { var instance = instanceMap[item.id]; if (instance) { instance._lastRender.tree.dom.remove(instance._lastRender, treeLifecycle); instance.componentWillUnmount(); instanceMap[item.id] = null; } } }; return node; } function createRootDynamicTextNode(templateNode, valueIndex, recyclingEnabled) { var node = { pool: [], keyedPool: [], overrideItem: null, create: function create(item) { var domNode = undefined; if (recyclingEnabled) { domNode = recycle(node, item); if (domNode) { return domNode; } } domNode = templateNode.cloneNode(false); var value = getValueWithIndex(item, valueIndex); if (!isVoid(value)) { if (isStringOrNumber(value)) { domNode.nodeValue = value; } } item.rootNode = domNode; return domNode; }, update: function update(lastItem, nextItem, treeLifecycle) { if (node !== lastItem.tree.dom) { recreateRootNode(lastItem, nextItem, node, treeLifecycle); return; } var domNode = lastItem.rootNode; nextItem.rootNode = domNode; nextItem.id = lastItem.id; var nextValue = getValueWithIndex(nextItem, valueIndex); if (nextValue !== getValueWithIndex(lastItem, valueIndex)) { if (isStringOrNumber(nextValue)) { domNode.nodeValue = nextValue; } } }, remove: function remove() /* lastItem */{} }; return node; } function createRootVoidNode(templateNode, dynamicAttrs, recyclingEnabled) { var node = { pool: [], keyedPool: [], overrideItem: null, create: function create(item, treeLifecycle) { var domNode = undefined; if (recyclingEnabled) { domNode = recycle(node, item); if (domNode) { return domNode; } } domNode = templateNode.cloneNode(true); item.rootNode = domNode; if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, node, 'onCreated'); } if (dynamicAttrs && dynamicAttrs.onAttached) { treeLifecycle.addTreeSuccessListener(function () { handleHooks(item, dynamicAttrs, domNode, 'onAttached'); }); } return domNode; }, update: function update(lastItem, nextItem, treeLifecycle) { if (node !== lastItem.tree.dom) { recreateRootNode(lastItem, nextItem, node, treeLifecycle); return; } var domNode = lastItem.rootNode; nextItem.rootNode = domNode; nextItem.rootNode = lastItem.rootNode; if (dynamicAttrs && dynamicAttrs.onWillUpdate) { handleHooks(nextItem, dynamicAttrs, domNode, 'onWillUpdate'); } if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } if (dynamicAttrs && dynamicAttrs.onDidUpdate) { handleHooks(nextItem, dynamicAttrs, domNode, 'onDidUpdate'); } }, remove: function remove(item) { if (dynamicAttrs) { var domNode = item.rootNode; if (dynamicAttrs.onDetached) { handleHooks(item, dynamicAttrs, domNode, 'onDetached'); } clearListeners(item, item.rootNode, dynamicAttrs); } } }; return node; } function createVoidNode(templateNode, dynamicAttrs) { var domNodeMap = {}; var node = { overrideItem: null, create: function create(item, treeLifecycle) { var domNode = templateNode.cloneNode(true); if (dynamicAttrs) { addDOMDynamicAttributes(item, domNode, dynamicAttrs, node, 'onCreated'); } if (dynamicAttrs && dynamicAttrs.onAttached) { treeLifecycle.addTreeSuccessListener(function () { handleHooks(item, dynamicAttrs, domNode, 'onAttached'); }); } domNodeMap[item.id] = domNode; return domNode; }, update: function update(lastItem, nextItem) { var domNode = domNodeMap[lastItem.id]; if (dynamicAttrs && dynamicAttrs.onWillUpdate) { handleHooks(nextItem, dynamicAttrs, domNode, 'onWillUpdate'); } if (dynamicAttrs) { updateDOMDynamicAttributes(lastItem, nextItem, domNode, dynamicAttrs); } if (dynamicAttrs && dynamicAttrs.onDidUpdate) { handleHooks(nextItem, dynamicAttrs, domNode, 'onDidUpdate'); } }, remove: function remove(item) { var domNode = domNodeMap[item.id]; if (dynamicAttrs) { if (dynamicAttrs.onDetached) { handleHooks(item, dynamicAttrs, domNode, 'onDetached'); } clearListeners(item, domNode, dynamicAttrs); } } }; return node; } function canHydrate(domNode, nextDomNode) { if (nextDomNode) { if (nextDomNode.nodeType === 1 && nextDomNode.hasAttribute('data-inferno')) { return true; } else { // otherwise clear the DOM node domNode.innerHTML = ''; } } } function purgeCommentNodes(domNode, parentDom) { var nextSibling = domNode.nextSibling; if (nextSibling && nextSibling.nodeType === 8) { nextSibling = purgeCommentNodes(nextSibling, parentDom); parentDom.removeChild(nextSibling); } return nextSibling; } function validateHydrateNodeChildren(hydrateNode, templateNode) { var templateNodeChild = templateNode.firstChild; var hydrateNodeChild = hydrateNode.firstChild; while (templateNodeChild) { var result = validateHydrateNode(hydrateNodeChild, templateNodeChild); if (!result) { return false; } templateNodeChild = templateNodeChild.nextSibling; // check when we reach a comment and remove it, as they are used to break up text nodes hydrateNodeChild = purgeCommentNodes(hydrateNodeChild, hydrateNode); } return true; } function validateHydrateNode(hydrateNode, templateNode, item, dynamicAttrs) { // check nodeNames, return false if not same if (hydrateNode.nodeName !== templateNode.nodeName) { return false; } if (hydrateNode.nodeType === 1) { // check hydrateNode has all the same attrs as templateNode (as these will be static) // return false if not same // TODO // check hydrateNode has all the same attrs as dynamicAttrs+item (as these will be dyanmic), // passively update here and do not return false (as state could have changed) if not same if (dynamicAttrs && item) {} // TODO // check through children return validateHydrateNodeChildren(hydrateNode, templateNode); } else if (hydrateNode.nodeType === 3) { return hydrateNode.nodeValue === templateNode.nodeValue; } } function createRootStaticNode(templateNode, recyclingEnabled) { var node = { pool: [], keyedPool: [], overrideItem: null, create: function create(item) { var domNode = undefined; if (recyclingEnabled) { domNode = recycle(node, item); if (domNode) { return domNode; } } domNode = templateNode.cloneNode(true); item.rootNode = domNode; return domNode; }, update: function update(lastItem, nextItem) { // wrong tree and it toggle if (node !== lastItem.tree.dom) { recreateRootNode(lastItem, nextItem, node); return; } nextItem.rootNode = lastItem.rootNode; }, remove: function remove() {}, hydrate: function hydrate(hydrateNode, item) { if (!validateHydrateNode(hydrateNode, templateNode, item)) { recreateRootNodeFromHydration(hydrateNode, item, node); return; } item.rootNode = hydrateNode; } }; return node; } function createStaticNode(templateNode) { var node = { overrideItem: null, create: function create() { return templateNode.cloneNode(true); }, update: function update() {}, remove: function remove() {}, hydrate: function hydrate() {} }; return node; } function createElement(schema, domNamespace, parentNode) { var MathNamespace = 'http://www.w3.org/1998/Math/MathML'; var SVGNamespace = 'http://www.w3.org/2000/svg'; var nodeName = schema && typeof schema.tag === 'string' && schema.tag.toLowerCase(); var is = schema.attrs && schema.attrs.is; var templateNode = undefined; if (domNamespace === undefined) { if (schema.attrs && schema.attrs.xmlns) { domNamespace = schema.attrs.xmlns; } else { switch (nodeName) { case 'svg': domNamespace = SVGNamespace; break; case 'math': domNamespace = MathNamespace; break; default: // Edge case. In case a namespace element are wrapped inside a non-namespace element, it will inherit wrong namespace. // E.g. <div><svg><svg></div> - will not work if (parentNode) { // only used by static children // check only for top-level element for both mathML and SVG if (nodeName === 'svg' && parentNode.namespaceURI !== SVGNamespace) { domNamespace = SVGNamespace; } else if (nodeName === 'math' && parentNode.namespaceURI !== MathNamespace) { domNamespace = MathNamespace; } } else if (isSVGElement(nodeName)) { domNamespace = SVGNamespace; } else if (isMathMLElement(nodeName)) { domNamespace = MathNamespace; } } } } templateNode = domNamespace ? is ? document.createElementNS(domNamespace, nodeName, is) : document.createElementNS(domNamespace, nodeName) : is ? document.createElement(nodeName, is) : document.createElement(nodeName); return { namespace: domNamespace, node: templateNode }; } var recyclingEnabled = isRecyclingEnabled(); var invalidTemplateError = 'Inferno Error: A valid template node must be returned. You may have returned undefined, an array or some other invalid object.'; function createStaticAttributes(node, domNode, excludeAttrs) { var attrs = node.attrs; if (!isVoid(attrs)) { if (excludeAttrs) { var newAttrs = babelHelpers_extends({}, attrs); for (var attr in excludeAttrs) { if (newAttrs[attr]) { delete newAttrs[attr]; } } addDOMStaticAttributes(node, domNode, newAttrs); } else { addDOMStaticAttributes(node, domNode, attrs); } } } function createStaticTreeChildren(children, parentNode, domNamespace) { if (isArray(children)) { for (var i = 0; i < children.length; i++) { var childItem = children[i]; if (isStringOrNumber(childItem)) { var textNode = document.createTextNode(childItem); parentNode.appendChild(textNode); } else { createStaticTreeNode(childItem, parentNode, domNamespace); } } } else { if (isStringOrNumber(children)) { parentNode.textContent = children; } else { createStaticTreeNode(children, parentNode, domNamespace); } } } function createStaticTreeNode(node, parentNode, domNamespace) { var staticNode = undefined; if (!isVoid(node)) { if (isStringOrNumber(node)) { staticNode = document.createTextNode(node); } else { var tag = node.tag; if (tag) { var Element = createElement(node, domNamespace, parentNode); staticNode = Element.node; domNamespace = Element.namespace; var text = node.text; var children = node.children; if (!isVoid(text)) { if ("development" !== 'production') { if (!isVoid(children)) { throw Error(invalidTemplateError); } if (!isStringOrNumber(text)) { throw Error('Inferno Error: Template nodes with TEXT must only have a StringLiteral or NumericLiteral as a value, this is intended for low-level optimisation purposes.'); } } staticNode.textContent = text; } else { if (!isVoid(children)) { createStaticTreeChildren(children, staticNode, domNamespace); } } createStaticAttributes(node, staticNode); } else if (node.text) { staticNode = document.createTextNode(node.text); } } if ("development" !== 'production') { if (staticNode === undefined) { throw Error(invalidTemplateError); } } if (parentNode === null) { return staticNode; } else { parentNode.appendChild(staticNode); } } } function createDOMTree(schema, isRoot, dynamicNodeMap, domNamespace) { if ("development" !== 'production') { if (isVoid(schema)) { throw Error(invalidTemplateError); } if (isArray(schema)) { throw Error(invalidTemplateError); } } var dynamicFlags = dynamicNodeMap.get(schema); var node = undefined; var templateNode = undefined; if (!dynamicFlags) { templateNode = createStaticTreeNode(schema, null, domNamespace, schema); if ("development" !== 'production') { if (!templateNode) { throw Error(invalidTemplateError); } } if (isRoot) { node = createRootStaticNode(templateNode, recyclingEnabled); } else { node = createStaticNode(templateNode); } } else { if (dynamicFlags.NODE === true) { if (isRoot) { // node = createRootDynamicNode( schema.index, domNamespace, recyclingEnabled ); } else { node = createDynamicNode(schema.index, domNamespace); } } else { var tag = schema.tag; var text = schema.text; if (tag) { if (tag.type === ObjectTypes.VARIABLE) { var lastAttrs = schema.attrs; var _attrs = babelHelpers_extends({}, lastAttrs); var _children = schema.children; if (_children) { if (isArray(_children)) { if (_children.length > 1) { _attrs.children = []; for (var i = 0; i < _children.length; i++) { var childNode = _children[i]; _attrs.children.push(createDOMTree(childNode, false, dynamicNodeMap, domNamespace)); } } else if (_children.length === 1) { _attrs.children = createDOMTree(_children[0], false, dynamicNodeMap, domNamespace); } } else { _attrs.children = createDOMTree(_children, false, dynamicNodeMap, domNamespace); } } if (isRoot) { return createRootNodeWithComponent(tag.index, _attrs, _children, domNamespace, recyclingEnabled); } else { return createNodeWithComponent(tag.index, _attrs, _children, domNamespace); } } templateNode = createElement(schema, domNamespace, null).node; var attrs = schema.attrs; var dynamicAttrs = null; if (!isVoid(attrs)) { if (dynamicFlags.ATTRS === true) { dynamicAttrs = attrs; } else if (dynamicFlags.ATTRS !== false) { dynamicAttrs = dynamicFlags.ATTRS; createStaticAttributes(schema, templateNode, dynamicAttrs); } else { createStaticAttributes(schema, templateNode); } } var children = schema.children; if (!isVoid(text)) { if ("development" !== 'production') { if (!isVoid(children)) { throw Error('Inferno Error: Template nodes cannot contain both TEXT and a CHILDREN properties, they must only use one or the other.'); } } if (dynamicFlags.TEXT === true) { if (isRoot) { node = createRootNodeWithDynamicText(templateNode, text.index, dynamicAttrs, recyclingEnabled); } else { node = createNodeWithDynamicText(templateNode, text.index, dynamicAttrs); } } else { if (isStringOrNumber(text)) { templateNode.textContent = text; } else { if ("development" !== 'production') { throw Error('Inferno Error: Template nodes with TEXT must only have a StringLiteral or NumericLiteral as a value, this is intended for low-level optimisation purposes.'); } } if (isRoot) { node = createRootNodeWithStaticChild(templateNode, dynamicAttrs, recyclingEnabled); } else { node = createNodeWithStaticChild(templateNode, dynamicAttrs); } } } else { if (!isVoid(children)) { if (children.type === ObjectTypes.VARIABLE) { if (isRoot) { node = createRootNodeWithDynamicChild(templateNode, children.index, dynamicAttrs, recyclingEnabled); } else { node = createNodeWithDynamicChild(templateNode, children.index, dynamicAttrs); } } else if (dynamicFlags.CHILDREN === true) { var subTreeForChildren = []; if ((typeof children === 'undefined' ? 'undefined' : babelHelpers_typeof(children)) === 'object') { if (isArray(children)) { for (var i = 0; i < children.length; i++) { var childItem = children[i]; subTreeForChildren.push(createDOMTree(childItem, false, dynamicNodeMap)); } } else { subTreeForChildren = createDOMTree(children, false, dynamicNodeMap); } } if (isRoot) { node = createRootNodeWithDynamicSubTreeForChildren(templateNode, subTreeForChildren, dynamicAttrs, recyclingEnabled); } else { node = createNodeWithDynamicSubTreeForChildren(templateNode, subTreeForChildren, dynamicAttrs); } } else if (isStringOrNumber(children)) { templateNode.textContent = children; if (isRoot) { node = createRootNodeWithStaticChild(templateNode, dynamicAttrs, recyclingEnabled); } else { node = createNodeWithStaticChild(templateNode, dynamicAttrs); } } else { var childNodeDynamicFlags = dynamicNodeMap.get(children); if (childNodeDynamicFlags === undefined) { createStaticTreeChildren(children, templateNode); if (isRoot) { node = createRootNodeWithStaticChild(templateNode, dynamicAttrs, recyclingEnabled); } else { node = createNodeWithStaticChild(templateNode, dynamicAttrs); } } } } else { if (isRoot) { node = createRootVoidNode(templateNode, dynamicAttrs, recyclingEnabled); } else { node = createVoidNode(templateNode, dynamicAttrs); } } } } else if (text) { templateNode = document.createTextNode(''); // if ( isRoot ) { node = createRootDynamicTextNode(templateNode, text.index); // } //else { // node = createDynamicTextNode( templateNode, text.index ); // } } } } return node; } function createRef() { return { element: null }; } function createDOMFragment(parentNode, nextNode) { var lastItem = undefined; var treeSuccessListeners = []; var context = {}; var treeLifecycle = { addTreeSuccessListener: function addTreeSuccessListener(listener) { treeSuccessListeners.push(listener); }, removeTreeSuccessListener: function removeTreeSuccessListener(listener) { for (var i = 0; i < treeSuccessListeners.length; i++) { var treeSuccessListener = treeSuccessListeners[i]; if (treeSuccessListener === listener) { treeSuccessListeners.splice(i, 1); return; } } } }; return { parentNode: parentNode, render: function render(nextItem) { if (nextItem) { var tree = nextItem.tree && nextItem.tree.dom; if (tree) { var activeNode = document.activeElement; if (lastItem) { tree.update(lastItem, nextItem, treeLifecycle, context); if (!nextItem.rootNode) { lastItem = null; return; } } else { if (tree) { var hydrateNode = parentNode.firstChild; if (canHydrate(parentNode, hydrateNode)) { tree.hydrate(hydrateNode, nextItem, treeLifecycle, context); } else { var dom = tree.create(nextItem, treeLifecycle, context); if (!dom) { return; } if (nextNode) { parentNode.insertBefore(dom, nextNode); } else if (parentNode) { parentNode.appendChild(dom); } } } } if (treeSuccessListeners.length > 0) { for (var i = 0; i < treeSuccessListeners.length; i++) { treeSuccessListeners[i](); } } lastItem = nextItem; if (activeNode !== document.body && document.activeElement !== activeNode) { activeNode.focus(); } } } }, remove: function remove$$() { if (lastItem) { var tree = lastItem.tree.dom; if (lastItem) { tree.remove(lastItem, treeLifecycle); } if (lastItem.rootNode.parentNode) { remove(lastItem, parentNode); } } treeSuccessListeners = []; } }; } var rootFragments = []; function getRootFragmentAtNode(node) { var rootFragmentsLength = rootFragments.length; if (rootFragmentsLength === 0) { return null; } for (var i = 0; i < rootFragmentsLength; i++) { var rootFragment = rootFragments[i]; if (rootFragment.parentNode === node) { return rootFragment; } } return null; } function removeRootFragment(rootFragment) { for (var i = 0; i < rootFragments.length; i++) { if (rootFragments[i] === rootFragment) { rootFragments.splice(i, 1); return true; } } return false; } function render(nextItem, parentNode) { var rootFragment = getRootFragmentAtNode(parentNode); if (isVoid(rootFragment)) { var fragment = createDOMFragment(parentNode); fragment.render(nextItem); rootFragments.push(fragment); } else { if (isVoid(nextItem)) { rootFragment.remove(); removeRootFragment(rootFragment); } else { rootFragment.render(nextItem); } } } var global = global || (typeof window !== 'undefined' ? window : null); // browser if (global && global.Inferno) { global.Inferno.addTreeConstructor('dom', createDOMTree); // nodeJS // TODO! Find a better way to detect if we are running in Node, and test if this actually works!!! } else if (global && !global.Inferno) { var Inferno = undefined; // TODO! Avoid try / catch try { Inferno = require('inferno'); } catch (e) { Inferno = null; // TODO Should we throw a warning and inform that the Inferno package is not installed? } if (Inferno != null) { if (typeof Inferno.addTreeConstructor !== 'function') { throw 'Your package is out-of-date! Upgrade to latest Inferno in order to use the InfernoDOM package.'; } else { Inferno.addTreeConstructor('dom', createDOMTree); } } } var index = { render: render, createRef: createRef }; return index; }));
/*! jQuery UI - v1.11.3 - 2015-02-13 * http://jqueryui.com * Copyright jQuery Foundation and other contributors; Licensed MIT */ (function(t){"function"==typeof define&&define.amd?define(["jquery","./effect","./effect-size"],t):t(jQuery)})(function(t){return t.effects.effect.scale=function(e,i){var s=t(this),n=t.extend(!0,{},e),o=t.effects.setMode(s,e.mode||"effect"),a=parseInt(e.percent,10)||(0===parseInt(e.percent,10)?0:"hide"===o?0:100),r=e.direction||"both",h=e.origin,l={height:s.height(),width:s.width(),outerHeight:s.outerHeight(),outerWidth:s.outerWidth()},c={y:"horizontal"!==r?a/100:1,x:"vertical"!==r?a/100:1};n.effect="size",n.queue=!1,n.complete=i,"effect"!==o&&(n.origin=h||["middle","center"],n.restore=!0),n.from=e.from||("show"===o?{height:0,width:0,outerHeight:0,outerWidth:0}:l),n.to={height:l.height*c.y,width:l.width*c.x,outerHeight:l.outerHeight*c.y,outerWidth:l.outerWidth*c.x},n.fade&&("show"===o&&(n.from.opacity=0,n.to.opacity=1),"hide"===o&&(n.from.opacity=1,n.to.opacity=0)),s.effect(n)}});
/*! * Bootstrap-select v1.12.0 (http://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2016 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(root["jQuery"]); } }(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Nu a fost selectat nimic', noneResultsText: 'Nu exista niciun rezultat {0}', countSelectedText: '{0} din {1} selectat(e)', maxOptionsText: ['Limita a fost atinsa ({n} {var} max)', 'Limita de grup a fost atinsa ({n} {var} max)', ['iteme', 'item']], multipleSeparator: ', ' }; })(jQuery); }));
/*! angular-multi-select 7.0.1 */ "use strict";var angular_multi_select=angular.module("angular-multi-select");angular_multi_select.run(["$templateCache",function(a){var b=a.get("angular-multi-select.tpl");b=b.replace(/(class="(?:.*?)ams-item-text(?:.*?)")/gi,'$1 ng-click="amse.toggle_open_node(item)"'),a.put("angular-multi-select.tpl",b)}]);
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault");Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"default",{enumerable:!0,get:function(){return _TableBody.default}});var _TableBody=_interopRequireDefault(require("./TableBody"));
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":6,"../lib/Shim.IE8":30}],2:[function(_dereq_,module,exports){ var Core = _dereq_('./Core'), Persist = _dereq_('../lib/Persist'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Persist":25,"./Core":1}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (!(index instanceof Array)) { // Convert the index object to an array of key val objects index = this.keys(index); } } return this.$super.call(this, index); }); BinaryTree.prototype.keys = function (obj) { var i, keys = []; for (i in obj) { if (obj.hasOwnProperty(i)) { keys.push({ key: i, val: obj[i] }); } } return keys; }; BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return true; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._index.length; i++) { indexData = this._index[i]; if (indexData.val === 1) { result = this.sortAsc(a[indexData.key], b[indexData.key]); } else if (indexData.val === -1) { result = this.sortDesc(a[indexData.key], b[indexData.key]); } if (result !== 0) { return result; } } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._index.length; i++) { indexData = this._index[i]; if (hash) { hash += '_'; } hash += obj[indexData.key]; } return hash;*/ return obj[this._index[0].key]; }; BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (!this._data) { // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === -1) { // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === 1) { // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } return false; }; BinaryTree.prototype.lookup = function (data, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, resultArr); } } return resultArr; }; BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'key': resultArr.push(this._data); break; default: resultArr.push({ key: this._key, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Shared":29}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = JSON.stringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert; var returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: dataSet }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': this._updateIncrement(doc, i, update[i]); updated = true; break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = JSON.stringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (JSON.stringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } //op.time('Resolve chains'); this.chainSend('remove', { query: query, dataSet: dataSet }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(dataSet); } this._onChange(); this.deferEmit('change', {type: 'remove', data: dataSet}); } if (callback) { callback(false, dataSet); } return dataSet; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. * @private */ Collection.prototype.deferEmit = function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } } // Check if all queues are complete if (!this.isProcessingQueue()) { this.emit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } //op.time('Resolve chains'); this.chainSend('insert', data, {index: index}); //op.time('Resolve chains'); resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc; this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return false; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = JSON.stringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = JSON.stringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = JSON.stringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.apply(this, arguments); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, i; if (typeof query === 'string') { return new Path(query).value(item)[0]; } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":7,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":23,"./Path":24,"./ReactorIO":28,"./Shared":29}],5:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * 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 = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function () { if (!this.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); } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":4,"./Shared":29}],6:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } callback(); }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":8,"./Metrics.js":12,"./Overload":23,"./Shared":29}],7:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],8:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":12,"./Overload":23,"./Shared":29}],9:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), treeInstance = new BinaryTree(), btree = function () {}; treeInstance.inOrder('hash'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":24,"./Shared":29}],10:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":24,"./Shared":29}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":29}],12:[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":22,"./Shared":29}],13:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],14:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } arrItem.chainReceive(this, type, data, options); } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],15:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Common; Common = { /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return JSON.parse(JSON.stringify(data)); } else { var i, json = JSON.stringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(JSON.parse(json)); } return copyArr; } } return undefined; }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":23}],16:[function(_dereq_,module,exports){ "use strict"; var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],17:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; } }; module.exports = Events; },{"./Overload":23}],18:[function(_dereq_,module,exports){ "use strict"; var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Reset operation flag operation = false; substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) { return true; } else if (inArr[inArrIndex] === source) { return true; } } return false; } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (notInArr[notInArrIndex] === source) { return false; } } return true; } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; } return -1; } }; module.exports = Matching; },{}],19:[function(_dereq_,module,exports){ "use strict"; var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":23}],21:[function(_dereq_,module,exports){ "use strict"; var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],22:[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":24,"./Shared":29}],23:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + JSON.stringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path) { if (obj !== undefined && typeof obj === 'object') { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr = [], i, k; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i])); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":29}],25:[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; /** * 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) { this._encodeSteps = [ this._encode ]; this._decodeSteps = [ this._decode ]; // 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'); 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 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) { 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) { 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 = JSON.parse(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 = JSON.parse(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::' + JSON.stringify(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.apply(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); }); } 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!'); } } } // Call the original method CollectionDrop.apply(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) { 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!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Db.prototype.load = function (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 obj[index].load(loadCallback); } } }; /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Db.prototype.save = function (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 obj[index].save(saveCallback); } } }; Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":26,"./PersistCrypto":27,"./Shared":29,"async":31,"localforage":73}],26:[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) { }; 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, JSON.stringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = JSON.parse(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 the persistent storage class Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":29,"pako":75}],27:[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; }; /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype._jsonFormatter = { 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 JSON.stringify(jsonObj); }, parse: function (jsonStr) { // parse json string var jsonObj = JSON.parse(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 wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: this._jsonFormatter }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, JSON.stringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var data; if (wrapper) { wrapper = JSON.parse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: this._jsonFormatter }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with the persistent storage class Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":29,"crypto-js":40}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactoreOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":29}],29:[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.295', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Triggers":20,"./Mixin.Updating":21,"./Overload":23}],30:[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 = {}; },{}],31:[function(_dereq_,module,exports){ (function (process){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ /*jshint onevar: false, indent:4 */ /*global setImmediate: false, setTimeout: false, console: false */ (function () { var async = {}; // global on the server, window in the browser var root, previous_async; root = this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { var called = false; return function() { if (called) throw new Error("Callback was already called."); called = true; fn.apply(root, arguments); } } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; var _each = function (arr, iterator) { for (var i = 0; i < arr.length; i += 1) { iterator(arr[i], i, arr); } }; var _map = function (arr, iterator) { if (arr.map) { return arr.map(iterator); } var results = []; _each(arr, function (x, i, a) { results.push(iterator(x, i, a)); }); return results; }; var _reduce = function (arr, iterator, memo) { if (arr.reduce) { return arr.reduce(iterator, memo); } _each(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; }; var _keys = function (obj) { if (Object.keys) { return Object.keys(obj); } var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// if (typeof process === 'undefined' || !(process.nextTick)) { if (typeof setImmediate === 'function') { async.nextTick = function (fn) { // not a direct alias for IE10 compatibility setImmediate(fn); }; async.setImmediate = async.nextTick; } else { async.nextTick = function (fn) { setTimeout(fn, 0); }; async.setImmediate = async.nextTick; } } else { async.nextTick = process.nextTick; if (typeof setImmediate !== 'undefined') { async.setImmediate = function (fn) { // not a direct alias for IE10 compatibility setImmediate(fn); }; } else { async.setImmediate = async.nextTick; } } async.each = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; _each(arr, function (x) { iterator(x, only_once(done) ); }); function done(err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(); } } } }; async.forEach = async.each; async.eachSeries = function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length) { return callback(); } var completed = 0; var iterate = function () { iterator(arr[completed], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; if (completed >= arr.length) { callback(); } else { iterate(); } } }); }; iterate(); }; async.forEachSeries = async.eachSeries; async.eachLimit = function (arr, limit, iterator, callback) { var fn = _eachLimit(limit); fn.apply(null, [arr, iterator, callback]); }; async.forEachLimit = async.eachLimit; var _eachLimit = function (limit) { return function (arr, iterator, callback) { callback = callback || function () {}; if (!arr.length || limit <= 0) { return callback(); } var completed = 0; var started = 0; var running = 0; (function replenish () { if (completed >= arr.length) { return callback(); } while (running < limit && started < arr.length) { started += 1; running += 1; iterator(arr[started - 1], function (err) { if (err) { callback(err); callback = function () {}; } else { completed += 1; running -= 1; if (completed >= arr.length) { callback(); } else { replenish(); } } }); } })(); }; }; var doParallel = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.each].concat(args)); }; }; var doParallelLimit = function(limit, fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [_eachLimit(limit)].concat(args)); }; }; var doSeries = function (fn) { return function () { var args = Array.prototype.slice.call(arguments); return fn.apply(null, [async.eachSeries].concat(args)); }; }; var _asyncMap = function (eachfn, arr, iterator, callback) { arr = _map(arr, function (x, i) { return {index: i, value: x}; }); if (!callback) { eachfn(arr, function (x, callback) { iterator(x.value, function (err) { callback(err); }); }); } else { var results = []; eachfn(arr, function (x, callback) { iterator(x.value, function (err, v) { results[x.index] = v; callback(err); }); }, function (err) { callback(err, results); }); } }; async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = function (arr, limit, iterator, callback) { return _mapLimit(limit)(arr, iterator, callback); }; var _mapLimit = function(limit) { return doParallelLimit(limit, _asyncMap); }; // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.reduce = function (arr, memo, iterator, callback) { async.eachSeries(arr, function (x, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; // inject alias async.inject = async.reduce; // foldl alias async.foldl = async.reduce; async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, function (x) { return x; }).reverse(); async.reduce(reversed, memo, iterator, callback); }; // foldr alias async.foldr = async.reduceRight; var _filter = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.filter = doParallel(_filter); async.filterSeries = doSeries(_filter); // select alias async.select = async.filter; async.selectSeries = async.filterSeries; var _reject = function (eachfn, arr, iterator, callback) { var results = []; arr = _map(arr, function (x, i) { return {index: i, value: x}; }); eachfn(arr, function (x, callback) { iterator(x.value, function (v) { if (!v) { results.push(x); } callback(); }); }, function (err) { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); }; async.reject = doParallel(_reject); async.rejectSeries = doSeries(_reject); var _detect = function (eachfn, arr, iterator, main_callback) { eachfn(arr, function (x, callback) { iterator(x, function (result) { if (result) { main_callback(x); main_callback = function () {}; } else { callback(); } }); }, function (err) { main_callback(); }); }; async.detect = doParallel(_detect); async.detectSeries = doSeries(_detect); async.some = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (v) { main_callback(true); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(false); }); }; // any alias async.any = async.some; async.every = function (arr, iterator, main_callback) { async.each(arr, function (x, callback) { iterator(x, function (v) { if (!v) { main_callback(false); main_callback = function () {}; } callback(); }); }, function (err) { main_callback(true); }); }; // all alias async.all = async.every; 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 { var fn = function (left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; }; callback(null, _map(results.sort(fn), function (x) { return x.value; })); } }); }; async.auto = function (tasks, callback) { callback = callback || function () {}; var keys = _keys(tasks); var remainingTasks = keys.length if (!remainingTasks) { return callback(); } var results = {}; var listeners = []; var addListener = function (fn) { listeners.unshift(fn); }; var removeListener = function (fn) { for (var i = 0; i < listeners.length; i += 1) { if (listeners[i] === fn) { listeners.splice(i, 1); return; } } }; var taskComplete = function () { remainingTasks-- _each(listeners.slice(0), function (fn) { fn(); }); }; addListener(function () { if (!remainingTasks) { var theCallback = callback; // prevent final callback from calling itself if it errors callback = function () {}; theCallback(null, results); } }); _each(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _each(_keys(results), function(rkey) { safeResults[rkey] = results[rkey]; }); safeResults[k] = args; callback(err, safeResults); // stop subsequent errors hitting callback multiple times callback = function () {}; } else { results[k] = args; async.setImmediate(taskComplete); } }; var requires = task.slice(0, Math.abs(task.length - 1)) || []; var ready = function () { return _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); }; if (ready()) { task[task.length - 1](taskCallback, results); } else { var listener = function () { if (ready()) { removeListener(listener); task[task.length - 1](taskCallback, results); } }; addListener(listener); } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var attempts = []; // Use defaults if times not passed if (typeof times === 'function') { callback = task; task = times; times = DEFAULT_TIMES; } // Make sure times is a number times = parseInt(times, 10) || DEFAULT_TIMES; var wrappedTask = function(wrappedCallback, wrappedResults) { var retryAttempt = function(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; }; while (times) { attempts.push(retryAttempt(task, !(times-=1))); } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return callback ? wrappedTask() : wrappedTask }; async.waterfall = function (tasks, callback) { callback = callback || function () {}; 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(); } var wrapIterator = function (iterator) { return function (err) { if (err) { callback.apply(null, arguments); callback = function () {}; } else { var args = Array.prototype.slice.call(arguments, 1); var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } async.setImmediate(function () { iterator.apply(null, args); }); } }; }; wrapIterator(async.iterator(tasks))(); }; var _parallel = function(eachfn, tasks, callback) { callback = callback || function () {}; if (_isArray(tasks)) { eachfn.map(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; eachfn.each(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.parallel = function (tasks, callback) { _parallel({ map: async.map, each: async.each }, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback); }; async.series = function (tasks, callback) { callback = callback || function () {}; if (_isArray(tasks)) { async.mapSeries(tasks, function (fn, callback) { if (fn) { fn(function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } callback.call(null, err, args); }); } }, callback); } else { var results = {}; async.eachSeries(_keys(tasks), function (k, callback) { tasks[k](function (err) { var args = Array.prototype.slice.call(arguments, 1); if (args.length <= 1) { args = args[0]; } results[k] = args; callback(err); }); }, function (err) { callback(err, results); }); } }; async.iterator = function (tasks) { var makeCallback = function (index) { var fn = function () { 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 = function (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { return fn.apply( null, args.concat(Array.prototype.slice.call(arguments)) ); }; }; var _concat = function (eachfn, arr, fn, callback) { var r = []; eachfn(arr, function (x, cb) { fn(x, function (err, y) { r = r.concat(y || []); cb(err); }); }, function (err) { callback(err, r); }); }; async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { if (test()) { iterator(function (err) { if (err) { return callback(err); } async.whilst(test, iterator, callback); }); } else { callback(); } }; async.doWhilst = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } var args = Array.prototype.slice.call(arguments, 1); if (test.apply(null, args)) { async.doWhilst(iterator, test, callback); } else { callback(); } }); }; async.until = function (test, iterator, callback) { if (!test()) { iterator(function (err) { if (err) { return callback(err); } async.until(test, iterator, callback); }); } else { callback(); } }; async.doUntil = function (iterator, test, callback) { iterator(function (err) { if (err) { return callback(err); } var args = Array.prototype.slice.call(arguments, 1); if (!test.apply(null, args)) { async.doUntil(iterator, test, callback); } else { callback(); } }); }; async.queue = function (worker, concurrency) { if (concurrency === undefined) { concurrency = 1; } function _insert(q, data, pos, callback) { if (!q.started){ q.started = true; } if (!_isArray(data)) { data = [data]; } if(data.length == 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { if (q.drain) { q.drain(); } }); } _each(data, function(task) { var item = { data: task, callback: typeof callback === 'function' ? callback : null }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.saturated && q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } var workers = 0; var q = { tasks: [], concurrency: concurrency, saturated: null, empty: null, drain: null, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = null; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { var task = q.tasks.shift(); if (q.empty && q.tasks.length === 0) { q.empty(); } workers += 1; var next = function () { workers -= 1; if (task.callback) { task.callback.apply(task, arguments); } if (q.drain && q.tasks.length + workers === 0) { q.drain(); } q.process(); }; var cb = only_once(next); worker(task.data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { if (q.paused === true) { return; } q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= q.concurrency; w++) { async.setImmediate(q.process); } } }; 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 (!q.started){ q.started = true; } if (!_isArray(data)) { data = [data]; } if(data.length == 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { if (q.drain) { q.drain(); } }); } _each(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : null }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.saturated && 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) { var working = false, tasks = []; var cargo = { tasks: tasks, payload: payload, saturated: null, empty: null, drain: null, drained: true, push: function (data, callback) { if (!_isArray(data)) { data = [data]; } _each(data, function(task) { tasks.push({ data: task, callback: typeof callback === 'function' ? callback : null }); cargo.drained = false; if (cargo.saturated && tasks.length === payload) { cargo.saturated(); } }); async.setImmediate(cargo.process); }, process: function process() { if (working) return; if (tasks.length === 0) { if(cargo.drain && !cargo.drained) cargo.drain(); cargo.drained = true; return; } var ts = typeof payload === 'number' ? tasks.splice(0, payload) : tasks.splice(0, tasks.length); var ds = _map(ts, function (task) { return task.data; }); if(cargo.empty) cargo.empty(); working = true; worker(ds, function () { working = false; var args = arguments; _each(ts, function (data) { if (data.callback) { data.callback.apply(null, args); } }); process(); }); }, length: function () { return tasks.length; }, running: function () { return working; } }; return cargo; }; var _console_fn = function (name) { return function (fn) { var args = Array.prototype.slice.call(arguments, 1); fn.apply(null, args.concat([function (err) { var args = Array.prototype.slice.call(arguments, 1); if (typeof console !== 'undefined') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _each(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 || function (x) { return x; }; var memoized = function () { var args = Array.prototype.slice.call(arguments); var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.nextTick(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([function () { memo[key] = arguments; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, arguments); } }])); } }; memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; async.times = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.map(counter, iterator, callback); }; async.timesSeries = function (count, iterator, callback) { var counter = []; for (var i = 0; i < count; i++) { counter.push(i); } return async.mapSeries(counter, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([function () { var err = arguments[0]; var nextargs = Array.prototype.slice.call(arguments, 1); 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)); }; var _applyEach = function (eachfn, fns /*args...*/) { var go = function () { var that = this; var args = Array.prototype.slice.call(arguments); var callback = args.pop(); return eachfn(fns, function (fn, cb) { fn.apply(that, args.concat([cb])); }, callback); }; if (arguments.length > 2) { var args = Array.prototype.slice.call(arguments, 2); return go.apply(this, args); } else { return go; } }; async.applyEach = doParallel(_applyEach); async.applyEachSeries = doSeries(_applyEach); async.forever = function (fn, callback) { function next(err) { if (err) { if (callback) { return callback(err); } throw err; } fn(next); } next(); }; // Node.js if (typeof module !== 'undefined' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define !== 'undefined' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process')) },{"_process":66}],32:[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":33,"./core":34,"./enc-base64":35,"./evpkdf":37,"./md5":42}],33:[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":34}],34:[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; })); },{}],35:[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":34}],36:[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":34}],37:[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":34,"./hmac":39,"./sha1":58}],38:[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":33,"./core":34}],39:[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":34}],40:[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":32,"./cipher-core":33,"./core":34,"./enc-base64":35,"./enc-utf16":36,"./evpkdf":37,"./format-hex":38,"./hmac":39,"./lib-typedarrays":41,"./md5":42,"./mode-cfb":43,"./mode-ctr":45,"./mode-ctr-gladman":44,"./mode-ecb":46,"./mode-ofb":47,"./pad-ansix923":48,"./pad-iso10126":49,"./pad-iso97971":50,"./pad-nopadding":51,"./pad-zeropadding":52,"./pbkdf2":53,"./rabbit":55,"./rabbit-legacy":54,"./rc4":56,"./ripemd160":57,"./sha1":58,"./sha224":59,"./sha256":60,"./sha3":61,"./sha384":62,"./sha512":63,"./tripledes":64,"./x64-core":65}],41:[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":34}],42:[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":34}],43:[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":33,"./core":34}],44:[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 jhruby.web@gmail.com */ 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":33,"./core":34}],45:[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":33,"./core":34}],46:[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":33,"./core":34}],47:[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":33,"./core":34}],48:[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":33,"./core":34}],49:[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":33,"./core":34}],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) { /** * 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":33,"./core":34}],51:[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":33,"./core":34}],52:[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":33,"./core":34}],53:[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":34,"./hmac":39,"./sha1":58}],54:[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":33,"./core":34,"./enc-base64":35,"./evpkdf":37,"./md5":42}],55:[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":33,"./core":34,"./enc-base64":35,"./evpkdf":37,"./md5":42}],56:[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":33,"./core":34,"./enc-base64":35,"./evpkdf":37,"./md5":42}],57:[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":34}],58:[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":34}],59:[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":34,"./sha256":60}],60:[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":34}],61:[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":34,"./x64-core":65}],62:[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":34,"./sha512":63,"./x64-core":65}],63:[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":34,"./x64-core":65}],64:[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":33,"./core":34,"./enc-base64":35,"./evpkdf":37,"./md5":42}],65:[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":34}],66:[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) { 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'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],67:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":69}],68:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":67,"asap":69}],69:[function(_dereq_,module,exports){ (function (process){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":66}],70:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // 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; // 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 = window.BlobBuilder || window.MSBlobBuilder || window.MozBlobBuilder || window.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]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function(e) { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // added when support for blob shims was added openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } 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') { window.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') { window.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') { window.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 }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":68}],71:[function(_dereq_,module,exports){ // 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). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; 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; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // 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 + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { 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') { window.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 = 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 keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; for (var i = 0; i < length; i++) { var key = localStorage.key(i); 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 = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), i + 1); 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') { window.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') { window.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) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; 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 }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":74,"promise":68}],72:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // 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 serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); 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 serializerPromise.then(function(lib) { 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') { window.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 = 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 = 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') { window.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; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; 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') { window.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 }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":74,"promise":68}],73:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // 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 ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; 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 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // 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 globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // 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]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // 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(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(driverObject, callback, errorCallback) { var defineDriver = 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); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { var driverPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly switch (driverName) { case self.INDEXEDDB: resolve(_dereq_('./drivers/indexeddb')); break; case self.LOCALSTORAGE: resolve(_dereq_('./drivers/localstorage')); break; case self.WEBSQL: resolve(_dereq_('./drivers/websql')); break; } } else { resolve(globalObject[driverName]); } }); driverPromise.then(function(driver) { self._extend(driver); resolve(); }); } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); resolve(); } else { self._driverSet = Promise.reject(error); reject(error); } }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // 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. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":70,"./drivers/localstorage":71,"./drivers/websql":72,"promise":68}],74:[function(_dereq_,module,exports){ (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 }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}],75:[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":76,"./lib/inflate":77,"./lib/utils/common":78,"./lib/zlib/constants":81}],76:[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":78,"./utils/strings":79,"./zlib/deflate.js":83,"./zlib/messages":88,"./zlib/zstream":90}],77:[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 sWindow 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 sWindow 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; 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_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)); } } } } while ((strm.avail_in > 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":78,"./utils/strings":79,"./zlib/constants":81,"./zlib/gzheader":84,"./zlib/inflate.js":86,"./zlib/messages":88,"./zlib/zstream":90}],78:[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); },{}],79:[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":78}],80:[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; },{}],81:[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 }; },{}],82:[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; },{}],83:[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 sWindow */ 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.sWindow; // 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 sWindow 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->sWindow+(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 sWindow 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 sWindow 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.sWindow, s.sWindow, _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.sWindow, 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.sWindow[str]; /* UPDATE_HASH(s, s->ins_h, s->sWindow[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[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->sWindow[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[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 sWindow, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->sWindow + 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 sWindow, 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->sWindow + 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 * sWindow 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 sWindow 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 sWindow[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.sWindow[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 sWindow 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.sWindow[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.sWindow[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.sWindow[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.sWindow[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.sWindow[s.strstart])); /*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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 sWindow 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 sWindow[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.sWindow[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 sWindow 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.sWindow[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->sWindow[s->strstart-1])); /*** _tr_tally_lit(s, s.sWindow[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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->sWindow[s->strstart-1])); /*** _tr_tally_lit(s, s.sWindow[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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.sWindow; 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->sWindow+(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->sWindow[s->strstart])); /*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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->sWindow[s->strstart])); /*** _tr_tally_lit(s, s.sWindow[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.sWindow[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 sWindow size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.sWindow = null; /* Sliding sWindow. Input bytes are read into the second half of the sWindow, * 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 sWindow: 2*wSize, except when the user input buffer * is directly used as sliding sWindow. */ 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 sWindow 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; /* sWindow position at the beginning of the current output block. Gets * negative when the sWindow 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 sWindow */ 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 sWindow 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 sWindow 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 sWindow 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 sWindow 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 sWindow 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.sWindow = 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->sWindow 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":78,"./adler32":80,"./crc32":82,"./messages":88,"./trees":89}],84:[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; },{}],85:[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; /* sWindow size or zero if not using sWindow */ var whave; /* valid bytes in the sWindow */ var wnext; /* sWindow write index */ var sWindow; /* allocated sliding sWindow, 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 */ /* sWindow position, sWindow 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; sWindow = state.sWindow; 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 sWindow */ op = dist - op; /* distance back in sWindow */ 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; // sWindow index from_source = sWindow; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from sWindow */ len -= op; do { output[_out++] = sWindow[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around sWindow */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of sWindow */ len -= op; do { output[_out++] = sWindow[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of sWindow */ op = wnext; len -= op; do { output[_out++] = sWindow[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in sWindow */ from += wnext - op; if (op < len) { /* some from sWindow */ len -= op; do { output[_out++] = sWindow[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; }; },{}],86:[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 sWindow */ 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 sWindow */ this.wbits = 0; /* log base 2 of requested sWindow size */ this.wsize = 0; /* sWindow size or zero if not using sWindow */ this.whave = 0; /* valid bytes in the sWindow */ this.wnext = 0; /* sWindow write index */ this.sWindow = null; /* allocated sliding sWindow, 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 sWindow bits, free sWindow if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.sWindow !== null && state.wbits !== windowBits) { state.sWindow = 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.sWindow = 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 sWindow with the last wsize (normally 32K) bytes written before returning. If sWindow does not exist yet, create it. This is only called when a sWindow 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 sWindow 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 sWindow 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 sWindow */ if (state.sWindow === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.sWindow = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular sWindow */ if (copy >= state.wsize) { utils.arraySet(state.sWindow,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->sWindow + state->wnext, end - copy, dist); utils.arraySet(state.sWindow,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->sWindow, end - copy, copy); utils.arraySet(state.sWindow,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 sWindow 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 sWindow */ 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.sWindow; } 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 sWindow 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.sWindow) { state.sWindow = 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":78,"./adler32":80,"./crc32":82,"./inffast":85,"./inftrees":87}],87:[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":78}],88:[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) */ }; },{}],89:[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.sWindow, 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":78}],90:[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; },{}]},{},[2]);
class X { foo = 2 bar: number = 3 baz: ?string }
(function(){ var canv = document.getElementById('myCanvas'), c = canv.getContext('2d'), gravity = 0.01; var circle = { x: 50, y: 50, // (vx, vy) = Velocity vector vx: 0, vy: 0, radius: 20 }; function executeFrame(){ // Increment location by velocity circle.x += circle.vx; circle.y += circle.vy; // Increment Gravity circle.vy += gravity; if(circle.y + circle.radius > canv.height){ circle.vy = -Math.abs(circle.vy); } c.clearRect(0, 0, canv.width, canv.height); c.beginPath(); c.arc(circle.x, circle.y, circle.radius, 0, 2*Math.PI); c.closePath(); c.fill(); requestAnimFrame(executeFrame); } // Start animation executeFrame(); })();
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (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' && p.then !== Rx.Observable.prototype.then; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // 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; }; } 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 Object.prototype.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; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
'use strict'; angular .module('app', ['angularFileUpload']) .controller('AppController', ['$scope', 'FileUploader', function($scope, FileUploader) { var uploader = $scope.uploader = new FileUploader({ url: 'upload.php' }); // FILTERS uploader.filters.push({ name: 'imageFilter', fn: function(item /*{File|FileLikeObject}*/, options) { var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|'; return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1; } }); // CALLBACKS uploader.onWhenAddingFileFailed = function(item /*{File|FileLikeObject}*/, filter, options) { console.info('onWhenAddingFileFailed', item, filter, options); }; uploader.onAfterAddingFile = function(fileItem) { console.info('onAfterAddingFile', fileItem); }; uploader.onAfterAddingAll = function(addedFileItems) { console.info('onAfterAddingAll', addedFileItems); }; uploader.onBeforeUploadItem = function(item) { console.info('onBeforeUploadItem', item); }; uploader.onProgressItem = function(fileItem, progress) { console.info('onProgressItem', fileItem, progress); }; uploader.onProgressAll = function(progress) { console.info('onProgressAll', progress); }; uploader.onSuccessItem = function(fileItem, response, status, headers) { console.info('onSuccessItem', fileItem, response, status, headers); }; uploader.onErrorItem = function(fileItem, response, status, headers) { console.info('onErrorItem', fileItem, response, status, headers); }; uploader.onCancelItem = function(fileItem, response, status, headers) { console.info('onCancelItem', fileItem, response, status, headers); }; uploader.onCompleteItem = function(fileItem, response, status, headers) { console.info('onCompleteItem', fileItem, response, status, headers); }; uploader.onCompleteAll = function() { console.info('onCompleteAll'); }; console.info('uploader', uploader); }]);
/** * angular-recaptcha build:2016-04-12 * https://github.com/vividcortex/angular-recaptcha * Copyright (c) 2016 VividCortex **/ /*global angular, Recaptcha */ (function (ng) { 'use strict'; ng.module('vcRecaptcha', []); }(angular)); /*global angular */ (function (ng) { 'use strict'; function throwNoKeyException() { throw new Error('You need to set the "key" attribute to your public reCaptcha key. If you don\'t have a key, please get one from https://www.google.com/recaptcha/admin/create'); } var app = ng.module('vcRecaptcha'); /** * An angular service to wrap the reCaptcha API */ app.provider('vcRecaptchaService', function(){ var provider = this; var config = {}; provider.onLoadFunctionName = 'vcRecaptchaApiLoaded'; /** * Sets the reCaptcha configuration values which will be used by default is not specified in a specific directive instance. * * @since 2.5.0 * @param defaults object which overrides the current defaults object. */ provider.setDefaults = function(defaults){ ng.copy(config, defaults); }; /** * Sets the reCaptcha key which will be used by default is not specified in a specific directive instance. * * @since 2.5.0 * @param siteKey the reCaptcha public key (refer to the README file if you don't know what this is). */ provider.setSiteKey = function(siteKey){ config.key = siteKey; }; /** * Sets the reCaptcha theme which will be used by default is not specified in a specific directive instance. * * @since 2.5.0 * @param theme The reCaptcha theme. */ provider.setTheme = function(theme){ config.theme = theme; }; /** * Sets the reCaptcha stoken which will be used by default is not specified in a specific directive instance. * * @since 2.5.0 * @param stoken The reCaptcha stoken. */ provider.setStoken = function(stoken){ config.stoken = stoken; }; /** * Sets the reCaptcha size which will be used by default is not specified in a specific directive instance. * * @since 2.5.0 * @param size The reCaptcha size. */ provider.setSize = function(size){ config.size = size; }; /** * Sets the reCaptcha type which will be used by default is not specified in a specific directive instance. * * @since 2.5.0 * @param type The reCaptcha type. */ provider.setType = function(type){ config.type = type; }; /** * Sets the reCaptcha configuration values which will be used by default is not specified in a specific directive instance. * * @since 2.5.0 * @param onLoadFunctionName string name which overrides the name of the onload function. Should match what is in the recaptcha script querystring onload value. */ provider.setOnLoadFunctionName = function(onLoadFunctionName){ provider.onLoadFunctionName = onLoadFunctionName; }; provider.$get = ['$rootScope','$window', '$q', function ($rootScope, $window, $q) { var deferred = $q.defer(), promise = deferred.promise, recaptcha; $window.vcRecaptchaApiLoadedCallback = $window.vcRecaptchaApiLoadedCallback || []; var callback = function () { recaptcha = $window.grecaptcha; deferred.resolve(recaptcha); }; $window.vcRecaptchaApiLoadedCallback.push(callback); $window[provider.onLoadFunctionName] = function () { $window.vcRecaptchaApiLoadedCallback.forEach(function(callback) { callback(); }); }; function getRecaptcha() { if (!!recaptcha) { return $q.when(recaptcha); } return promise; } function validateRecaptchaInstance() { if (!recaptcha) { throw new Error('reCaptcha has not been loaded yet.'); } } // Check if grecaptcha is not defined already. if (ng.isDefined($window.grecaptcha)) { callback(); } return { /** * Creates a new reCaptcha object * * @param elm the DOM element where to put the captcha * @param conf the captcha object configuration * @throws NoKeyException if no key is provided in the provider config or the directive instance (via attribute) */ create: function (elm, conf) { conf.sitekey = conf.key || config.key; conf.theme = conf.theme || config.theme; conf.stoken = conf.stoken || config.stoken; conf.size = conf.size || config.size; conf.type = conf.type || config.type; if (!conf.sitekey || conf.sitekey.length !== 40) { throwNoKeyException(); } return getRecaptcha().then(function (recaptcha) { return recaptcha.render(elm, conf); }); }, /** * Reloads the reCaptcha */ reload: function (widgetId) { validateRecaptchaInstance(); // $log.info('Reloading captcha'); recaptcha.reset(widgetId); // Let everyone know this widget has been reset. $rootScope.$broadcast('reCaptchaReset', widgetId); }, /** * Gets the response from the reCaptcha widget. * * @see https://developers.google.com/recaptcha/docs/display#js_api * * @returns {String} */ getResponse: function (widgetId) { validateRecaptchaInstance(); return recaptcha.getResponse(widgetId); } }; }]; }); }(angular)); /*global angular, Recaptcha */ (function (ng) { 'use strict'; var app = ng.module('vcRecaptcha'); app.directive('vcRecaptcha', ['$document', '$timeout', 'vcRecaptchaService', function ($document, $timeout, vcRecaptcha) { return { restrict: 'A', require: "?^^form", scope: { response: '=?ngModel', key: '=?', stoken: '=?', theme: '=?', size: '=?', type: '=?', tabindex: '=?', required: '=?', onCreate: '&', onSuccess: '&', onExpire: '&' }, link: function (scope, elm, attrs, ctrl) { scope.widgetId = null; if(ctrl && ng.isDefined(attrs.required)){ scope.$watch('required', validate); } var removeCreationListener = scope.$watch('key', function (key) { var callback = function (gRecaptchaResponse) { // Safe $apply $timeout(function () { scope.response = gRecaptchaResponse; validate(); // Notify about the response availability scope.onSuccess({response: gRecaptchaResponse, widgetId: scope.widgetId}); }); }; vcRecaptcha.create(elm[0], { callback: callback, key: key, stoken: scope.stoken || attrs.stoken || null, theme: scope.theme || attrs.theme || null, type: scope.type || attrs.type || null, tabindex: scope.tabindex || attrs.tabindex || null, size: scope.size || attrs.size || null, 'expired-callback': expired }).then(function (widgetId) { // The widget has been created validate(); scope.widgetId = widgetId; scope.onCreate({widgetId: widgetId}); scope.$on('$destroy', destroy); scope.$on('reCaptchaReset', function(event, resetWidgetId){ if(ng.isUndefined(resetWidgetId) || widgetId === resetWidgetId){ scope.response = ""; validate(); } }) }); // Remove this listener to avoid creating the widget more than once. removeCreationListener(); }); function destroy() { if (ctrl) { // reset the validity of the form if we were removed ctrl.$setValidity('recaptcha', null); } cleanup(); } function expired(){ // Safe $apply $timeout(function () { scope.response = ""; validate(); // Notify about the response availability scope.onExpire({ widgetId: scope.widgetId }); }); } function validate(){ if(ctrl){ ctrl.$setValidity('recaptcha', scope.required === false ? null : Boolean(scope.response)); } } function cleanup(){ // removes elements reCaptcha added. ng.element($document[0].querySelectorAll('.pls-container')).parent().remove(); } } }; }]); }(angular));
import "day"; import "interval"; import "time"; import "year"; d3_time_daySymbols.forEach(function(day, i) { day = day.toLowerCase(); i = 7 - i; var interval = d3.time[day] = d3_time_interval(function(date) { (date = d3.time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7); return date; }, function(date, offset) { date.setDate(date.getDate() + Math.floor(offset) * 7); }, function(date) { var day = d3.time.year(date).getDay(); return Math.floor((d3.time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i); }); d3.time[day + "s"] = interval.range; d3.time[day + "s"].utc = interval.utc.range; d3.time[day + "OfYear"] = function(date) { var day = d3.time.year(date).getDay(); return Math.floor((d3.time.dayOfYear(date) + (day + i) % 7) / 7); }; }); d3.time.week = d3.time.sunday; d3.time.weeks = d3.time.sunday.range; d3.time.weeks.utc = d3.time.sunday.utc.range; d3.time.weekOfYear = d3.time.sundayOfYear;
/** * API Bound Models for AngularJS * @version v1.1.0 - 2014-09-23 * @link https://github.com/angular-platanus/restmod * @author Ignacio Baixas <ignacio@platan.us> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function(angular, undefined) { 'use strict'; /** * @mixin Populate * * @description * * Adds the `Scope.$populate` method that enables multiple record resolving using one request. * * This plugin requires special api support for multiple id requests. */ angular.module('restmod').factory('restmod.FindMany', ['restmod', 'RMPackerCache', 'inflector', function(restmod, packerCache, inflector) { return restmod.mixin(function() { /** * @method $populate * @memberOf Populate * * @description Provides the url for a findMany/populate operation. */ this.define('Scope.$findManyUrl', function(_resource) { return this.$fetchManyUrl ? this.$fetchManyUrl(_resource) : this.$url(_resource); }) /** * @method $populate * @memberOf Populate * * @description Resolves a series of records using a single api call. * * By default, this method uses the same url used by `collection.$fetch`. To provide a different url * then override the `Scope.$findManyUrl` function. * * By default this method uses the pluralized variat of the primary key for the query parameter holding * the ids. You can override this parameter by setting the `findManyKey` configuration var. * * This method triggers the `before-find-many` event before sending the server request. * * Usage: * * ```javascript * var bikes = [ * Bike.$new(1), * Bike.$new(2), * Bike.$new(3) * ]; * * Bike.$populate(bikes).$then(function() { * // populate returns a fully fledged resource! * alert('Ready!'); * }) * ``` * * @param {array} _records Records to resolve. * @return {Resource} Resource holding the populate promise. */ .define('Scope.$populate', function(_records) { // Extract record pks for non resolved records and build a record map var pks = [], recordMap = {}, params = {}, model = this.$type, dummy = model.dummy(true), record, request; for(var i = 0; i < _records.length; i++) { record = _records[i]; if(!record.$resolved) { if(recordMap[record.$pk]) { recordMap[record.$pk].push(record); } else { recordMap[record.$pk] = [record]; pks.push(record.$pk); } } } if(pks.length === 0) return dummy; // build request params[model.getProperty('findManyKey', inflector.pluralize(model.getProperty('primaryKey')))] = pks; request = { url: (this.$scope || this).$findManyUrl(this), method: 'GET', params: params }; // allow user to modify request on hook dummy.$dispatch('before-find-many', [request]); // Execute request to fetch for required records return model.dummy(true).$send(request, function(_response) { try { packerCache.prepare(); var raw = model.unpack(this, _response.data), pk, records; // load raw data into records for(var i = 0; i < raw.length; i++) { pk = model.inferKey(raw[i]); records = recordMap[pk]; if(records) { for(var j = 0; j < records.length; j++) { if(!records[j].$resolved) records[j].$decode(raw[i]); } } } } finally { packerCache.clear(); } }); }); }); }]);})(angular);
/** * @license wysihtml v0.5.0-beta13 * https://github.com/Voog/wysihtml * * Author: Christopher Blum (https://github.com/tiff) * Secondary author of extended features: Oliver Pulges (https://github.com/pulges) * * Copyright (C) 2012 XING AG * Licensed under the MIT license (MIT) * */ var wysihtml5 = { version: "0.5.0-beta13", // namespaces commands: {}, dom: {}, quirks: {}, toolbar: {}, lang: {}, selection: {}, views: {}, INVISIBLE_SPACE: "\uFEFF", INVISIBLE_SPACE_REG_EXP: /\uFEFF/g, EMPTY_FUNCTION: function() {}, ELEMENT_NODE: 1, TEXT_NODE: 3, BACKSPACE_KEY: 8, ENTER_KEY: 13, ESCAPE_KEY: 27, SPACE_KEY: 32, TAB_KEY: 9, DELETE_KEY: 46 }; ;wysihtml5.polyfills = function(win, doc) { // TODO: in future try to replace most inline compability checks with polyfills for code readability // IE8 SUPPORT BLOCK // You can compile without all this if IE8 is not needed // String trim for ie8 if (!String.prototype.trim) { (function() { // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; String.prototype.trim = function() { return this.replace(rtrim, ''); }; })(); } // addEventListener, removeEventListener (function() { var s_add = 'addEventListener', s_rem = 'removeEventListener'; if( doc[s_add] ) return; win.Element.prototype[ s_add ] = win[ s_add ] = doc[ s_add ] = function( on, fn, self ) { return (self = this).attachEvent( 'on' + on, function(e){ var e = e || win.event; e.target = e.target || e.srcElement; e.preventDefault = e.preventDefault || function(){e.returnValue = false}; e.stopPropagation = e.stopPropagation || function(){e.cancelBubble = true}; e.which = e.button ? ( e.button === 2 ? 3 : e.button === 4 ? 2 : e.button ) : e.keyCode; fn.call(self, e); }); }; win.Element.prototype[ s_rem ] = win[ s_rem ] = doc[ s_rem ] = function( on, fn ) { return this.detachEvent( 'on' + on, fn ); }; })(); // element.textContent polyfill. if (Object.defineProperty && Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(win.Element.prototype, "textContent") && !Object.getOwnPropertyDescriptor(win.Element.prototype, "textContent").get) { (function() { var innerText = Object.getOwnPropertyDescriptor(win.Element.prototype, "innerText"); Object.defineProperty(win.Element.prototype, "textContent", { get: function() { return innerText.get.call(this); }, set: function(s) { return innerText.set.call(this, s); } } ); })(); } // isArray polyfill for ie8 if(!Array.isArray) { Array.isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; } // Array indexOf for ie8 if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(a,f) { for(var c=this.length,r=-1,d=f>>>0; ~(c-d); r=this[--c]===a?c:r); return r; }; } // Function.prototype.bind() // TODO: clean the code from variable 'that' as it can be confusing if (!Function.prototype.bind) { Function.prototype.bind = function(oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function() {}, fBound = function() { return fToBind.apply(this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; } // Element.matches Adds ie8 support and unifies nonstandard function names in other browsers win.Element && function(ElementPrototype) { ElementPrototype.matches = ElementPrototype.matches || ElementPrototype.matchesSelector || ElementPrototype.mozMatchesSelector || ElementPrototype.msMatchesSelector || ElementPrototype.oMatchesSelector || ElementPrototype.webkitMatchesSelector || function (selector) { var node = this, nodes = (node.parentNode || node.document).querySelectorAll(selector), i = -1; while (nodes[++i] && nodes[i] != node); return !!nodes[i]; }; }(win.Element.prototype); // Element.classList for ie8-9 (toggle all IE) // source http://purl.eligrey.com/github/classList.js/blob/master/classList.js if ("document" in win) { // Full polyfill for browsers with no classList support if (!("classList" in doc.createElement("_"))) { (function(view) { "use strict"; if (!('Element' in view)) return; var classListProp = "classList", protoProp = "prototype", elemCtrProto = view.Element[protoProp], objCtr = Object, strTrim = String[protoProp].trim || function() { return this.replace(/^\s+|\s+$/g, ""); }, arrIndexOf = Array[protoProp].indexOf || function(item) { var i = 0, len = this.length; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; }, // Vendors: please allow content code to instantiate DOMExceptions DOMEx = function(type, message) { this.name = type; this.code = DOMException[type]; this.message = message; }, checkTokenAndGetIndex = function(classList, token) { if (token === "") { throw new DOMEx( "SYNTAX_ERR", "An invalid or illegal string was specified" ); } if (/\s/.test(token)) { throw new DOMEx( "INVALID_CHARACTER_ERR", "String contains an invalid character" ); } return arrIndexOf.call(classList, token); }, ClassList = function(elem) { var trimmedClasses = strTrim.call(elem.getAttribute("class") || ""), classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [], i = 0, len = classes.length; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function() { elem.setAttribute("class", this.toString()); }; }, classListProto = ClassList[protoProp] = [], classListGetter = function() { return new ClassList(this); }; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function(i) { return this[i] || null; }; classListProto.contains = function(token) { token += ""; return checkTokenAndGetIndex(this, token) !== -1; }; classListProto.add = function() { var tokens = arguments, i = 0, l = tokens.length, token, updated = false; do { token = tokens[i] + ""; if (checkTokenAndGetIndex(this, token) === -1) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function() { var tokens = arguments, i = 0, l = tokens.length, token, updated = false, index; do { token = tokens[i] + ""; index = checkTokenAndGetIndex(this, token); while (index !== -1) { this.splice(index, 1); updated = true; index = checkTokenAndGetIndex(this, token); } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function(token, force) { token += ""; var result = this.contains(token), method = result ? force !== true && "remove" : force !== false && "add"; if (method) { this[method](token); } if (force === true || force === false) { return force; } else { return !result; } }; classListProto.toString = function() { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter, enumerable: true, configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true if (ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } }(win)); } else if ("DOMTokenList" in win) { // There is full or partial native classList support, so just check if we need // to normalize the add/remove and toggle APIs. // DOMTokenList is expected to exist (removes conflicts with multiple polyfills present on site) (function() { "use strict"; var testElement = doc.createElement("_"); testElement.classList.add("c1", "c2"); // Polyfill for IE 10/11 and Firefox <26, where classList.add and // classList.remove exist but support only one argument at a time. if (!testElement.classList.contains("c2")) { var createMethod = function(method) { var original = win.DOMTokenList.prototype[method]; win.DOMTokenList.prototype[method] = function(token) { var i, len = arguments.length; for (i = 0; i < len; i++) { token = arguments[i]; original.call(this, token); } }; }; createMethod('add'); createMethod('remove'); } testElement.classList.toggle("c3", false); // Polyfill for IE 10 and Firefox <24, where classList.toggle does not // support the second argument. if (testElement.classList.contains("c3")) { var _toggle = win.DOMTokenList.prototype.toggle; win.DOMTokenList.prototype.toggle = function(token, force) { if (1 in arguments && !this.contains(token) === !force) { return force; } else { return _toggle.call(this, token); } }; } testElement = null; }()); } } // Safary has a bug of not restoring selection after node.normalize correctly. // Detects the misbegaviour and patches it var normalizeHasCaretError = function() { if ("createRange" in document && "getSelection" in window) { var e = document.createElement('div'), t1 = document.createTextNode('a'), t2 = document.createTextNode('a'), t3 = document.createTextNode('a'), r = document.createRange(), s, ret; e.setAttribute('contenteditable', 'true'); e.appendChild(t1); e.appendChild(t2); e.appendChild(t3); document.body.appendChild(e); r.setStart(t2, 1); r.setEnd(t2, 1); s = window.getSelection(); s.removeAllRanges(); s.addRange(r); e.normalize(); s = window.getSelection(); ret = (e.childNodes.length !== 1 || s.anchorNode !== e.firstChild || s.anchorOffset !== 2); e.parentNode.removeChild(e); s.removeAllRanges(); return ret; } }; var getTextNodes = function(node){ var all = []; for (node=node.firstChild;node;node=node.nextSibling){ if (node.nodeType == 3) { all.push(node); } else { all = all.concat(getTextNodes(node)); } } return all; }; var normalizeFix = function() { var f = Node.prototype.normalize; var nf = function() { var texts = getTextNodes(this), s = this.ownerDocument.defaultView.getSelection(), anode = s.anchorNode, aoffset = s.anchorOffset, aelement = anode && anode.nodeType === 1 && anode.childNodes.length > 0 ? anode.childNodes[aoffset] : undefined, fnode = s.focusNode, foffset = s.focusOffset, felement = fnode && fnode.nodeType === 1 && foffset > 0 ? fnode.childNodes[foffset -1] : undefined, r = this.ownerDocument.createRange(), prevTxt = texts.shift(), curText = prevTxt ? texts.shift() : null; if ((anode === fnode && foffset < aoffset) || (anode !== fnode && (anode.compareDocumentPosition(fnode) & Node.DOCUMENT_POSITION_PRECEDING) && !(anode.compareDocumentPosition(fnode) & Node.DOCUMENT_POSITION_CONTAINS))) { fnode = [anode, anode = fnode][0]; foffset = [aoffset, aoffset = foffset][0]; } while(prevTxt && curText) { if (curText.previousSibling && curText.previousSibling === prevTxt) { if (anode === curText) { anode = prevTxt; aoffset = prevTxt.nodeValue.length + aoffset; } if (fnode === curText) { fnode = prevTxt; foffset = prevTxt.nodeValue.length + foffset; } prevTxt.nodeValue = prevTxt.nodeValue + curText.nodeValue; curText.parentNode.removeChild(curText); curText = texts.shift(); } else { prevTxt = curText; curText = texts.shift(); } } if (felement) { foffset = Array.prototype.indexOf.call(felement.parentNode.childNodes, felement) + 1; } if (aelement) { aoffset = Array.prototype.indexOf.call(aelement.parentNode.childNodes, aelement); } if (anode && anode.parentNode && fnode && fnode.parentNode) { r.setStart(anode, aoffset); r.setEnd(fnode, foffset); s.removeAllRanges(); s.addRange(r); } }; Node.prototype.normalize = nf; }; if ("Node" in window && "normalize" in Node.prototype && normalizeHasCaretError()) { normalizeFix(); } }; wysihtml5.polyfills(window, document); ;/** * Rangy, a cross-browser JavaScript range and selection library * https://github.com/timdown/rangy * * Copyright 2015, Tim Down * Licensed under the MIT license. * Version: 1.3.0 * Build date: 10 May 2015 */ (function(factory, root) { if (typeof define == "function" && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof module != "undefined" && typeof exports == "object") { // Node/CommonJS style module.exports = factory(); } else { // No AMD or CommonJS support so we place Rangy in (probably) the global variable root.rangy = factory(); } })(function() { var OBJECT = "object", FUNCTION = "function", UNDEFINED = "undefined"; // Minimal set of properties required for DOM Level 2 Range compliance. Comparison constants such as START_TO_START // are omitted because ranges in KHTML do not have them but otherwise work perfectly well. See issue 113. var domRangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer"]; // Minimal set of methods required for DOM Level 2 Range compliance var domRangeMethods = ["setStart", "setStartBefore", "setStartAfter", "setEnd", "setEndBefore", "setEndAfter", "collapse", "selectNode", "selectNodeContents", "compareBoundaryPoints", "deleteContents", "extractContents", "cloneContents", "insertNode", "surroundContents", "cloneRange", "toString", "detach"]; var textRangeProperties = ["boundingHeight", "boundingLeft", "boundingTop", "boundingWidth", "htmlText", "text"]; // Subset of TextRange's full set of methods that we're interested in var textRangeMethods = ["collapse", "compareEndPoints", "duplicate", "moveToElementText", "parentElement", "select", "setEndPoint", "getBoundingClientRect"]; /*----------------------------------------------------------------------------------------------------------------*/ // Trio of functions taken from Peter Michaux's article: // http://peter.michaux.ca/articles/feature-detection-state-of-the-art-browser-scripting function isHostMethod(o, p) { var t = typeof o[p]; return t == FUNCTION || (!!(t == OBJECT && o[p])) || t == "unknown"; } function isHostObject(o, p) { return !!(typeof o[p] == OBJECT && o[p]); } function isHostProperty(o, p) { return typeof o[p] != UNDEFINED; } // Creates a convenience function to save verbose repeated calls to tests functions function createMultiplePropertyTest(testFunc) { return function(o, props) { var i = props.length; while (i--) { if (!testFunc(o, props[i])) { return false; } } return true; }; } // Next trio of functions are a convenience to save verbose repeated calls to previous two functions var areHostMethods = createMultiplePropertyTest(isHostMethod); var areHostObjects = createMultiplePropertyTest(isHostObject); var areHostProperties = createMultiplePropertyTest(isHostProperty); function isTextRange(range) { return range && areHostMethods(range, textRangeMethods) && areHostProperties(range, textRangeProperties); } function getBody(doc) { return isHostObject(doc, "body") ? doc.body : doc.getElementsByTagName("body")[0]; } var forEach = [].forEach ? function(arr, func) { arr.forEach(func); } : function(arr, func) { for (var i = 0, len = arr.length; i < len; ++i) { func(arr[i], i); } }; var modules = {}; var isBrowser = (typeof window != UNDEFINED && typeof document != UNDEFINED); var util = { isHostMethod: isHostMethod, isHostObject: isHostObject, isHostProperty: isHostProperty, areHostMethods: areHostMethods, areHostObjects: areHostObjects, areHostProperties: areHostProperties, isTextRange: isTextRange, getBody: getBody, forEach: forEach }; var api = { version: "1.3.0", initialized: false, isBrowser: isBrowser, supported: true, util: util, features: {}, modules: modules, config: { alertOnFail: false, alertOnWarn: false, preferTextRange: false, autoInitialize: (typeof rangyAutoInitialize == UNDEFINED) ? true : rangyAutoInitialize } }; function consoleLog(msg) { if (typeof console != UNDEFINED && isHostMethod(console, "log")) { console.log(msg); } } function alertOrLog(msg, shouldAlert) { if (isBrowser && shouldAlert) { alert(msg); } else { consoleLog(msg); } } function fail(reason) { api.initialized = true; api.supported = false; alertOrLog("Rangy is not supported in this environment. Reason: " + reason, api.config.alertOnFail); } api.fail = fail; function warn(msg) { alertOrLog("Rangy warning: " + msg, api.config.alertOnWarn); } api.warn = warn; // Add utility extend() method var extend; if ({}.hasOwnProperty) { util.extend = extend = function(obj, props, deep) { var o, p; for (var i in props) { if (props.hasOwnProperty(i)) { o = obj[i]; p = props[i]; if (deep && o !== null && typeof o == "object" && p !== null && typeof p == "object") { extend(o, p, true); } obj[i] = p; } } // Special case for toString, which does not show up in for...in loops in IE <= 8 if (props.hasOwnProperty("toString")) { obj.toString = props.toString; } return obj; }; util.createOptions = function(optionsParam, defaults) { var options = {}; extend(options, defaults); if (optionsParam) { extend(options, optionsParam); } return options; }; } else { fail("hasOwnProperty not supported"); } // Test whether we're in a browser and bail out if not if (!isBrowser) { fail("Rangy can only run in a browser"); } // Test whether Array.prototype.slice can be relied on for NodeLists and use an alternative toArray() if not (function() { var toArray; if (isBrowser) { var el = document.createElement("div"); el.appendChild(document.createElement("span")); var slice = [].slice; try { if (slice.call(el.childNodes, 0)[0].nodeType == 1) { toArray = function(arrayLike) { return slice.call(arrayLike, 0); }; } } catch (e) {} } if (!toArray) { toArray = function(arrayLike) { var arr = []; for (var i = 0, len = arrayLike.length; i < len; ++i) { arr[i] = arrayLike[i]; } return arr; }; } util.toArray = toArray; })(); // Very simple event handler wrapper function that doesn't attempt to solve issues such as "this" handling or // normalization of event properties var addListener; if (isBrowser) { if (isHostMethod(document, "addEventListener")) { addListener = function(obj, eventType, listener) { obj.addEventListener(eventType, listener, false); }; } else if (isHostMethod(document, "attachEvent")) { addListener = function(obj, eventType, listener) { obj.attachEvent("on" + eventType, listener); }; } else { fail("Document does not have required addEventListener or attachEvent method"); } util.addListener = addListener; } var initListeners = []; function getErrorDesc(ex) { return ex.message || ex.description || String(ex); } // Initialization function init() { if (!isBrowser || api.initialized) { return; } var testRange; var implementsDomRange = false, implementsTextRange = false; // First, perform basic feature tests if (isHostMethod(document, "createRange")) { testRange = document.createRange(); if (areHostMethods(testRange, domRangeMethods) && areHostProperties(testRange, domRangeProperties)) { implementsDomRange = true; } } var body = getBody(document); if (!body || body.nodeName.toLowerCase() != "body") { fail("No body element found"); return; } if (body && isHostMethod(body, "createTextRange")) { testRange = body.createTextRange(); if (isTextRange(testRange)) { implementsTextRange = true; } } if (!implementsDomRange && !implementsTextRange) { fail("Neither Range nor TextRange are available"); return; } api.initialized = true; api.features = { implementsDomRange: implementsDomRange, implementsTextRange: implementsTextRange }; // Initialize modules var module, errorMessage; for (var moduleName in modules) { if ( (module = modules[moduleName]) instanceof Module ) { module.init(module, api); } } // Call init listeners for (var i = 0, len = initListeners.length; i < len; ++i) { try { initListeners[i](api); } catch (ex) { errorMessage = "Rangy init listener threw an exception. Continuing. Detail: " + getErrorDesc(ex); consoleLog(errorMessage); } } } function deprecationNotice(deprecated, replacement, module) { if (module) { deprecated += " in module " + module.name; } api.warn("DEPRECATED: " + deprecated + " is deprecated. Please use " + replacement + " instead."); } function createAliasForDeprecatedMethod(owner, deprecated, replacement, module) { owner[deprecated] = function() { deprecationNotice(deprecated, replacement, module); return owner[replacement].apply(owner, util.toArray(arguments)); }; } util.deprecationNotice = deprecationNotice; util.createAliasForDeprecatedMethod = createAliasForDeprecatedMethod; // Allow external scripts to initialize this library in case it's loaded after the document has loaded api.init = init; // Execute listener immediately if already initialized api.addInitListener = function(listener) { if (api.initialized) { listener(api); } else { initListeners.push(listener); } }; var shimListeners = []; api.addShimListener = function(listener) { shimListeners.push(listener); }; function shim(win) { win = win || window; init(); // Notify listeners for (var i = 0, len = shimListeners.length; i < len; ++i) { shimListeners[i](win); } } if (isBrowser) { api.shim = api.createMissingNativeApi = shim; createAliasForDeprecatedMethod(api, "createMissingNativeApi", "shim"); } function Module(name, dependencies, initializer) { this.name = name; this.dependencies = dependencies; this.initialized = false; this.supported = false; this.initializer = initializer; } Module.prototype = { init: function() { var requiredModuleNames = this.dependencies || []; for (var i = 0, len = requiredModuleNames.length, requiredModule, moduleName; i < len; ++i) { moduleName = requiredModuleNames[i]; requiredModule = modules[moduleName]; if (!requiredModule || !(requiredModule instanceof Module)) { throw new Error("required module '" + moduleName + "' not found"); } requiredModule.init(); if (!requiredModule.supported) { throw new Error("required module '" + moduleName + "' not supported"); } } // Now run initializer this.initializer(this); }, fail: function(reason) { this.initialized = true; this.supported = false; throw new Error(reason); }, warn: function(msg) { api.warn("Module " + this.name + ": " + msg); }, deprecationNotice: function(deprecated, replacement) { api.warn("DEPRECATED: " + deprecated + " in module " + this.name + " is deprecated. Please use " + replacement + " instead"); }, createError: function(msg) { return new Error("Error in Rangy " + this.name + " module: " + msg); } }; function createModule(name, dependencies, initFunc) { var newModule = new Module(name, dependencies, function(module) { if (!module.initialized) { module.initialized = true; try { initFunc(api, module); module.supported = true; } catch (ex) { var errorMessage = "Module '" + name + "' failed to load: " + getErrorDesc(ex); consoleLog(errorMessage); if (ex.stack) { consoleLog(ex.stack); } } } }); modules[name] = newModule; return newModule; } api.createModule = function(name) { // Allow 2 or 3 arguments (second argument is an optional array of dependencies) var initFunc, dependencies; if (arguments.length == 2) { initFunc = arguments[1]; dependencies = []; } else { initFunc = arguments[2]; dependencies = arguments[1]; } var module = createModule(name, dependencies, initFunc); // Initialize the module immediately if the core is already initialized if (api.initialized && api.supported) { module.init(); } }; api.createCoreModule = function(name, dependencies, initFunc) { createModule(name, dependencies, initFunc); }; /*----------------------------------------------------------------------------------------------------------------*/ // Ensure rangy.rangePrototype and rangy.selectionPrototype are available immediately function RangePrototype() {} api.RangePrototype = RangePrototype; api.rangePrototype = new RangePrototype(); function SelectionPrototype() {} api.selectionPrototype = new SelectionPrototype(); /*----------------------------------------------------------------------------------------------------------------*/ // DOM utility methods used by Rangy api.createCoreModule("DomUtil", [], function(api, module) { var UNDEF = "undefined"; var util = api.util; var getBody = util.getBody; // Perform feature tests if (!util.areHostMethods(document, ["createDocumentFragment", "createElement", "createTextNode"])) { module.fail("document missing a Node creation method"); } if (!util.isHostMethod(document, "getElementsByTagName")) { module.fail("document missing getElementsByTagName method"); } var el = document.createElement("div"); if (!util.areHostMethods(el, ["insertBefore", "appendChild", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]))) { module.fail("Incomplete Element implementation"); } // innerHTML is required for Range's createContextualFragment method if (!util.isHostProperty(el, "innerHTML")) { module.fail("Element is missing innerHTML property"); } var textNode = document.createTextNode("test"); if (!util.areHostMethods(textNode, ["splitText", "deleteData", "insertData", "appendData", "cloneNode"] || !util.areHostObjects(el, ["previousSibling", "nextSibling", "childNodes", "parentNode"]) || !util.areHostProperties(textNode, ["data"]))) { module.fail("Incomplete Text Node implementation"); } /*----------------------------------------------------------------------------------------------------------------*/ // Removed use of indexOf because of a bizarre bug in Opera that is thrown in one of the Acid3 tests. I haven't been // able to replicate it outside of the test. The bug is that indexOf returns -1 when called on an Array that // contains just the document as a single element and the value searched for is the document. var arrayContains = /*Array.prototype.indexOf ? function(arr, val) { return arr.indexOf(val) > -1; }:*/ function(arr, val) { var i = arr.length; while (i--) { if (arr[i] === val) { return true; } } return false; }; // Opera 11 puts HTML elements in the null namespace, it seems, and IE 7 has undefined namespaceURI function isHtmlNamespace(node) { var ns; return typeof node.namespaceURI == UNDEF || ((ns = node.namespaceURI) === null || ns == "http://www.w3.org/1999/xhtml"); } function parentElement(node) { var parent = node.parentNode; return (parent.nodeType == 1) ? parent : null; } function getNodeIndex(node) { var i = 0; while( (node = node.previousSibling) ) { ++i; } return i; } function getNodeLength(node) { switch (node.nodeType) { case 7: case 10: return 0; case 3: case 8: return node.length; default: return node.childNodes.length; } } function getCommonAncestor(node1, node2) { var ancestors = [], n; for (n = node1; n; n = n.parentNode) { ancestors.push(n); } for (n = node2; n; n = n.parentNode) { if (arrayContains(ancestors, n)) { return n; } } return null; } function isAncestorOf(ancestor, descendant, selfIsAncestor) { var n = selfIsAncestor ? descendant : descendant.parentNode; while (n) { if (n === ancestor) { return true; } else { n = n.parentNode; } } return false; } function isOrIsAncestorOf(ancestor, descendant) { return isAncestorOf(ancestor, descendant, true); } function getClosestAncestorIn(node, ancestor, selfIsAncestor) { var p, n = selfIsAncestor ? node : node.parentNode; while (n) { p = n.parentNode; if (p === ancestor) { return n; } n = p; } return null; } function isCharacterDataNode(node) { var t = node.nodeType; return t == 3 || t == 4 || t == 8 ; // Text, CDataSection or Comment } function isTextOrCommentNode(node) { if (!node) { return false; } var t = node.nodeType; return t == 3 || t == 8 ; // Text or Comment } function insertAfter(node, precedingNode) { var nextNode = precedingNode.nextSibling, parent = precedingNode.parentNode; if (nextNode) { parent.insertBefore(node, nextNode); } else { parent.appendChild(node); } return node; } // Note that we cannot use splitText() because it is bugridden in IE 9. function splitDataNode(node, index, positionsToPreserve) { var newNode = node.cloneNode(false); newNode.deleteData(0, index); node.deleteData(index, node.length - index); insertAfter(newNode, node); // Preserve positions if (positionsToPreserve) { for (var i = 0, position; position = positionsToPreserve[i++]; ) { // Handle case where position was inside the portion of node after the split point if (position.node == node && position.offset > index) { position.node = newNode; position.offset -= index; } // Handle the case where the position is a node offset within node's parent else if (position.node == node.parentNode && position.offset > getNodeIndex(node)) { ++position.offset; } } } return newNode; } function getDocument(node) { if (node.nodeType == 9) { return node; } else if (typeof node.ownerDocument != UNDEF) { return node.ownerDocument; } else if (typeof node.document != UNDEF) { return node.document; } else if (node.parentNode) { return getDocument(node.parentNode); } else { throw module.createError("getDocument: no document found for node"); } } function getWindow(node) { var doc = getDocument(node); if (typeof doc.defaultView != UNDEF) { return doc.defaultView; } else if (typeof doc.parentWindow != UNDEF) { return doc.parentWindow; } else { throw module.createError("Cannot get a window object for node"); } } function getIframeDocument(iframeEl) { if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument; } else if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow.document; } else { throw module.createError("getIframeDocument: No Document object found for iframe element"); } } function getIframeWindow(iframeEl) { if (typeof iframeEl.contentWindow != UNDEF) { return iframeEl.contentWindow; } else if (typeof iframeEl.contentDocument != UNDEF) { return iframeEl.contentDocument.defaultView; } else { throw module.createError("getIframeWindow: No Window object found for iframe element"); } } // This looks bad. Is it worth it? function isWindow(obj) { return obj && util.isHostMethod(obj, "setTimeout") && util.isHostObject(obj, "document"); } function getContentDocument(obj, module, methodName) { var doc; if (!obj) { doc = document; } // Test if a DOM node has been passed and obtain a document object for it if so else if (util.isHostProperty(obj, "nodeType")) { doc = (obj.nodeType == 1 && obj.tagName.toLowerCase() == "iframe") ? getIframeDocument(obj) : getDocument(obj); } // Test if the doc parameter appears to be a Window object else if (isWindow(obj)) { doc = obj.document; } if (!doc) { throw module.createError(methodName + "(): Parameter must be a Window object or DOM node"); } return doc; } function getRootContainer(node) { var parent; while ( (parent = node.parentNode) ) { node = parent; } return node; } function comparePoints(nodeA, offsetA, nodeB, offsetB) { // See http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html#Level-2-Range-Comparing var nodeC, root, childA, childB, n; if (nodeA == nodeB) { // Case 1: nodes are the same return offsetA === offsetB ? 0 : (offsetA < offsetB) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeB, nodeA, true)) ) { // Case 2: node C (container B or an ancestor) is a child node of A return offsetA <= getNodeIndex(nodeC) ? -1 : 1; } else if ( (nodeC = getClosestAncestorIn(nodeA, nodeB, true)) ) { // Case 3: node C (container A or an ancestor) is a child node of B return getNodeIndex(nodeC) < offsetB ? -1 : 1; } else { root = getCommonAncestor(nodeA, nodeB); if (!root) { throw new Error("comparePoints error: nodes have no common ancestor"); } // Case 4: containers are siblings or descendants of siblings childA = (nodeA === root) ? root : getClosestAncestorIn(nodeA, root, true); childB = (nodeB === root) ? root : getClosestAncestorIn(nodeB, root, true); if (childA === childB) { // This shouldn't be possible throw module.createError("comparePoints got to case 4 and childA and childB are the same!"); } else { n = root.firstChild; while (n) { if (n === childA) { return -1; } else if (n === childB) { return 1; } n = n.nextSibling; } } } } /*----------------------------------------------------------------------------------------------------------------*/ // Test for IE's crash (IE 6/7) or exception (IE >= 8) when a reference to garbage-collected text node is queried var crashyTextNodes = false; function isBrokenNode(node) { var n; try { n = node.parentNode; return false; } catch (e) { return true; } } (function() { var el = document.createElement("b"); el.innerHTML = "1"; var textNode = el.firstChild; el.innerHTML = "<br />"; crashyTextNodes = isBrokenNode(textNode); api.features.crashyTextNodes = crashyTextNodes; })(); /*----------------------------------------------------------------------------------------------------------------*/ function inspectNode(node) { if (!node) { return "[No node]"; } if (crashyTextNodes && isBrokenNode(node)) { return "[Broken node]"; } if (isCharacterDataNode(node)) { return '"' + node.data + '"'; } if (node.nodeType == 1) { var idAttr = node.id ? ' id="' + node.id + '"' : ""; return "<" + node.nodeName + idAttr + ">[index:" + getNodeIndex(node) + ",length:" + node.childNodes.length + "][" + (node.innerHTML || "[innerHTML not supported]").slice(0, 25) + "]"; } return node.nodeName; } function fragmentFromNodeChildren(node) { var fragment = getDocument(node).createDocumentFragment(), child; while ( (child = node.firstChild) ) { fragment.appendChild(child); } return fragment; } var getComputedStyleProperty; if (typeof window.getComputedStyle != UNDEF) { getComputedStyleProperty = function(el, propName) { return getWindow(el).getComputedStyle(el, null)[propName]; }; } else if (typeof document.documentElement.currentStyle != UNDEF) { getComputedStyleProperty = function(el, propName) { return el.currentStyle ? el.currentStyle[propName] : ""; }; } else { module.fail("No means of obtaining computed style properties found"); } function createTestElement(doc, html, contentEditable) { var body = getBody(doc); var el = doc.createElement("div"); el.contentEditable = "" + !!contentEditable; if (html) { el.innerHTML = html; } // Insert the test element at the start of the body to prevent scrolling to the bottom in iOS (issue #292) var bodyFirstChild = body.firstChild; if (bodyFirstChild) { body.insertBefore(el, bodyFirstChild); } else { body.appendChild(el); } return el; } function removeNode(node) { return node.parentNode.removeChild(node); } function NodeIterator(root) { this.root = root; this._next = root; } NodeIterator.prototype = { _current: null, hasNext: function() { return !!this._next; }, next: function() { var n = this._current = this._next; var child, next; if (this._current) { child = n.firstChild; if (child) { this._next = child; } else { next = null; while ((n !== this.root) && !(next = n.nextSibling)) { n = n.parentNode; } this._next = next; } } return this._current; }, detach: function() { this._current = this._next = this.root = null; } }; function createIterator(root) { return new NodeIterator(root); } function DomPosition(node, offset) { this.node = node; this.offset = offset; } DomPosition.prototype = { equals: function(pos) { return !!pos && this.node === pos.node && this.offset == pos.offset; }, inspect: function() { return "[DomPosition(" + inspectNode(this.node) + ":" + this.offset + ")]"; }, toString: function() { return this.inspect(); } }; function DOMException(codeName) { this.code = this[codeName]; this.codeName = codeName; this.message = "DOMException: " + this.codeName; } DOMException.prototype = { INDEX_SIZE_ERR: 1, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INVALID_STATE_ERR: 11, INVALID_NODE_TYPE_ERR: 24 }; DOMException.prototype.toString = function() { return this.message; }; api.dom = { arrayContains: arrayContains, isHtmlNamespace: isHtmlNamespace, parentElement: parentElement, getNodeIndex: getNodeIndex, getNodeLength: getNodeLength, getCommonAncestor: getCommonAncestor, isAncestorOf: isAncestorOf, isOrIsAncestorOf: isOrIsAncestorOf, getClosestAncestorIn: getClosestAncestorIn, isCharacterDataNode: isCharacterDataNode, isTextOrCommentNode: isTextOrCommentNode, insertAfter: insertAfter, splitDataNode: splitDataNode, getDocument: getDocument, getWindow: getWindow, getIframeWindow: getIframeWindow, getIframeDocument: getIframeDocument, getBody: getBody, isWindow: isWindow, getContentDocument: getContentDocument, getRootContainer: getRootContainer, comparePoints: comparePoints, isBrokenNode: isBrokenNode, inspectNode: inspectNode, getComputedStyleProperty: getComputedStyleProperty, createTestElement: createTestElement, removeNode: removeNode, fragmentFromNodeChildren: fragmentFromNodeChildren, createIterator: createIterator, DomPosition: DomPosition }; api.DOMException = DOMException; }); /*----------------------------------------------------------------------------------------------------------------*/ // Pure JavaScript implementation of DOM Range api.createCoreModule("DomRange", ["DomUtil"], function(api, module) { var dom = api.dom; var util = api.util; var DomPosition = dom.DomPosition; var DOMException = api.DOMException; var isCharacterDataNode = dom.isCharacterDataNode; var getNodeIndex = dom.getNodeIndex; var isOrIsAncestorOf = dom.isOrIsAncestorOf; var getDocument = dom.getDocument; var comparePoints = dom.comparePoints; var splitDataNode = dom.splitDataNode; var getClosestAncestorIn = dom.getClosestAncestorIn; var getNodeLength = dom.getNodeLength; var arrayContains = dom.arrayContains; var getRootContainer = dom.getRootContainer; var crashyTextNodes = api.features.crashyTextNodes; var removeNode = dom.removeNode; /*----------------------------------------------------------------------------------------------------------------*/ // Utility functions function isNonTextPartiallySelected(node, range) { return (node.nodeType != 3) && (isOrIsAncestorOf(node, range.startContainer) || isOrIsAncestorOf(node, range.endContainer)); } function getRangeDocument(range) { return range.document || getDocument(range.startContainer); } function getRangeRoot(range) { return getRootContainer(range.startContainer); } function getBoundaryBeforeNode(node) { return new DomPosition(node.parentNode, getNodeIndex(node)); } function getBoundaryAfterNode(node) { return new DomPosition(node.parentNode, getNodeIndex(node) + 1); } function insertNodeAtPosition(node, n, o) { var firstNodeInserted = node.nodeType == 11 ? node.firstChild : node; if (isCharacterDataNode(n)) { if (o == n.length) { dom.insertAfter(node, n); } else { n.parentNode.insertBefore(node, o == 0 ? n : splitDataNode(n, o)); } } else if (o >= n.childNodes.length) { n.appendChild(node); } else { n.insertBefore(node, n.childNodes[o]); } return firstNodeInserted; } function rangesIntersect(rangeA, rangeB, touchingIsIntersecting) { assertRangeValid(rangeA); assertRangeValid(rangeB); if (getRangeDocument(rangeB) != getRangeDocument(rangeA)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } var startComparison = comparePoints(rangeA.startContainer, rangeA.startOffset, rangeB.endContainer, rangeB.endOffset), endComparison = comparePoints(rangeA.endContainer, rangeA.endOffset, rangeB.startContainer, rangeB.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; } function cloneSubtree(iterator) { var partiallySelected; for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { partiallySelected = iterator.isPartiallySelectedSubtree(); node = node.cloneNode(!partiallySelected); if (partiallySelected) { subIterator = iterator.getSubtreeIterator(); node.appendChild(cloneSubtree(subIterator)); subIterator.detach(); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function iterateSubtree(rangeIterator, func, iteratorState) { var it, n; iteratorState = iteratorState || { stop: false }; for (var node, subRangeIterator; node = rangeIterator.next(); ) { if (rangeIterator.isPartiallySelectedSubtree()) { if (func(node) === false) { iteratorState.stop = true; return; } else { // The node is partially selected by the Range, so we can use a new RangeIterator on the portion of // the node selected by the Range. subRangeIterator = rangeIterator.getSubtreeIterator(); iterateSubtree(subRangeIterator, func, iteratorState); subRangeIterator.detach(); if (iteratorState.stop) { return; } } } else { // The whole node is selected, so we can use efficient DOM iteration to iterate over the node and its // descendants it = dom.createIterator(node); while ( (n = it.next()) ) { if (func(n) === false) { iteratorState.stop = true; return; } } } } } function deleteSubtree(iterator) { var subIterator; while (iterator.next()) { if (iterator.isPartiallySelectedSubtree()) { subIterator = iterator.getSubtreeIterator(); deleteSubtree(subIterator); subIterator.detach(); } else { iterator.remove(); } } } function extractSubtree(iterator) { for (var node, frag = getRangeDocument(iterator.range).createDocumentFragment(), subIterator; node = iterator.next(); ) { if (iterator.isPartiallySelectedSubtree()) { node = node.cloneNode(false); subIterator = iterator.getSubtreeIterator(); node.appendChild(extractSubtree(subIterator)); subIterator.detach(); } else { iterator.remove(); } if (node.nodeType == 10) { // DocumentType throw new DOMException("HIERARCHY_REQUEST_ERR"); } frag.appendChild(node); } return frag; } function getNodesInRange(range, nodeTypes, filter) { var filterNodeTypes = !!(nodeTypes && nodeTypes.length), regex; var filterExists = !!filter; if (filterNodeTypes) { regex = new RegExp("^(" + nodeTypes.join("|") + ")$"); } var nodes = []; iterateSubtree(new RangeIterator(range, false), function(node) { if (filterNodeTypes && !regex.test(node.nodeType)) { return; } if (filterExists && !filter(node)) { return; } // Don't include a boundary container if it is a character data node and the range does not contain any // of its character data. See issue 190. var sc = range.startContainer; if (node == sc && isCharacterDataNode(sc) && range.startOffset == sc.length) { return; } var ec = range.endContainer; if (node == ec && isCharacterDataNode(ec) && range.endOffset == 0) { return; } nodes.push(node); }); return nodes; } function inspect(range) { var name = (typeof range.getName == "undefined") ? "Range" : range.getName(); return "[" + name + "(" + dom.inspectNode(range.startContainer) + ":" + range.startOffset + ", " + dom.inspectNode(range.endContainer) + ":" + range.endOffset + ")]"; } /*----------------------------------------------------------------------------------------------------------------*/ // RangeIterator code partially borrows from IERange by Tim Ryan (http://github.com/timcameronryan/IERange) function RangeIterator(range, clonePartiallySelectedTextNodes) { this.range = range; this.clonePartiallySelectedTextNodes = clonePartiallySelectedTextNodes; if (!range.collapsed) { this.sc = range.startContainer; this.so = range.startOffset; this.ec = range.endContainer; this.eo = range.endOffset; var root = range.commonAncestorContainer; if (this.sc === this.ec && isCharacterDataNode(this.sc)) { this.isSingleCharacterDataNode = true; this._first = this._last = this._next = this.sc; } else { this._first = this._next = (this.sc === root && !isCharacterDataNode(this.sc)) ? this.sc.childNodes[this.so] : getClosestAncestorIn(this.sc, root, true); this._last = (this.ec === root && !isCharacterDataNode(this.ec)) ? this.ec.childNodes[this.eo - 1] : getClosestAncestorIn(this.ec, root, true); } } } RangeIterator.prototype = { _current: null, _next: null, _first: null, _last: null, isSingleCharacterDataNode: false, reset: function() { this._current = null; this._next = this._first; }, hasNext: function() { return !!this._next; }, next: function() { // Move to next node var current = this._current = this._next; if (current) { this._next = (current !== this._last) ? current.nextSibling : null; // Check for partially selected text nodes if (isCharacterDataNode(current) && this.clonePartiallySelectedTextNodes) { if (current === this.ec) { (current = current.cloneNode(true)).deleteData(this.eo, current.length - this.eo); } if (this._current === this.sc) { (current = current.cloneNode(true)).deleteData(0, this.so); } } } return current; }, remove: function() { var current = this._current, start, end; if (isCharacterDataNode(current) && (current === this.sc || current === this.ec)) { start = (current === this.sc) ? this.so : 0; end = (current === this.ec) ? this.eo : current.length; if (start != end) { current.deleteData(start, end - start); } } else { if (current.parentNode) { removeNode(current); } else { } } }, // Checks if the current node is partially selected isPartiallySelectedSubtree: function() { var current = this._current; return isNonTextPartiallySelected(current, this.range); }, getSubtreeIterator: function() { var subRange; if (this.isSingleCharacterDataNode) { subRange = this.range.cloneRange(); subRange.collapse(false); } else { subRange = new Range(getRangeDocument(this.range)); var current = this._current; var startContainer = current, startOffset = 0, endContainer = current, endOffset = getNodeLength(current); if (isOrIsAncestorOf(current, this.sc)) { startContainer = this.sc; startOffset = this.so; } if (isOrIsAncestorOf(current, this.ec)) { endContainer = this.ec; endOffset = this.eo; } updateBoundaries(subRange, startContainer, startOffset, endContainer, endOffset); } return new RangeIterator(subRange, this.clonePartiallySelectedTextNodes); }, detach: function() { this.range = this._current = this._next = this._first = this._last = this.sc = this.so = this.ec = this.eo = null; } }; /*----------------------------------------------------------------------------------------------------------------*/ var beforeAfterNodeTypes = [1, 3, 4, 5, 7, 8, 10]; var rootContainerNodeTypes = [2, 9, 11]; var readonlyNodeTypes = [5, 6, 10, 12]; var insertableNodeTypes = [1, 3, 4, 5, 7, 8, 10, 11]; var surroundNodeTypes = [1, 3, 4, 5, 7, 8]; function createAncestorFinder(nodeTypes) { return function(node, selfIsAncestor) { var t, n = selfIsAncestor ? node : node.parentNode; while (n) { t = n.nodeType; if (arrayContains(nodeTypes, t)) { return n; } n = n.parentNode; } return null; }; } var getDocumentOrFragmentContainer = createAncestorFinder( [9, 11] ); var getReadonlyAncestor = createAncestorFinder(readonlyNodeTypes); var getDocTypeNotationEntityAncestor = createAncestorFinder( [6, 10, 12] ); function assertNoDocTypeNotationEntityAncestor(node, allowSelf) { if (getDocTypeNotationEntityAncestor(node, allowSelf)) { throw new DOMException("INVALID_NODE_TYPE_ERR"); } } function assertValidNodeType(node, invalidTypes) { if (!arrayContains(invalidTypes, node.nodeType)) { throw new DOMException("INVALID_NODE_TYPE_ERR"); } } function assertValidOffset(node, offset) { if (offset < 0 || offset > (isCharacterDataNode(node) ? node.length : node.childNodes.length)) { throw new DOMException("INDEX_SIZE_ERR"); } } function assertSameDocumentOrFragment(node1, node2) { if (getDocumentOrFragmentContainer(node1, true) !== getDocumentOrFragmentContainer(node2, true)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } function assertNodeNotReadOnly(node) { if (getReadonlyAncestor(node, true)) { throw new DOMException("NO_MODIFICATION_ALLOWED_ERR"); } } function assertNode(node, codeName) { if (!node) { throw new DOMException(codeName); } } function isValidOffset(node, offset) { return offset <= (isCharacterDataNode(node) ? node.length : node.childNodes.length); } function isRangeValid(range) { return (!!range.startContainer && !!range.endContainer && !(crashyTextNodes && (dom.isBrokenNode(range.startContainer) || dom.isBrokenNode(range.endContainer))) && getRootContainer(range.startContainer) == getRootContainer(range.endContainer) && isValidOffset(range.startContainer, range.startOffset) && isValidOffset(range.endContainer, range.endOffset)); } function assertRangeValid(range) { if (!isRangeValid(range)) { throw new Error("Range error: Range is not valid. This usually happens after DOM mutation. Range: (" + range.inspect() + ")"); } } /*----------------------------------------------------------------------------------------------------------------*/ // Test the browser's innerHTML support to decide how to implement createContextualFragment var styleEl = document.createElement("style"); var htmlParsingConforms = false; try { styleEl.innerHTML = "<b>x</b>"; htmlParsingConforms = (styleEl.firstChild.nodeType == 3); // Opera incorrectly creates an element node } catch (e) { // IE 6 and 7 throw } api.features.htmlParsingConforms = htmlParsingConforms; var createContextualFragment = htmlParsingConforms ? // Implementation as per HTML parsing spec, trusting in the browser's implementation of innerHTML. See // discussion and base code for this implementation at issue 67. // Spec: http://html5.org/specs/dom-parsing.html#extensions-to-the-range-interface // Thanks to Aleks Williams. function(fragmentStr) { // "Let node the context object's start's node." var node = this.startContainer; var doc = getDocument(node); // "If the context object's start's node is null, raise an INVALID_STATE_ERR // exception and abort these steps." if (!node) { throw new DOMException("INVALID_STATE_ERR"); } // "Let element be as follows, depending on node's interface:" // Document, Document Fragment: null var el = null; // "Element: node" if (node.nodeType == 1) { el = node; // "Text, Comment: node's parentElement" } else if (isCharacterDataNode(node)) { el = dom.parentElement(node); } // "If either element is null or element's ownerDocument is an HTML document // and element's local name is "html" and element's namespace is the HTML // namespace" if (el === null || ( el.nodeName == "HTML" && dom.isHtmlNamespace(getDocument(el).documentElement) && dom.isHtmlNamespace(el) )) { // "let element be a new Element with "body" as its local name and the HTML // namespace as its namespace."" el = doc.createElement("body"); } else { el = el.cloneNode(false); } // "If the node's document is an HTML document: Invoke the HTML fragment parsing algorithm." // "If the node's document is an XML document: Invoke the XML fragment parsing algorithm." // "In either case, the algorithm must be invoked with fragment as the input // and element as the context element." el.innerHTML = fragmentStr; // "If this raises an exception, then abort these steps. Otherwise, let new // children be the nodes returned." // "Let fragment be a new DocumentFragment." // "Append all new children to fragment." // "Return fragment." return dom.fragmentFromNodeChildren(el); } : // In this case, innerHTML cannot be trusted, so fall back to a simpler, non-conformant implementation that // previous versions of Rangy used (with the exception of using a body element rather than a div) function(fragmentStr) { var doc = getRangeDocument(this); var el = doc.createElement("body"); el.innerHTML = fragmentStr; return dom.fragmentFromNodeChildren(el); }; function splitRangeBoundaries(range, positionsToPreserve) { assertRangeValid(range); var sc = range.startContainer, so = range.startOffset, ec = range.endContainer, eo = range.endOffset; var startEndSame = (sc === ec); if (isCharacterDataNode(ec) && eo > 0 && eo < ec.length) { splitDataNode(ec, eo, positionsToPreserve); } if (isCharacterDataNode(sc) && so > 0 && so < sc.length) { sc = splitDataNode(sc, so, positionsToPreserve); if (startEndSame) { eo -= so; ec = sc; } else if (ec == sc.parentNode && eo >= getNodeIndex(sc)) { eo++; } so = 0; } range.setStartAndEnd(sc, so, ec, eo); } function rangeToHtml(range) { assertRangeValid(range); var container = range.commonAncestorContainer.parentNode.cloneNode(false); container.appendChild( range.cloneContents() ); return container.innerHTML; } /*----------------------------------------------------------------------------------------------------------------*/ var rangeProperties = ["startContainer", "startOffset", "endContainer", "endOffset", "collapsed", "commonAncestorContainer"]; var s2s = 0, s2e = 1, e2e = 2, e2s = 3; var n_b = 0, n_a = 1, n_b_a = 2, n_i = 3; util.extend(api.rangePrototype, { compareBoundaryPoints: function(how, range) { assertRangeValid(this); assertSameDocumentOrFragment(this.startContainer, range.startContainer); var nodeA, offsetA, nodeB, offsetB; var prefixA = (how == e2s || how == s2s) ? "start" : "end"; var prefixB = (how == s2e || how == s2s) ? "start" : "end"; nodeA = this[prefixA + "Container"]; offsetA = this[prefixA + "Offset"]; nodeB = range[prefixB + "Container"]; offsetB = range[prefixB + "Offset"]; return comparePoints(nodeA, offsetA, nodeB, offsetB); }, insertNode: function(node) { assertRangeValid(this); assertValidNodeType(node, insertableNodeTypes); assertNodeNotReadOnly(this.startContainer); if (isOrIsAncestorOf(node, this.startContainer)) { throw new DOMException("HIERARCHY_REQUEST_ERR"); } // No check for whether the container of the start of the Range is of a type that does not allow // children of the type of node: the browser's DOM implementation should do this for us when we attempt // to add the node var firstNodeInserted = insertNodeAtPosition(node, this.startContainer, this.startOffset); this.setStartBefore(firstNodeInserted); }, cloneContents: function() { assertRangeValid(this); var clone, frag; if (this.collapsed) { return getRangeDocument(this).createDocumentFragment(); } else { if (this.startContainer === this.endContainer && isCharacterDataNode(this.startContainer)) { clone = this.startContainer.cloneNode(true); clone.data = clone.data.slice(this.startOffset, this.endOffset); frag = getRangeDocument(this).createDocumentFragment(); frag.appendChild(clone); return frag; } else { var iterator = new RangeIterator(this, true); clone = cloneSubtree(iterator); iterator.detach(); } return clone; } }, canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && (isNonTextPartiallySelected(iterator._first, this)) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, surroundContents: function(node) { assertValidNodeType(node, surroundNodeTypes); if (!this.canSurroundContents()) { throw new DOMException("INVALID_STATE_ERR"); } // Extract the contents var content = this.extractContents(); // Clear the children of the node if (node.hasChildNodes()) { while (node.lastChild) { node.removeChild(node.lastChild); } } // Insert the new node and add the extracted contents insertNodeAtPosition(node, this.startContainer, this.startOffset); node.appendChild(content); this.selectNode(node); }, cloneRange: function() { assertRangeValid(this); var range = new Range(getRangeDocument(this)); var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = this[prop]; } return range; }, toString: function() { assertRangeValid(this); var sc = this.startContainer; if (sc === this.endContainer && isCharacterDataNode(sc)) { return (sc.nodeType == 3 || sc.nodeType == 4) ? sc.data.slice(this.startOffset, this.endOffset) : ""; } else { var textParts = [], iterator = new RangeIterator(this, true); iterateSubtree(iterator, function(node) { // Accept only text or CDATA nodes, not comments if (node.nodeType == 3 || node.nodeType == 4) { textParts.push(node.data); } }); iterator.detach(); return textParts.join(""); } }, // The methods below are all non-standard. The following batch were introduced by Mozilla but have since // been removed from Mozilla. compareNode: function(node) { assertRangeValid(this); var parent = node.parentNode; var nodeIndex = getNodeIndex(node); if (!parent) { throw new DOMException("NOT_FOUND_ERR"); } var startComparison = this.comparePoint(parent, nodeIndex), endComparison = this.comparePoint(parent, nodeIndex + 1); if (startComparison < 0) { // Node starts before return (endComparison > 0) ? n_b_a : n_b; } else { return (endComparison > 0) ? n_a : n_i; } }, comparePoint: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); if (comparePoints(node, offset, this.startContainer, this.startOffset) < 0) { return -1; } else if (comparePoints(node, offset, this.endContainer, this.endOffset) > 0) { return 1; } return 0; }, createContextualFragment: createContextualFragment, toHtml: function() { return rangeToHtml(this); }, // touchingIsIntersecting determines whether this method considers a node that borders a range intersects // with it (as in WebKit) or not (as in Gecko pre-1.9, and the default) intersectsNode: function(node, touchingIsIntersecting) { assertRangeValid(this); if (getRootContainer(node) != getRangeRoot(this)) { return false; } var parent = node.parentNode, offset = getNodeIndex(node); if (!parent) { return true; } var startComparison = comparePoints(parent, offset, this.endContainer, this.endOffset), endComparison = comparePoints(parent, offset + 1, this.startContainer, this.startOffset); return touchingIsIntersecting ? startComparison <= 0 && endComparison >= 0 : startComparison < 0 && endComparison > 0; }, isPointInRange: function(node, offset) { assertRangeValid(this); assertNode(node, "HIERARCHY_REQUEST_ERR"); assertSameDocumentOrFragment(node, this.startContainer); return (comparePoints(node, offset, this.startContainer, this.startOffset) >= 0) && (comparePoints(node, offset, this.endContainer, this.endOffset) <= 0); }, // The methods below are non-standard and invented by me. // Sharing a boundary start-to-end or end-to-start does not count as intersection. intersectsRange: function(range) { return rangesIntersect(this, range, false); }, // Sharing a boundary start-to-end or end-to-start does count as intersection. intersectsOrTouchesRange: function(range) { return rangesIntersect(this, range, true); }, intersection: function(range) { if (this.intersectsRange(range)) { var startComparison = comparePoints(this.startContainer, this.startOffset, range.startContainer, range.startOffset), endComparison = comparePoints(this.endContainer, this.endOffset, range.endContainer, range.endOffset); var intersectionRange = this.cloneRange(); if (startComparison == -1) { intersectionRange.setStart(range.startContainer, range.startOffset); } if (endComparison == 1) { intersectionRange.setEnd(range.endContainer, range.endOffset); } return intersectionRange; } return null; }, union: function(range) { if (this.intersectsOrTouchesRange(range)) { var unionRange = this.cloneRange(); if (comparePoints(range.startContainer, range.startOffset, this.startContainer, this.startOffset) == -1) { unionRange.setStart(range.startContainer, range.startOffset); } if (comparePoints(range.endContainer, range.endOffset, this.endContainer, this.endOffset) == 1) { unionRange.setEnd(range.endContainer, range.endOffset); } return unionRange; } else { throw new DOMException("Ranges do not intersect"); } }, containsNode: function(node, allowPartial) { if (allowPartial) { return this.intersectsNode(node, false); } else { return this.compareNode(node) == n_i; } }, containsNodeContents: function(node) { return this.comparePoint(node, 0) >= 0 && this.comparePoint(node, getNodeLength(node)) <= 0; }, containsRange: function(range) { var intersection = this.intersection(range); return intersection !== null && range.equals(intersection); }, containsNodeText: function(node) { var nodeRange = this.cloneRange(); nodeRange.selectNode(node); var textNodes = nodeRange.getNodes([3]); if (textNodes.length > 0) { nodeRange.setStart(textNodes[0], 0); var lastTextNode = textNodes.pop(); nodeRange.setEnd(lastTextNode, lastTextNode.length); return this.containsRange(nodeRange); } else { return this.containsNodeContents(node); } }, getNodes: function(nodeTypes, filter) { assertRangeValid(this); return getNodesInRange(this, nodeTypes, filter); }, getDocument: function() { return getRangeDocument(this); }, collapseBefore: function(node) { this.setEndBefore(node); this.collapse(false); }, collapseAfter: function(node) { this.setStartAfter(node); this.collapse(true); }, getBookmark: function(containerNode) { var doc = getRangeDocument(this); var preSelectionRange = api.createRange(doc); containerNode = containerNode || dom.getBody(doc); preSelectionRange.selectNodeContents(containerNode); var range = this.intersection(preSelectionRange); var start = 0, end = 0; if (range) { preSelectionRange.setEnd(range.startContainer, range.startOffset); start = preSelectionRange.toString().length; end = start + range.toString().length; } return { start: start, end: end, containerNode: containerNode }; }, moveToBookmark: function(bookmark) { var containerNode = bookmark.containerNode; var charIndex = 0; this.setStart(containerNode, 0); this.collapse(true); var nodeStack = [containerNode], node, foundStart = false, stop = false; var nextCharIndex, i, childNodes; while (!stop && (node = nodeStack.pop())) { if (node.nodeType == 3) { nextCharIndex = charIndex + node.length; if (!foundStart && bookmark.start >= charIndex && bookmark.start <= nextCharIndex) { this.setStart(node, bookmark.start - charIndex); foundStart = true; } if (foundStart && bookmark.end >= charIndex && bookmark.end <= nextCharIndex) { this.setEnd(node, bookmark.end - charIndex); stop = true; } charIndex = nextCharIndex; } else { childNodes = node.childNodes; i = childNodes.length; while (i--) { nodeStack.push(childNodes[i]); } } } }, getName: function() { return "DomRange"; }, equals: function(range) { return Range.rangesEqual(this, range); }, isValid: function() { return isRangeValid(this); }, inspect: function() { return inspect(this); }, detach: function() { // In DOM4, detach() is now a no-op. } }); function copyComparisonConstantsToObject(obj) { obj.START_TO_START = s2s; obj.START_TO_END = s2e; obj.END_TO_END = e2e; obj.END_TO_START = e2s; obj.NODE_BEFORE = n_b; obj.NODE_AFTER = n_a; obj.NODE_BEFORE_AND_AFTER = n_b_a; obj.NODE_INSIDE = n_i; } function copyComparisonConstants(constructor) { copyComparisonConstantsToObject(constructor); copyComparisonConstantsToObject(constructor.prototype); } function createRangeContentRemover(remover, boundaryUpdater) { return function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, root = this.commonAncestorContainer; var iterator = new RangeIterator(this, true); // Work out where to position the range after content removal var node, boundary; if (sc !== root) { node = getClosestAncestorIn(sc, root, true); boundary = getBoundaryAfterNode(node); sc = boundary.node; so = boundary.offset; } // Check none of the range is read-only iterateSubtree(iterator, assertNodeNotReadOnly); iterator.reset(); // Remove the content var returnValue = remover(iterator); iterator.detach(); // Move to the new position boundaryUpdater(this, sc, so, sc, so); return returnValue; }; } function createPrototypeRange(constructor, boundaryUpdater) { function createBeforeAfterNodeSetter(isBefore, isStart) { return function(node) { assertValidNodeType(node, beforeAfterNodeTypes); assertValidNodeType(getRootContainer(node), rootContainerNodeTypes); var boundary = (isBefore ? getBoundaryBeforeNode : getBoundaryAfterNode)(node); (isStart ? setRangeStart : setRangeEnd)(this, boundary.node, boundary.offset); }; } function setRangeStart(range, node, offset) { var ec = range.endContainer, eo = range.endOffset; if (node !== range.startContainer || offset !== range.startOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(ec) || comparePoints(node, offset, ec, eo) == 1) { ec = node; eo = offset; } boundaryUpdater(range, node, offset, ec, eo); } } function setRangeEnd(range, node, offset) { var sc = range.startContainer, so = range.startOffset; if (node !== range.endContainer || offset !== range.endOffset) { // Check the root containers of the range and the new boundary, and also check whether the new boundary // is after the current end. In either case, collapse the range to the new position if (getRootContainer(node) != getRootContainer(sc) || comparePoints(node, offset, sc, so) == -1) { sc = node; so = offset; } boundaryUpdater(range, sc, so, node, offset); } } // Set up inheritance var F = function() {}; F.prototype = api.rangePrototype; constructor.prototype = new F(); util.extend(constructor.prototype, { setStart: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeStart(this, node, offset); }, setEnd: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); setRangeEnd(this, node, offset); }, /** * Convenience method to set a range's start and end boundaries. Overloaded as follows: * - Two parameters (node, offset) creates a collapsed range at that position * - Three parameters (node, startOffset, endOffset) creates a range contained with node starting at * startOffset and ending at endOffset * - Four parameters (startNode, startOffset, endNode, endOffset) creates a range starting at startOffset in * startNode and ending at endOffset in endNode */ setStartAndEnd: function() { var args = arguments; var sc = args[0], so = args[1], ec = sc, eo = so; switch (args.length) { case 3: eo = args[2]; break; case 4: ec = args[2]; eo = args[3]; break; } boundaryUpdater(this, sc, so, ec, eo); }, setBoundary: function(node, offset, isStart) { this["set" + (isStart ? "Start" : "End")](node, offset); }, setStartBefore: createBeforeAfterNodeSetter(true, true), setStartAfter: createBeforeAfterNodeSetter(false, true), setEndBefore: createBeforeAfterNodeSetter(true, false), setEndAfter: createBeforeAfterNodeSetter(false, false), collapse: function(isStart) { assertRangeValid(this); if (isStart) { boundaryUpdater(this, this.startContainer, this.startOffset, this.startContainer, this.startOffset); } else { boundaryUpdater(this, this.endContainer, this.endOffset, this.endContainer, this.endOffset); } }, selectNodeContents: function(node) { assertNoDocTypeNotationEntityAncestor(node, true); boundaryUpdater(this, node, 0, node, getNodeLength(node)); }, selectNode: function(node) { assertNoDocTypeNotationEntityAncestor(node, false); assertValidNodeType(node, beforeAfterNodeTypes); var start = getBoundaryBeforeNode(node), end = getBoundaryAfterNode(node); boundaryUpdater(this, start.node, start.offset, end.node, end.offset); }, extractContents: createRangeContentRemover(extractSubtree, boundaryUpdater), deleteContents: createRangeContentRemover(deleteSubtree, boundaryUpdater), canSurroundContents: function() { assertRangeValid(this); assertNodeNotReadOnly(this.startContainer); assertNodeNotReadOnly(this.endContainer); // Check if the contents can be surrounded. Specifically, this means whether the range partially selects // no non-text nodes. var iterator = new RangeIterator(this, true); var boundariesInvalid = (iterator._first && isNonTextPartiallySelected(iterator._first, this) || (iterator._last && isNonTextPartiallySelected(iterator._last, this))); iterator.detach(); return !boundariesInvalid; }, splitBoundaries: function() { splitRangeBoundaries(this); }, splitBoundariesPreservingPositions: function(positionsToPreserve) { splitRangeBoundaries(this, positionsToPreserve); }, normalizeBoundaries: function() { assertRangeValid(this); var sc = this.startContainer, so = this.startOffset, ec = this.endContainer, eo = this.endOffset; var mergeForward = function(node) { var sibling = node.nextSibling; if (sibling && sibling.nodeType == node.nodeType) { ec = node; eo = node.length; node.appendData(sibling.data); removeNode(sibling); } }; var mergeBackward = function(node) { var sibling = node.previousSibling; if (sibling && sibling.nodeType == node.nodeType) { sc = node; var nodeLength = node.length; so = sibling.length; node.insertData(0, sibling.data); removeNode(sibling); if (sc == ec) { eo += so; ec = sc; } else if (ec == node.parentNode) { var nodeIndex = getNodeIndex(node); if (eo == nodeIndex) { ec = node; eo = nodeLength; } else if (eo > nodeIndex) { eo--; } } } }; var normalizeStart = true; var sibling; if (isCharacterDataNode(ec)) { if (eo == ec.length) { mergeForward(ec); } else if (eo == 0) { sibling = ec.previousSibling; if (sibling && sibling.nodeType == ec.nodeType) { eo = sibling.length; if (sc == ec) { normalizeStart = false; } sibling.appendData(ec.data); removeNode(ec); ec = sibling; } } } else { if (eo > 0) { var endNode = ec.childNodes[eo - 1]; if (endNode && isCharacterDataNode(endNode)) { mergeForward(endNode); } } normalizeStart = !this.collapsed; } if (normalizeStart) { if (isCharacterDataNode(sc)) { if (so == 0) { mergeBackward(sc); } else if (so == sc.length) { sibling = sc.nextSibling; if (sibling && sibling.nodeType == sc.nodeType) { if (ec == sibling) { ec = sc; eo += sc.length; } sc.appendData(sibling.data); removeNode(sibling); } } } else { if (so < sc.childNodes.length) { var startNode = sc.childNodes[so]; if (startNode && isCharacterDataNode(startNode)) { mergeBackward(startNode); } } } } else { sc = ec; so = eo; } boundaryUpdater(this, sc, so, ec, eo); }, collapseToPoint: function(node, offset) { assertNoDocTypeNotationEntityAncestor(node, true); assertValidOffset(node, offset); this.setStartAndEnd(node, offset); } }); copyComparisonConstants(constructor); } /*----------------------------------------------------------------------------------------------------------------*/ // Updates commonAncestorContainer and collapsed after boundary change function updateCollapsedAndCommonAncestor(range) { range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); range.commonAncestorContainer = range.collapsed ? range.startContainer : dom.getCommonAncestor(range.startContainer, range.endContainer); } function updateBoundaries(range, startContainer, startOffset, endContainer, endOffset) { range.startContainer = startContainer; range.startOffset = startOffset; range.endContainer = endContainer; range.endOffset = endOffset; range.document = dom.getDocument(startContainer); updateCollapsedAndCommonAncestor(range); } function Range(doc) { this.startContainer = doc; this.startOffset = 0; this.endContainer = doc; this.endOffset = 0; this.document = doc; updateCollapsedAndCommonAncestor(this); } createPrototypeRange(Range, updateBoundaries); util.extend(Range, { rangeProperties: rangeProperties, RangeIterator: RangeIterator, copyComparisonConstants: copyComparisonConstants, createPrototypeRange: createPrototypeRange, inspect: inspect, toHtml: rangeToHtml, getRangeDocument: getRangeDocument, rangesEqual: function(r1, r2) { return r1.startContainer === r2.startContainer && r1.startOffset === r2.startOffset && r1.endContainer === r2.endContainer && r1.endOffset === r2.endOffset; } }); api.DomRange = Range; }); /*----------------------------------------------------------------------------------------------------------------*/ // Wrappers for the browser's native DOM Range and/or TextRange implementation api.createCoreModule("WrappedRange", ["DomRange"], function(api, module) { var WrappedRange, WrappedTextRange; var dom = api.dom; var util = api.util; var DomPosition = dom.DomPosition; var DomRange = api.DomRange; var getBody = dom.getBody; var getContentDocument = dom.getContentDocument; var isCharacterDataNode = dom.isCharacterDataNode; /*----------------------------------------------------------------------------------------------------------------*/ if (api.features.implementsDomRange) { // This is a wrapper around the browser's native DOM Range. It has two aims: // - Provide workarounds for specific browser bugs // - provide convenient extensions, which are inherited from Rangy's DomRange (function() { var rangeProto; var rangeProperties = DomRange.rangeProperties; function updateRangeProperties(range) { var i = rangeProperties.length, prop; while (i--) { prop = rangeProperties[i]; range[prop] = range.nativeRange[prop]; } // Fix for broken collapsed property in IE 9. range.collapsed = (range.startContainer === range.endContainer && range.startOffset === range.endOffset); } function updateNativeRange(range, startContainer, startOffset, endContainer, endOffset) { var startMoved = (range.startContainer !== startContainer || range.startOffset != startOffset); var endMoved = (range.endContainer !== endContainer || range.endOffset != endOffset); var nativeRangeDifferent = !range.equals(range.nativeRange); // Always set both boundaries for the benefit of IE9 (see issue 35) if (startMoved || endMoved || nativeRangeDifferent) { range.setEnd(endContainer, endOffset); range.setStart(startContainer, startOffset); } } var createBeforeAfterNodeSetter; WrappedRange = function(range) { if (!range) { throw module.createError("WrappedRange: Range must be specified"); } this.nativeRange = range; updateRangeProperties(this); }; DomRange.createPrototypeRange(WrappedRange, updateNativeRange); rangeProto = WrappedRange.prototype; rangeProto.selectNode = function(node) { this.nativeRange.selectNode(node); updateRangeProperties(this); }; rangeProto.cloneContents = function() { return this.nativeRange.cloneContents(); }; // Due to a long-standing Firefox bug that I have not been able to find a reliable way to detect, // insertNode() is never delegated to the native range. rangeProto.surroundContents = function(node) { this.nativeRange.surroundContents(node); updateRangeProperties(this); }; rangeProto.collapse = function(isStart) { this.nativeRange.collapse(isStart); updateRangeProperties(this); }; rangeProto.cloneRange = function() { return new WrappedRange(this.nativeRange.cloneRange()); }; rangeProto.refresh = function() { updateRangeProperties(this); }; rangeProto.toString = function() { return this.nativeRange.toString(); }; // Create test range and node for feature detection var testTextNode = document.createTextNode("test"); getBody(document).appendChild(testTextNode); var range = document.createRange(); /*--------------------------------------------------------------------------------------------------------*/ // Test for Firefox 2 bug that prevents moving the start of a Range to a point after its current end and // correct for it range.setStart(testTextNode, 0); range.setEnd(testTextNode, 0); try { range.setStart(testTextNode, 1); rangeProto.setStart = function(node, offset) { this.nativeRange.setStart(node, offset); updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { this.nativeRange.setEnd(node, offset); updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name) { return function(node) { this.nativeRange[name](node); updateRangeProperties(this); }; }; } catch(ex) { rangeProto.setStart = function(node, offset) { try { this.nativeRange.setStart(node, offset); } catch (ex) { this.nativeRange.setEnd(node, offset); this.nativeRange.setStart(node, offset); } updateRangeProperties(this); }; rangeProto.setEnd = function(node, offset) { try { this.nativeRange.setEnd(node, offset); } catch (ex) { this.nativeRange.setStart(node, offset); this.nativeRange.setEnd(node, offset); } updateRangeProperties(this); }; createBeforeAfterNodeSetter = function(name, oppositeName) { return function(node) { try { this.nativeRange[name](node); } catch (ex) { this.nativeRange[oppositeName](node); this.nativeRange[name](node); } updateRangeProperties(this); }; }; } rangeProto.setStartBefore = createBeforeAfterNodeSetter("setStartBefore", "setEndBefore"); rangeProto.setStartAfter = createBeforeAfterNodeSetter("setStartAfter", "setEndAfter"); rangeProto.setEndBefore = createBeforeAfterNodeSetter("setEndBefore", "setStartBefore"); rangeProto.setEndAfter = createBeforeAfterNodeSetter("setEndAfter", "setStartAfter"); /*--------------------------------------------------------------------------------------------------------*/ // Always use DOM4-compliant selectNodeContents implementation: it's simpler and less code than testing // whether the native implementation can be trusted rangeProto.selectNodeContents = function(node) { this.setStartAndEnd(node, 0, dom.getNodeLength(node)); }; /*--------------------------------------------------------------------------------------------------------*/ // Test for and correct WebKit bug that has the behaviour of compareBoundaryPoints round the wrong way for // constants START_TO_END and END_TO_START: https://bugs.webkit.org/show_bug.cgi?id=20738 range.selectNodeContents(testTextNode); range.setEnd(testTextNode, 3); var range2 = document.createRange(); range2.selectNodeContents(testTextNode); range2.setEnd(testTextNode, 4); range2.setStart(testTextNode, 2); if (range.compareBoundaryPoints(range.START_TO_END, range2) == -1 && range.compareBoundaryPoints(range.END_TO_START, range2) == 1) { // This is the wrong way round, so correct for it rangeProto.compareBoundaryPoints = function(type, range) { range = range.nativeRange || range; if (type == range.START_TO_END) { type = range.END_TO_START; } else if (type == range.END_TO_START) { type = range.START_TO_END; } return this.nativeRange.compareBoundaryPoints(type, range); }; } else { rangeProto.compareBoundaryPoints = function(type, range) { return this.nativeRange.compareBoundaryPoints(type, range.nativeRange || range); }; } /*--------------------------------------------------------------------------------------------------------*/ // Test for IE deleteContents() and extractContents() bug and correct it. See issue 107. var el = document.createElement("div"); el.innerHTML = "123"; var textNode = el.firstChild; var body = getBody(document); body.appendChild(el); range.setStart(textNode, 1); range.setEnd(textNode, 2); range.deleteContents(); if (textNode.data == "13") { // Behaviour is correct per DOM4 Range so wrap the browser's implementation of deleteContents() and // extractContents() rangeProto.deleteContents = function() { this.nativeRange.deleteContents(); updateRangeProperties(this); }; rangeProto.extractContents = function() { var frag = this.nativeRange.extractContents(); updateRangeProperties(this); return frag; }; } else { } body.removeChild(el); body = null; /*--------------------------------------------------------------------------------------------------------*/ // Test for existence of createContextualFragment and delegate to it if it exists if (util.isHostMethod(range, "createContextualFragment")) { rangeProto.createContextualFragment = function(fragmentStr) { return this.nativeRange.createContextualFragment(fragmentStr); }; } /*--------------------------------------------------------------------------------------------------------*/ // Clean up getBody(document).removeChild(testTextNode); rangeProto.getName = function() { return "WrappedRange"; }; api.WrappedRange = WrappedRange; api.createNativeRange = function(doc) { doc = getContentDocument(doc, module, "createNativeRange"); return doc.createRange(); }; })(); } if (api.features.implementsTextRange) { /* This is a workaround for a bug where IE returns the wrong container element from the TextRange's parentElement() method. For example, in the following (where pipes denote the selection boundaries): <ul id="ul"><li id="a">| a </li><li id="b"> b |</li></ul> var range = document.selection.createRange(); alert(range.parentElement().id); // Should alert "ul" but alerts "b" This method returns the common ancestor node of the following: - the parentElement() of the textRange - the parentElement() of the textRange after calling collapse(true) - the parentElement() of the textRange after calling collapse(false) */ var getTextRangeContainerElement = function(textRange) { var parentEl = textRange.parentElement(); var range = textRange.duplicate(); range.collapse(true); var startEl = range.parentElement(); range = textRange.duplicate(); range.collapse(false); var endEl = range.parentElement(); var startEndContainer = (startEl == endEl) ? startEl : dom.getCommonAncestor(startEl, endEl); return startEndContainer == parentEl ? startEndContainer : dom.getCommonAncestor(parentEl, startEndContainer); }; var textRangeIsCollapsed = function(textRange) { return textRange.compareEndPoints("StartToEnd", textRange) == 0; }; // Gets the boundary of a TextRange expressed as a node and an offset within that node. This function started // out as an improved version of code found in Tim Cameron Ryan's IERange (http://code.google.com/p/ierange/) // but has grown, fixing problems with line breaks in preformatted text, adding workaround for IE TextRange // bugs, handling for inputs and images, plus optimizations. var getTextRangeBoundaryPosition = function(textRange, wholeRangeContainerElement, isStart, isCollapsed, startInfo) { var workingRange = textRange.duplicate(); workingRange.collapse(isStart); var containerElement = workingRange.parentElement(); // Sometimes collapsing a TextRange that's at the start of a text node can move it into the previous node, so // check for that if (!dom.isOrIsAncestorOf(wholeRangeContainerElement, containerElement)) { containerElement = wholeRangeContainerElement; } // Deal with nodes that cannot "contain rich HTML markup". In practice, this means form inputs, images and // similar. See http://msdn.microsoft.com/en-us/library/aa703950%28VS.85%29.aspx if (!containerElement.canHaveHTML) { var pos = new DomPosition(containerElement.parentNode, dom.getNodeIndex(containerElement)); return { boundaryPosition: pos, nodeInfo: { nodeIndex: pos.offset, containerElement: pos.node } }; } var workingNode = dom.getDocument(containerElement).createElement("span"); // Workaround for HTML5 Shiv's insane violation of document.createElement(). See Rangy issue 104 and HTML5 // Shiv issue 64: https://github.com/aFarkas/html5shiv/issues/64 if (workingNode.parentNode) { dom.removeNode(workingNode); } var comparison, workingComparisonType = isStart ? "StartToStart" : "StartToEnd"; var previousNode, nextNode, boundaryPosition, boundaryNode; var start = (startInfo && startInfo.containerElement == containerElement) ? startInfo.nodeIndex : 0; var childNodeCount = containerElement.childNodes.length; var end = childNodeCount; // Check end first. Code within the loop assumes that the endth child node of the container is definitely // after the range boundary. var nodeIndex = end; while (true) { if (nodeIndex == childNodeCount) { containerElement.appendChild(workingNode); } else { containerElement.insertBefore(workingNode, containerElement.childNodes[nodeIndex]); } workingRange.moveToElementText(workingNode); comparison = workingRange.compareEndPoints(workingComparisonType, textRange); if (comparison == 0 || start == end) { break; } else if (comparison == -1) { if (end == start + 1) { // We know the endth child node is after the range boundary, so we must be done. break; } else { start = nodeIndex; } } else { end = (end == start + 1) ? start : nodeIndex; } nodeIndex = Math.floor((start + end) / 2); containerElement.removeChild(workingNode); } // We've now reached or gone past the boundary of the text range we're interested in // so have identified the node we want boundaryNode = workingNode.nextSibling; if (comparison == -1 && boundaryNode && isCharacterDataNode(boundaryNode)) { // This is a character data node (text, comment, cdata). The working range is collapsed at the start of // the node containing the text range's boundary, so we move the end of the working range to the // boundary point and measure the length of its text to get the boundary's offset within the node. workingRange.setEndPoint(isStart ? "EndToStart" : "EndToEnd", textRange); var offset; if (/[\r\n]/.test(boundaryNode.data)) { /* For the particular case of a boundary within a text node containing rendered line breaks (within a <pre> element, for example), we need a slightly complicated approach to get the boundary's offset in IE. The facts: - Each line break is represented as \r in the text node's data/nodeValue properties - Each line break is represented as \r\n in the TextRange's 'text' property - The 'text' property of the TextRange does not contain trailing line breaks To get round the problem presented by the final fact above, we can use the fact that TextRange's moveStart() and moveEnd() methods return the actual number of characters moved, which is not necessarily the same as the number of characters it was instructed to move. The simplest approach is to use this to store the characters moved when moving both the start and end of the range to the start of the document body and subtracting the start offset from the end offset (the "move-negative-gazillion" method). However, this is extremely slow when the document is large and the range is near the end of it. Clearly doing the mirror image (i.e. moving the range boundaries to the end of the document) has the same problem. Another approach that works is to use moveStart() to move the start boundary of the range up to the end boundary one character at a time and incrementing a counter with the value returned by the moveStart() call. However, the check for whether the start boundary has reached the end boundary is expensive, so this method is slow (although unlike "move-negative-gazillion" is largely unaffected by the location of the range within the document). The approach used below is a hybrid of the two methods above. It uses the fact that a string containing the TextRange's 'text' property with each \r\n converted to a single \r character cannot be longer than the text of the TextRange, so the start of the range is moved that length initially and then a character at a time to make up for any trailing line breaks not contained in the 'text' property. This has good performance in most situations compared to the previous two methods. */ var tempRange = workingRange.duplicate(); var rangeLength = tempRange.text.replace(/\r\n/g, "\r").length; offset = tempRange.moveStart("character", rangeLength); while ( (comparison = tempRange.compareEndPoints("StartToEnd", tempRange)) == -1) { offset++; tempRange.moveStart("character", 1); } } else { offset = workingRange.text.length; } boundaryPosition = new DomPosition(boundaryNode, offset); } else { // If the boundary immediately follows a character data node and this is the end boundary, we should favour // a position within that, and likewise for a start boundary preceding a character data node previousNode = (isCollapsed || !isStart) && workingNode.previousSibling; nextNode = (isCollapsed || isStart) && workingNode.nextSibling; if (nextNode && isCharacterDataNode(nextNode)) { boundaryPosition = new DomPosition(nextNode, 0); } else if (previousNode && isCharacterDataNode(previousNode)) { boundaryPosition = new DomPosition(previousNode, previousNode.data.length); } else { boundaryPosition = new DomPosition(containerElement, dom.getNodeIndex(workingNode)); } } // Clean up dom.removeNode(workingNode); return { boundaryPosition: boundaryPosition, nodeInfo: { nodeIndex: nodeIndex, containerElement: containerElement } }; }; // Returns a TextRange representing the boundary of a TextRange expressed as a node and an offset within that // node. This function started out as an optimized version of code found in Tim Cameron Ryan's IERange // (http://code.google.com/p/ierange/) var createBoundaryTextRange = function(boundaryPosition, isStart) { var boundaryNode, boundaryParent, boundaryOffset = boundaryPosition.offset; var doc = dom.getDocument(boundaryPosition.node); var workingNode, childNodes, workingRange = getBody(doc).createTextRange(); var nodeIsDataNode = isCharacterDataNode(boundaryPosition.node); if (nodeIsDataNode) { boundaryNode = boundaryPosition.node; boundaryParent = boundaryNode.parentNode; } else { childNodes = boundaryPosition.node.childNodes; boundaryNode = (boundaryOffset < childNodes.length) ? childNodes[boundaryOffset] : null; boundaryParent = boundaryPosition.node; } // Position the range immediately before the node containing the boundary workingNode = doc.createElement("span"); // Making the working element non-empty element persuades IE to consider the TextRange boundary to be within // the element rather than immediately before or after it workingNode.innerHTML = "&#feff;"; // insertBefore is supposed to work like appendChild if the second parameter is null. However, a bug report // for IERange suggests that it can crash the browser: http://code.google.com/p/ierange/issues/detail?id=12 if (boundaryNode) { boundaryParent.insertBefore(workingNode, boundaryNode); } else { boundaryParent.appendChild(workingNode); } workingRange.moveToElementText(workingNode); workingRange.collapse(!isStart); // Clean up boundaryParent.removeChild(workingNode); // Move the working range to the text offset, if required if (nodeIsDataNode) { workingRange[isStart ? "moveStart" : "moveEnd"]("character", boundaryOffset); } return workingRange; }; /*------------------------------------------------------------------------------------------------------------*/ // This is a wrapper around a TextRange, providing full DOM Range functionality using rangy's DomRange as a // prototype WrappedTextRange = function(textRange) { this.textRange = textRange; this.refresh(); }; WrappedTextRange.prototype = new DomRange(document); WrappedTextRange.prototype.refresh = function() { var start, end, startBoundary; // TextRange's parentElement() method cannot be trusted. getTextRangeContainerElement() works around that. var rangeContainerElement = getTextRangeContainerElement(this.textRange); if (textRangeIsCollapsed(this.textRange)) { end = start = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, true).boundaryPosition; } else { startBoundary = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, true, false); start = startBoundary.boundaryPosition; // An optimization used here is that if the start and end boundaries have the same parent element, the // search scope for the end boundary can be limited to exclude the portion of the element that precedes // the start boundary end = getTextRangeBoundaryPosition(this.textRange, rangeContainerElement, false, false, startBoundary.nodeInfo).boundaryPosition; } this.setStart(start.node, start.offset); this.setEnd(end.node, end.offset); }; WrappedTextRange.prototype.getName = function() { return "WrappedTextRange"; }; DomRange.copyComparisonConstants(WrappedTextRange); var rangeToTextRange = function(range) { if (range.collapsed) { return createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); } else { var startRange = createBoundaryTextRange(new DomPosition(range.startContainer, range.startOffset), true); var endRange = createBoundaryTextRange(new DomPosition(range.endContainer, range.endOffset), false); var textRange = getBody( DomRange.getRangeDocument(range) ).createTextRange(); textRange.setEndPoint("StartToStart", startRange); textRange.setEndPoint("EndToEnd", endRange); return textRange; } }; WrappedTextRange.rangeToTextRange = rangeToTextRange; WrappedTextRange.prototype.toTextRange = function() { return rangeToTextRange(this); }; api.WrappedTextRange = WrappedTextRange; // IE 9 and above have both implementations and Rangy makes both available. The next few lines sets which // implementation to use by default. if (!api.features.implementsDomRange || api.config.preferTextRange) { // Add WrappedTextRange as the Range property of the global object to allow expression like Range.END_TO_END to work var globalObj = (function(f) { return f("return this;")(); })(Function); if (typeof globalObj.Range == "undefined") { globalObj.Range = WrappedTextRange; } api.createNativeRange = function(doc) { doc = getContentDocument(doc, module, "createNativeRange"); return getBody(doc).createTextRange(); }; api.WrappedRange = WrappedTextRange; } } api.createRange = function(doc) { doc = getContentDocument(doc, module, "createRange"); return new api.WrappedRange(api.createNativeRange(doc)); }; api.createRangyRange = function(doc) { doc = getContentDocument(doc, module, "createRangyRange"); return new DomRange(doc); }; util.createAliasForDeprecatedMethod(api, "createIframeRange", "createRange"); util.createAliasForDeprecatedMethod(api, "createIframeRangyRange", "createRangyRange"); api.addShimListener(function(win) { var doc = win.document; if (typeof doc.createRange == "undefined") { doc.createRange = function() { return api.createRange(doc); }; } doc = win = null; }); }); /*----------------------------------------------------------------------------------------------------------------*/ // This module creates a selection object wrapper that conforms as closely as possible to the Selection specification // in the HTML Editing spec (http://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#selections) api.createCoreModule("WrappedSelection", ["DomRange", "WrappedRange"], function(api, module) { api.config.checkSelectionRanges = true; var BOOLEAN = "boolean"; var NUMBER = "number"; var dom = api.dom; var util = api.util; var isHostMethod = util.isHostMethod; var DomRange = api.DomRange; var WrappedRange = api.WrappedRange; var DOMException = api.DOMException; var DomPosition = dom.DomPosition; var getNativeSelection; var selectionIsCollapsed; var features = api.features; var CONTROL = "Control"; var getDocument = dom.getDocument; var getBody = dom.getBody; var rangesEqual = DomRange.rangesEqual; // Utility function to support direction parameters in the API that may be a string ("backward", "backwards", // "forward" or "forwards") or a Boolean (true for backwards). function isDirectionBackward(dir) { return (typeof dir == "string") ? /^backward(s)?$/i.test(dir) : !!dir; } function getWindow(win, methodName) { if (!win) { return window; } else if (dom.isWindow(win)) { return win; } else if (win instanceof WrappedSelection) { return win.win; } else { var doc = dom.getContentDocument(win, module, methodName); return dom.getWindow(doc); } } function getWinSelection(winParam) { return getWindow(winParam, "getWinSelection").getSelection(); } function getDocSelection(winParam) { return getWindow(winParam, "getDocSelection").document.selection; } function winSelectionIsBackward(sel) { var backward = false; if (sel.anchorNode) { backward = (dom.comparePoints(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset) == 1); } return backward; } // Test for the Range/TextRange and Selection features required // Test for ability to retrieve selection var implementsWinGetSelection = isHostMethod(window, "getSelection"), implementsDocSelection = util.isHostObject(document, "selection"); features.implementsWinGetSelection = implementsWinGetSelection; features.implementsDocSelection = implementsDocSelection; var useDocumentSelection = implementsDocSelection && (!implementsWinGetSelection || api.config.preferTextRange); if (useDocumentSelection) { getNativeSelection = getDocSelection; api.isSelectionValid = function(winParam) { var doc = getWindow(winParam, "isSelectionValid").document, nativeSel = doc.selection; // Check whether the selection TextRange is actually contained within the correct document return (nativeSel.type != "None" || getDocument(nativeSel.createRange().parentElement()) == doc); }; } else if (implementsWinGetSelection) { getNativeSelection = getWinSelection; api.isSelectionValid = function() { return true; }; } else { module.fail("Neither document.selection or window.getSelection() detected."); return false; } api.getNativeSelection = getNativeSelection; var testSelection = getNativeSelection(); // In Firefox, the selection is null in an iframe with display: none. See issue #138. if (!testSelection) { module.fail("Native selection was null (possibly issue 138?)"); return false; } var testRange = api.createNativeRange(document); var body = getBody(document); // Obtaining a range from a selection var selectionHasAnchorAndFocus = util.areHostProperties(testSelection, ["anchorNode", "focusNode", "anchorOffset", "focusOffset"]); features.selectionHasAnchorAndFocus = selectionHasAnchorAndFocus; // Test for existence of native selection extend() method var selectionHasExtend = isHostMethod(testSelection, "extend"); features.selectionHasExtend = selectionHasExtend; // Test if rangeCount exists var selectionHasRangeCount = (typeof testSelection.rangeCount == NUMBER); features.selectionHasRangeCount = selectionHasRangeCount; var selectionSupportsMultipleRanges = false; var collapsedNonEditableSelectionsSupported = true; var addRangeBackwardToNative = selectionHasExtend ? function(nativeSelection, range) { var doc = DomRange.getRangeDocument(range); var endRange = api.createRange(doc); endRange.collapseToPoint(range.endContainer, range.endOffset); nativeSelection.addRange(getNativeRange(endRange)); nativeSelection.extend(range.startContainer, range.startOffset); } : null; if (util.areHostMethods(testSelection, ["addRange", "getRangeAt", "removeAllRanges"]) && typeof testSelection.rangeCount == NUMBER && features.implementsDomRange) { (function() { // Previously an iframe was used but this caused problems in some circumstances in IE, so tests are // performed on the current document's selection. See issue 109. // Note also that if a selection previously existed, it is wiped and later restored by these tests. This // will result in the selection direction begin reversed if the original selection was backwards and the // browser does not support setting backwards selections (Internet Explorer, I'm looking at you). var sel = window.getSelection(); if (sel) { // Store the current selection var originalSelectionRangeCount = sel.rangeCount; var selectionHasMultipleRanges = (originalSelectionRangeCount > 1); var originalSelectionRanges = []; var originalSelectionBackward = winSelectionIsBackward(sel); for (var i = 0; i < originalSelectionRangeCount; ++i) { originalSelectionRanges[i] = sel.getRangeAt(i); } // Create some test elements var testEl = dom.createTestElement(document, "", false); var textNode = testEl.appendChild( document.createTextNode("\u00a0\u00a0\u00a0") ); // Test whether the native selection will allow a collapsed selection within a non-editable element var r1 = document.createRange(); r1.setStart(textNode, 1); r1.collapse(true); sel.removeAllRanges(); sel.addRange(r1); collapsedNonEditableSelectionsSupported = (sel.rangeCount == 1); sel.removeAllRanges(); // Test whether the native selection is capable of supporting multiple ranges. if (!selectionHasMultipleRanges) { // Doing the original feature test here in Chrome 36 (and presumably later versions) prints a // console error of "Discontiguous selection is not supported." that cannot be suppressed. There's // nothing we can do about this while retaining the feature test so we have to resort to a browser // sniff. I'm not happy about it. See // https://code.google.com/p/chromium/issues/detail?id=399791 var chromeMatch = window.navigator.appVersion.match(/Chrome\/(.*?) /); if (chromeMatch && parseInt(chromeMatch[1]) >= 36) { selectionSupportsMultipleRanges = false; } else { var r2 = r1.cloneRange(); r1.setStart(textNode, 0); r2.setEnd(textNode, 3); r2.setStart(textNode, 2); sel.addRange(r1); sel.addRange(r2); selectionSupportsMultipleRanges = (sel.rangeCount == 2); } } // Clean up dom.removeNode(testEl); sel.removeAllRanges(); for (i = 0; i < originalSelectionRangeCount; ++i) { if (i == 0 && originalSelectionBackward) { if (addRangeBackwardToNative) { addRangeBackwardToNative(sel, originalSelectionRanges[i]); } else { api.warn("Rangy initialization: original selection was backwards but selection has been restored forwards because the browser does not support Selection.extend"); sel.addRange(originalSelectionRanges[i]); } } else { sel.addRange(originalSelectionRanges[i]); } } } })(); } features.selectionSupportsMultipleRanges = selectionSupportsMultipleRanges; features.collapsedNonEditableSelectionsSupported = collapsedNonEditableSelectionsSupported; // ControlRanges var implementsControlRange = false, testControlRange; if (body && isHostMethod(body, "createControlRange")) { testControlRange = body.createControlRange(); if (util.areHostProperties(testControlRange, ["item", "add"])) { implementsControlRange = true; } } features.implementsControlRange = implementsControlRange; // Selection collapsedness if (selectionHasAnchorAndFocus) { selectionIsCollapsed = function(sel) { return sel.anchorNode === sel.focusNode && sel.anchorOffset === sel.focusOffset; }; } else { selectionIsCollapsed = function(sel) { return sel.rangeCount ? sel.getRangeAt(sel.rangeCount - 1).collapsed : false; }; } function updateAnchorAndFocusFromRange(sel, range, backward) { var anchorPrefix = backward ? "end" : "start", focusPrefix = backward ? "start" : "end"; sel.anchorNode = range[anchorPrefix + "Container"]; sel.anchorOffset = range[anchorPrefix + "Offset"]; sel.focusNode = range[focusPrefix + "Container"]; sel.focusOffset = range[focusPrefix + "Offset"]; } function updateAnchorAndFocusFromNativeSelection(sel) { var nativeSel = sel.nativeSelection; sel.anchorNode = nativeSel.anchorNode; sel.anchorOffset = nativeSel.anchorOffset; sel.focusNode = nativeSel.focusNode; sel.focusOffset = nativeSel.focusOffset; } function updateEmptySelection(sel) { sel.anchorNode = sel.focusNode = null; sel.anchorOffset = sel.focusOffset = 0; sel.rangeCount = 0; sel.isCollapsed = true; sel._ranges.length = 0; } function getNativeRange(range) { var nativeRange; if (range instanceof DomRange) { nativeRange = api.createNativeRange(range.getDocument()); nativeRange.setEnd(range.endContainer, range.endOffset); nativeRange.setStart(range.startContainer, range.startOffset); } else if (range instanceof WrappedRange) { nativeRange = range.nativeRange; } else if (features.implementsDomRange && (range instanceof dom.getWindow(range.startContainer).Range)) { nativeRange = range; } return nativeRange; } function rangeContainsSingleElement(rangeNodes) { if (!rangeNodes.length || rangeNodes[0].nodeType != 1) { return false; } for (var i = 1, len = rangeNodes.length; i < len; ++i) { if (!dom.isAncestorOf(rangeNodes[0], rangeNodes[i])) { return false; } } return true; } function getSingleElementFromRange(range) { var nodes = range.getNodes(); if (!rangeContainsSingleElement(nodes)) { throw module.createError("getSingleElementFromRange: range " + range.inspect() + " did not consist of a single element"); } return nodes[0]; } // Simple, quick test which only needs to distinguish between a TextRange and a ControlRange function isTextRange(range) { return !!range && typeof range.text != "undefined"; } function updateFromTextRange(sel, range) { // Create a Range from the selected TextRange var wrappedRange = new WrappedRange(range); sel._ranges = [wrappedRange]; updateAnchorAndFocusFromRange(sel, wrappedRange, false); sel.rangeCount = 1; sel.isCollapsed = wrappedRange.collapsed; } function updateControlSelection(sel) { // Update the wrapped selection based on what's now in the native selection sel._ranges.length = 0; if (sel.docSelection.type == "None") { updateEmptySelection(sel); } else { var controlRange = sel.docSelection.createRange(); if (isTextRange(controlRange)) { // This case (where the selection type is "Control" and calling createRange() on the selection returns // a TextRange) can happen in IE 9. It happens, for example, when all elements in the selected // ControlRange have been removed from the ControlRange and removed from the document. updateFromTextRange(sel, controlRange); } else { sel.rangeCount = controlRange.length; var range, doc = getDocument(controlRange.item(0)); for (var i = 0; i < sel.rangeCount; ++i) { range = api.createRange(doc); range.selectNode(controlRange.item(i)); sel._ranges.push(range); } sel.isCollapsed = sel.rangeCount == 1 && sel._ranges[0].collapsed; updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], false); } } } function addRangeToControlSelection(sel, range) { var controlRange = sel.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange plus the element // contained by the supplied range var doc = getDocument(controlRange.item(0)); var newControlRange = getBody(doc).createControlRange(); for (var i = 0, len = controlRange.length; i < len; ++i) { newControlRange.add(controlRange.item(i)); } try { newControlRange.add(rangeElement); } catch (ex) { throw module.createError("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)"); } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } var getSelectionRangeAt; if (isHostMethod(testSelection, "getRangeAt")) { // try/catch is present because getRangeAt() must have thrown an error in some browser and some situation. // Unfortunately, I didn't write a comment about the specifics and am now scared to take it out. Let that be a // lesson to us all, especially me. getSelectionRangeAt = function(sel, index) { try { return sel.getRangeAt(index); } catch (ex) { return null; } }; } else if (selectionHasAnchorAndFocus) { getSelectionRangeAt = function(sel) { var doc = getDocument(sel.anchorNode); var range = api.createRange(doc); range.setStartAndEnd(sel.anchorNode, sel.anchorOffset, sel.focusNode, sel.focusOffset); // Handle the case when the selection was selected backwards (from the end to the start in the // document) if (range.collapsed !== this.isCollapsed) { range.setStartAndEnd(sel.focusNode, sel.focusOffset, sel.anchorNode, sel.anchorOffset); } return range; }; } function WrappedSelection(selection, docSelection, win) { this.nativeSelection = selection; this.docSelection = docSelection; this._ranges = []; this.win = win; this.refresh(); } WrappedSelection.prototype = api.selectionPrototype; function deleteProperties(sel) { sel.win = sel.anchorNode = sel.focusNode = sel._ranges = null; sel.rangeCount = sel.anchorOffset = sel.focusOffset = 0; sel.detached = true; } var cachedRangySelections = []; function actOnCachedSelection(win, action) { var i = cachedRangySelections.length, cached, sel; while (i--) { cached = cachedRangySelections[i]; sel = cached.selection; if (action == "deleteAll") { deleteProperties(sel); } else if (cached.win == win) { if (action == "delete") { cachedRangySelections.splice(i, 1); return true; } else { return sel; } } } if (action == "deleteAll") { cachedRangySelections.length = 0; } return null; } var getSelection = function(win) { // Check if the parameter is a Rangy Selection object if (win && win instanceof WrappedSelection) { win.refresh(); return win; } win = getWindow(win, "getNativeSelection"); var sel = actOnCachedSelection(win); var nativeSel = getNativeSelection(win), docSel = implementsDocSelection ? getDocSelection(win) : null; if (sel) { sel.nativeSelection = nativeSel; sel.docSelection = docSel; sel.refresh(); } else { sel = new WrappedSelection(nativeSel, docSel, win); cachedRangySelections.push( { win: win, selection: sel } ); } return sel; }; api.getSelection = getSelection; util.createAliasForDeprecatedMethod(api, "getIframeSelection", "getSelection"); var selProto = WrappedSelection.prototype; function createControlSelection(sel, ranges) { // Ensure that the selection becomes of type "Control" var doc = getDocument(ranges[0].startContainer); var controlRange = getBody(doc).createControlRange(); for (var i = 0, el, len = ranges.length; i < len; ++i) { el = getSingleElementFromRange(ranges[i]); try { controlRange.add(el); } catch (ex) { throw module.createError("setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)"); } } controlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(sel); } // Selecting a range if (!useDocumentSelection && selectionHasAnchorAndFocus && util.areHostMethods(testSelection, ["removeAllRanges", "addRange"])) { selProto.removeAllRanges = function() { this.nativeSelection.removeAllRanges(); updateEmptySelection(this); }; var addRangeBackward = function(sel, range) { addRangeBackwardToNative(sel.nativeSelection, range); sel.refresh(); }; if (selectionHasRangeCount) { selProto.addRange = function(range, direction) { if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { if (isDirectionBackward(direction) && selectionHasExtend) { addRangeBackward(this, range); } else { var previousRangeCount; if (selectionSupportsMultipleRanges) { previousRangeCount = this.rangeCount; } else { this.removeAllRanges(); previousRangeCount = 0; } // Clone the native range so that changing the selected range does not affect the selection. // This is contrary to the spec but is the only way to achieve consistency between browsers. See // issue 80. var clonedNativeRange = getNativeRange(range).cloneRange(); try { this.nativeSelection.addRange(clonedNativeRange); } catch (ex) { } // Check whether adding the range was successful this.rangeCount = this.nativeSelection.rangeCount; if (this.rangeCount == previousRangeCount + 1) { // The range was added successfully // Check whether the range that we added to the selection is reflected in the last range extracted from // the selection if (api.config.checkSelectionRanges) { var nativeRange = getSelectionRangeAt(this.nativeSelection, this.rangeCount - 1); if (nativeRange && !rangesEqual(nativeRange, range)) { // Happens in WebKit with, for example, a selection placed at the start of a text node range = new WrappedRange(nativeRange); } } this._ranges[this.rangeCount - 1] = range; updateAnchorAndFocusFromRange(this, range, selectionIsBackward(this.nativeSelection)); this.isCollapsed = selectionIsCollapsed(this); } else { // The range was not added successfully. The simplest thing is to refresh this.refresh(); } } } }; } else { selProto.addRange = function(range, direction) { if (isDirectionBackward(direction) && selectionHasExtend) { addRangeBackward(this, range); } else { this.nativeSelection.addRange(getNativeRange(range)); this.refresh(); } }; } selProto.setRanges = function(ranges) { if (implementsControlRange && implementsDocSelection && ranges.length > 1) { createControlSelection(this, ranges); } else { this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { this.addRange(ranges[i]); } } }; } else if (isHostMethod(testSelection, "empty") && isHostMethod(testRange, "select") && implementsControlRange && useDocumentSelection) { selProto.removeAllRanges = function() { // Added try/catch as fix for issue #21 try { this.docSelection.empty(); // Check for empty() not working (issue #24) if (this.docSelection.type != "None") { // Work around failure to empty a control selection by instead selecting a TextRange and then // calling empty() var doc; if (this.anchorNode) { doc = getDocument(this.anchorNode); } else if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); if (controlRange.length) { doc = getDocument( controlRange.item(0) ); } } if (doc) { var textRange = getBody(doc).createTextRange(); textRange.select(); this.docSelection.empty(); } } } catch(ex) {} updateEmptySelection(this); }; selProto.addRange = function(range) { if (this.docSelection.type == CONTROL) { addRangeToControlSelection(this, range); } else { api.WrappedTextRange.rangeToTextRange(range).select(); this._ranges[0] = range; this.rangeCount = 1; this.isCollapsed = this._ranges[0].collapsed; updateAnchorAndFocusFromRange(this, range, false); } }; selProto.setRanges = function(ranges) { this.removeAllRanges(); var rangeCount = ranges.length; if (rangeCount > 1) { createControlSelection(this, ranges); } else if (rangeCount) { this.addRange(ranges[0]); } }; } else { module.fail("No means of selecting a Range or TextRange was found"); return false; } selProto.getRangeAt = function(index) { if (index < 0 || index >= this.rangeCount) { throw new DOMException("INDEX_SIZE_ERR"); } else { // Clone the range to preserve selection-range independence. See issue 80. return this._ranges[index].cloneRange(); } }; var refreshSelection; if (useDocumentSelection) { refreshSelection = function(sel) { var range; if (api.isSelectionValid(sel.win)) { range = sel.docSelection.createRange(); } else { range = getBody(sel.win.document).createTextRange(); range.collapse(true); } if (sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else if (isTextRange(range)) { updateFromTextRange(sel, range); } else { updateEmptySelection(sel); } }; } else if (isHostMethod(testSelection, "getRangeAt") && typeof testSelection.rangeCount == NUMBER) { refreshSelection = function(sel) { if (implementsControlRange && implementsDocSelection && sel.docSelection.type == CONTROL) { updateControlSelection(sel); } else { sel._ranges.length = sel.rangeCount = sel.nativeSelection.rangeCount; if (sel.rangeCount) { for (var i = 0, len = sel.rangeCount; i < len; ++i) { sel._ranges[i] = new api.WrappedRange(sel.nativeSelection.getRangeAt(i)); } updateAnchorAndFocusFromRange(sel, sel._ranges[sel.rangeCount - 1], selectionIsBackward(sel.nativeSelection)); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } } }; } else if (selectionHasAnchorAndFocus && typeof testSelection.isCollapsed == BOOLEAN && typeof testRange.collapsed == BOOLEAN && features.implementsDomRange) { refreshSelection = function(sel) { var range, nativeSel = sel.nativeSelection; if (nativeSel.anchorNode) { range = getSelectionRangeAt(nativeSel, 0); sel._ranges = [range]; sel.rangeCount = 1; updateAnchorAndFocusFromNativeSelection(sel); sel.isCollapsed = selectionIsCollapsed(sel); } else { updateEmptySelection(sel); } }; } else { module.fail("No means of obtaining a Range or TextRange from the user's selection was found"); return false; } selProto.refresh = function(checkForChanges) { var oldRanges = checkForChanges ? this._ranges.slice(0) : null; var oldAnchorNode = this.anchorNode, oldAnchorOffset = this.anchorOffset; refreshSelection(this); if (checkForChanges) { // Check the range count first var i = oldRanges.length; if (i != this._ranges.length) { return true; } // Now check the direction. Checking the anchor position is the same is enough since we're checking all the // ranges after this if (this.anchorNode != oldAnchorNode || this.anchorOffset != oldAnchorOffset) { return true; } // Finally, compare each range in turn while (i--) { if (!rangesEqual(oldRanges[i], this._ranges[i])) { return true; } } return false; } }; // Removal of a single range var removeRangeManually = function(sel, range) { var ranges = sel.getAllRanges(); sel.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { if (!rangesEqual(range, ranges[i])) { sel.addRange(ranges[i]); } } if (!sel.rangeCount) { updateEmptySelection(sel); } }; if (implementsControlRange && implementsDocSelection) { selProto.removeRange = function(range) { if (this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var rangeElement = getSingleElementFromRange(range); // Create a new ControlRange containing all the elements in the selected ControlRange minus the // element contained by the supplied range var doc = getDocument(controlRange.item(0)); var newControlRange = getBody(doc).createControlRange(); var el, removed = false; for (var i = 0, len = controlRange.length; i < len; ++i) { el = controlRange.item(i); if (el !== rangeElement || removed) { newControlRange.add(controlRange.item(i)); } else { removed = true; } } newControlRange.select(); // Update the wrapped selection based on what's now in the native selection updateControlSelection(this); } else { removeRangeManually(this, range); } }; } else { selProto.removeRange = function(range) { removeRangeManually(this, range); }; } // Detecting if a selection is backward var selectionIsBackward; if (!useDocumentSelection && selectionHasAnchorAndFocus && features.implementsDomRange) { selectionIsBackward = winSelectionIsBackward; selProto.isBackward = function() { return selectionIsBackward(this); }; } else { selectionIsBackward = selProto.isBackward = function() { return false; }; } // Create an alias for backwards compatibility. From 1.3, everything is "backward" rather than "backwards" selProto.isBackwards = selProto.isBackward; // Selection stringifier // This is conformant to the old HTML5 selections draft spec but differs from WebKit and Mozilla's implementation. // The current spec does not yet define this method. selProto.toString = function() { var rangeTexts = []; for (var i = 0, len = this.rangeCount; i < len; ++i) { rangeTexts[i] = "" + this._ranges[i]; } return rangeTexts.join(""); }; function assertNodeInSameDocument(sel, node) { if (sel.win.document != getDocument(node)) { throw new DOMException("WRONG_DOCUMENT_ERR"); } } // No current browser conforms fully to the spec for this method, so Rangy's own method is always used selProto.collapse = function(node, offset) { assertNodeInSameDocument(this, node); var range = api.createRange(node); range.collapseToPoint(node, offset); this.setSingleRange(range); this.isCollapsed = true; }; selProto.collapseToStart = function() { if (this.rangeCount) { var range = this._ranges[0]; this.collapse(range.startContainer, range.startOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; selProto.collapseToEnd = function() { if (this.rangeCount) { var range = this._ranges[this.rangeCount - 1]; this.collapse(range.endContainer, range.endOffset); } else { throw new DOMException("INVALID_STATE_ERR"); } }; // The spec is very specific on how selectAllChildren should be implemented and not all browsers implement it as // specified so the native implementation is never used by Rangy. selProto.selectAllChildren = function(node) { assertNodeInSameDocument(this, node); var range = api.createRange(node); range.selectNodeContents(node); this.setSingleRange(range); }; selProto.deleteFromDocument = function() { // Sepcial behaviour required for IE's control selections if (implementsControlRange && implementsDocSelection && this.docSelection.type == CONTROL) { var controlRange = this.docSelection.createRange(); var element; while (controlRange.length) { element = controlRange.item(0); controlRange.remove(element); dom.removeNode(element); } this.refresh(); } else if (this.rangeCount) { var ranges = this.getAllRanges(); if (ranges.length) { this.removeAllRanges(); for (var i = 0, len = ranges.length; i < len; ++i) { ranges[i].deleteContents(); } // The spec says nothing about what the selection should contain after calling deleteContents on each // range. Firefox moves the selection to where the final selected range was, so we emulate that this.addRange(ranges[len - 1]); } } }; // The following are non-standard extensions selProto.eachRange = function(func, returnValue) { for (var i = 0, len = this._ranges.length; i < len; ++i) { if ( func( this.getRangeAt(i) ) ) { return returnValue; } } }; selProto.getAllRanges = function() { var ranges = []; this.eachRange(function(range) { ranges.push(range); }); return ranges; }; selProto.setSingleRange = function(range, direction) { this.removeAllRanges(); this.addRange(range, direction); }; selProto.callMethodOnEachRange = function(methodName, params) { var results = []; this.eachRange( function(range) { results.push( range[methodName].apply(range, params || []) ); } ); return results; }; function createStartOrEndSetter(isStart) { return function(node, offset) { var range; if (this.rangeCount) { range = this.getRangeAt(0); range["set" + (isStart ? "Start" : "End")](node, offset); } else { range = api.createRange(this.win.document); range.setStartAndEnd(node, offset); } this.setSingleRange(range, this.isBackward()); }; } selProto.setStart = createStartOrEndSetter(true); selProto.setEnd = createStartOrEndSetter(false); // Add select() method to Range prototype. Any existing selection will be removed. api.rangePrototype.select = function(direction) { getSelection( this.getDocument() ).setSingleRange(this, direction); }; selProto.changeEachRange = function(func) { var ranges = []; var backward = this.isBackward(); this.eachRange(function(range) { func(range); ranges.push(range); }); this.removeAllRanges(); if (backward && ranges.length == 1) { this.addRange(ranges[0], "backward"); } else { this.setRanges(ranges); } }; selProto.containsNode = function(node, allowPartial) { return this.eachRange( function(range) { return range.containsNode(node, allowPartial); }, true ) || false; }; selProto.getBookmark = function(containerNode) { return { backward: this.isBackward(), rangeBookmarks: this.callMethodOnEachRange("getBookmark", [containerNode]) }; }; selProto.moveToBookmark = function(bookmark) { var selRanges = []; for (var i = 0, rangeBookmark, range; rangeBookmark = bookmark.rangeBookmarks[i++]; ) { range = api.createRange(this.win); range.moveToBookmark(rangeBookmark); selRanges.push(range); } if (bookmark.backward) { this.setSingleRange(selRanges[0], "backward"); } else { this.setRanges(selRanges); } }; selProto.saveRanges = function() { return { backward: this.isBackward(), ranges: this.callMethodOnEachRange("cloneRange") }; }; selProto.restoreRanges = function(selRanges) { this.removeAllRanges(); for (var i = 0, range; range = selRanges.ranges[i]; ++i) { this.addRange(range, (selRanges.backward && i == 0)); } }; selProto.toHtml = function() { var rangeHtmls = []; this.eachRange(function(range) { rangeHtmls.push( DomRange.toHtml(range) ); }); return rangeHtmls.join(""); }; if (features.implementsTextRange) { selProto.getNativeTextRange = function() { var sel, textRange; if ( (sel = this.docSelection) ) { var range = sel.createRange(); if (isTextRange(range)) { return range; } else { throw module.createError("getNativeTextRange: selection is a control selection"); } } else if (this.rangeCount > 0) { return api.WrappedTextRange.rangeToTextRange( this.getRangeAt(0) ); } else { throw module.createError("getNativeTextRange: selection contains no range"); } }; } function inspect(sel) { var rangeInspects = []; var anchor = new DomPosition(sel.anchorNode, sel.anchorOffset); var focus = new DomPosition(sel.focusNode, sel.focusOffset); var name = (typeof sel.getName == "function") ? sel.getName() : "Selection"; if (typeof sel.rangeCount != "undefined") { for (var i = 0, len = sel.rangeCount; i < len; ++i) { rangeInspects[i] = DomRange.inspect(sel.getRangeAt(i)); } } return "[" + name + "(Ranges: " + rangeInspects.join(", ") + ")(anchor: " + anchor.inspect() + ", focus: " + focus.inspect() + "]"; } selProto.getName = function() { return "WrappedSelection"; }; selProto.inspect = function() { return inspect(this); }; selProto.detach = function() { actOnCachedSelection(this.win, "delete"); deleteProperties(this); }; WrappedSelection.detachAll = function() { actOnCachedSelection(null, "deleteAll"); }; WrappedSelection.inspect = inspect; WrappedSelection.isDirectionBackward = isDirectionBackward; api.Selection = WrappedSelection; api.selectionPrototype = selProto; api.addShimListener(function(win) { if (typeof win.getSelection == "undefined") { win.getSelection = function() { return getSelection(win); }; } win = null; }); }); /*----------------------------------------------------------------------------------------------------------------*/ // Wait for document to load before initializing var docReady = false; var loadHandler = function(e) { if (!docReady) { docReady = true; if (!api.initialized && api.config.autoInitialize) { init(); } } }; if (isBrowser) { // Test whether the document has already been loaded and initialize immediately if so if (document.readyState == "complete") { loadHandler(); } else { if (isHostMethod(document, "addEventListener")) { document.addEventListener("DOMContentLoaded", loadHandler, false); } // Add a fallback in case the DOMContentLoaded event isn't supported addListener(window, "load", loadHandler); } } return api; }, this);;/** * Selection save and restore module for Rangy. * Saves and restores user selections using marker invisible elements in the DOM. * * Part of Rangy, a cross-browser JavaScript range and selection library * https://github.com/timdown/rangy * * Depends on Rangy core. * * Copyright 2015, Tim Down * Licensed under the MIT license. * Version: 1.3.0 * Build date: 10 May 2015 */ (function(factory, root) { if (typeof define == "function" && define.amd) { // AMD. Register as an anonymous module with a dependency on Rangy. define(["./rangy-core"], factory); } else if (typeof module != "undefined" && typeof exports == "object") { // Node/CommonJS style module.exports = factory( require("rangy") ); } else { // No AMD or CommonJS support so we use the rangy property of root (probably the global variable) factory(root.rangy); } })(function(rangy) { rangy.createModule("SaveRestore", ["WrappedRange"], function(api, module) { var dom = api.dom; var removeNode = dom.removeNode; var isDirectionBackward = api.Selection.isDirectionBackward; var markerTextChar = "\ufeff"; function gEBI(id, doc) { return (doc || document).getElementById(id); } function insertRangeBoundaryMarker(range, atStart) { var markerId = "selectionBoundary_" + (+new Date()) + "_" + ("" + Math.random()).slice(2); var markerEl; var doc = dom.getDocument(range.startContainer); // Clone the Range and collapse to the appropriate boundary point var boundaryRange = range.cloneRange(); boundaryRange.collapse(atStart); // Create the marker element containing a single invisible character using DOM methods and insert it markerEl = doc.createElement("span"); markerEl.id = markerId; markerEl.style.lineHeight = "0"; markerEl.style.display = "none"; markerEl.className = "rangySelectionBoundary"; markerEl.appendChild(doc.createTextNode(markerTextChar)); boundaryRange.insertNode(markerEl); return markerEl; } function setRangeBoundary(doc, range, markerId, atStart) { var markerEl = gEBI(markerId, doc); if (markerEl) { range[atStart ? "setStartBefore" : "setEndBefore"](markerEl); removeNode(markerEl); } else { module.warn("Marker element has been removed. Cannot restore selection."); } } function compareRanges(r1, r2) { return r2.compareBoundaryPoints(r1.START_TO_START, r1); } function saveRange(range, direction) { var startEl, endEl, doc = api.DomRange.getRangeDocument(range), text = range.toString(); var backward = isDirectionBackward(direction); if (range.collapsed) { endEl = insertRangeBoundaryMarker(range, false); return { document: doc, markerId: endEl.id, collapsed: true }; } else { endEl = insertRangeBoundaryMarker(range, false); startEl = insertRangeBoundaryMarker(range, true); return { document: doc, startMarkerId: startEl.id, endMarkerId: endEl.id, collapsed: false, backward: backward, toString: function() { return "original text: '" + text + "', new text: '" + range.toString() + "'"; } }; } } function restoreRange(rangeInfo, normalize) { var doc = rangeInfo.document; if (typeof normalize == "undefined") { normalize = true; } var range = api.createRange(doc); if (rangeInfo.collapsed) { var markerEl = gEBI(rangeInfo.markerId, doc); if (markerEl) { markerEl.style.display = "inline"; var previousNode = markerEl.previousSibling; // Workaround for issue 17 if (previousNode && previousNode.nodeType == 3) { removeNode(markerEl); range.collapseToPoint(previousNode, previousNode.length); } else { range.collapseBefore(markerEl); removeNode(markerEl); } } else { module.warn("Marker element has been removed. Cannot restore selection."); } } else { setRangeBoundary(doc, range, rangeInfo.startMarkerId, true); setRangeBoundary(doc, range, rangeInfo.endMarkerId, false); } if (normalize) { range.normalizeBoundaries(); } return range; } function saveRanges(ranges, direction) { var rangeInfos = [], range, doc; var backward = isDirectionBackward(direction); // Order the ranges by position within the DOM, latest first, cloning the array to leave the original untouched ranges = ranges.slice(0); ranges.sort(compareRanges); for (var i = 0, len = ranges.length; i < len; ++i) { rangeInfos[i] = saveRange(ranges[i], backward); } // Now that all the markers are in place and DOM manipulation over, adjust each range's boundaries to lie // between its markers for (i = len - 1; i >= 0; --i) { range = ranges[i]; doc = api.DomRange.getRangeDocument(range); if (range.collapsed) { range.collapseAfter(gEBI(rangeInfos[i].markerId, doc)); } else { range.setEndBefore(gEBI(rangeInfos[i].endMarkerId, doc)); range.setStartAfter(gEBI(rangeInfos[i].startMarkerId, doc)); } } return rangeInfos; } function saveSelection(win) { if (!api.isSelectionValid(win)) { module.warn("Cannot save selection. This usually happens when the selection is collapsed and the selection document has lost focus."); return null; } var sel = api.getSelection(win); var ranges = sel.getAllRanges(); var backward = (ranges.length == 1 && sel.isBackward()); var rangeInfos = saveRanges(ranges, backward); // Ensure current selection is unaffected if (backward) { sel.setSingleRange(ranges[0], backward); } else { sel.setRanges(ranges); } return { win: win, rangeInfos: rangeInfos, restored: false }; } function restoreRanges(rangeInfos) { var ranges = []; // Ranges are in reverse order of appearance in the DOM. We want to restore earliest first to avoid // normalization affecting previously restored ranges. var rangeCount = rangeInfos.length; for (var i = rangeCount - 1; i >= 0; i--) { ranges[i] = restoreRange(rangeInfos[i], true); } return ranges; } function restoreSelection(savedSelection, preserveDirection) { if (!savedSelection.restored) { var rangeInfos = savedSelection.rangeInfos; var sel = api.getSelection(savedSelection.win); var ranges = restoreRanges(rangeInfos), rangeCount = rangeInfos.length; if (rangeCount == 1 && preserveDirection && api.features.selectionHasExtend && rangeInfos[0].backward) { sel.removeAllRanges(); sel.addRange(ranges[0], true); } else { sel.setRanges(ranges); } savedSelection.restored = true; } } function removeMarkerElement(doc, markerId) { var markerEl = gEBI(markerId, doc); if (markerEl) { removeNode(markerEl); } } function removeMarkers(savedSelection) { var rangeInfos = savedSelection.rangeInfos; for (var i = 0, len = rangeInfos.length, rangeInfo; i < len; ++i) { rangeInfo = rangeInfos[i]; if (rangeInfo.collapsed) { removeMarkerElement(savedSelection.doc, rangeInfo.markerId); } else { removeMarkerElement(savedSelection.doc, rangeInfo.startMarkerId); removeMarkerElement(savedSelection.doc, rangeInfo.endMarkerId); } } } api.util.extend(api, { saveRange: saveRange, restoreRange: restoreRange, saveRanges: saveRanges, restoreRanges: restoreRanges, saveSelection: saveSelection, restoreSelection: restoreSelection, removeMarkerElement: removeMarkerElement, removeMarkers: removeMarkers }); }); return rangy; }, this);;/* Base.js, version 1.1a Copyright 2006-2010, Dean Edwards License: http://www.opensource.org/licenses/mit-license.php */ var Base = function() { // dummy }; Base.extend = function(_instance, _static) { // subclass var extend = Base.prototype.extend; // build the prototype Base._prototyping = true; var proto = new this; extend.call(proto, _instance); proto.base = function() { // call this method from any other method to invoke that method's ancestor }; delete Base._prototyping; // create the wrapper for the constructor function //var constructor = proto.constructor.valueOf(); //-dean var constructor = proto.constructor; var klass = proto.constructor = function() { if (!Base._prototyping) { if (this._constructing || this.constructor == klass) { // instantiation this._constructing = true; constructor.apply(this, arguments); delete this._constructing; } else if (arguments[0] != null) { // casting return (arguments[0].extend || extend).call(arguments[0], proto); } } }; // build the class interface klass.ancestor = this; klass.extend = this.extend; klass.forEach = this.forEach; klass.implement = this.implement; klass.prototype = proto; klass.toString = this.toString; klass.valueOf = function(type) { //return (type == "object") ? klass : constructor; //-dean return (type == "object") ? klass : constructor.valueOf(); }; extend.call(klass, _static); // class initialisation if (typeof klass.init == "function") klass.init(); return klass; }; Base.prototype = { extend: function(source, value) { if (arguments.length > 1) { // extending with a name/value pair var ancestor = this[source]; if (ancestor && (typeof value == "function") && // overriding a method? // the valueOf() comparison is to avoid circular references (!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) && /\bbase\b/.test(value)) { // get the underlying method var method = value.valueOf(); // override value = function() { var previous = this.base || Base.prototype.base; this.base = ancestor; var returnValue = method.apply(this, arguments); this.base = previous; return returnValue; }; // point to the underlying method value.valueOf = function(type) { return (type == "object") ? value : method; }; value.toString = Base.toString; } this[source] = value; } else if (source) { // extending with an object literal var extend = Base.prototype.extend; // if this object has a customised extend method then use it if (!Base._prototyping && typeof this != "function") { extend = this.extend || extend; } var proto = {toSource: null}; // do the "toString" and other methods manually var hidden = ["constructor", "toString", "valueOf"]; // if we are prototyping then include the constructor var i = Base._prototyping ? 0 : 1; while (key = hidden[i++]) { if (source[key] != proto[key]) { extend.call(this, key, source[key]); } } // copy each of the source object's properties to this object for (var key in source) { if (!proto[key]) extend.call(this, key, source[key]); } } return this; } }; // initialise Base = Base.extend({ constructor: function() { this.extend(arguments[0]); } }, { ancestor: Object, version: "1.1", forEach: function(object, block, context) { for (var key in object) { if (this.prototype[key] === undefined) { block.call(context, object[key], key, object); } } }, implement: function() { for (var i = 0; i < arguments.length; i++) { if (typeof arguments[i] == "function") { // if it's a function, call it arguments[i](this.prototype); } else { // add the interface using the extend method this.prototype.extend(arguments[i]); } } return this; }, toString: function() { return String(this.valueOf()); } });;/** * Detect browser support for specific features */ wysihtml5.browser = (function() { var userAgent = navigator.userAgent, testElement = document.createElement("div"), // Browser sniffing is unfortunately needed since some behaviors are impossible to feature detect isGecko = userAgent.indexOf("Gecko") !== -1 && userAgent.indexOf("KHTML") === -1, isWebKit = userAgent.indexOf("AppleWebKit/") !== -1, isChrome = userAgent.indexOf("Chrome/") !== -1, isOpera = userAgent.indexOf("Opera/") !== -1; function iosVersion(userAgent) { return +((/ipad|iphone|ipod/.test(userAgent) && userAgent.match(/ os (\d+).+? like mac os x/)) || [undefined, 0])[1]; } function androidVersion(userAgent) { return +(userAgent.match(/android (\d+)/) || [undefined, 0])[1]; } function isIE(version, equation) { var rv = -1, re; if (navigator.appName == 'Microsoft Internet Explorer') { re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})"); } else if (navigator.appName == 'Netscape') { re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})"); } if (re && re.exec(navigator.userAgent) != null) { rv = parseFloat(RegExp.$1); } if (rv === -1) { return false; } if (!version) { return true; } if (!equation) { return version === rv; } if (equation === "<") { return version < rv; } if (equation === ">") { return version > rv; } if (equation === "<=") { return version <= rv; } if (equation === ">=") { return version >= rv; } } return { // Static variable needed, publicly accessible, to be able override it in unit tests USER_AGENT: userAgent, /** * Exclude browsers that are not capable of displaying and handling * contentEditable as desired: * - iPhone, iPad (tested iOS 4.2.2) and Android (tested 2.2) refuse to make contentEditables focusable * - IE < 8 create invalid markup and crash randomly from time to time * * @return {Boolean} */ supported: function() { var userAgent = this.USER_AGENT.toLowerCase(), // Essential for making html elements editable hasContentEditableSupport = "contentEditable" in testElement, // Following methods are needed in order to interact with the contentEditable area hasEditingApiSupport = document.execCommand && document.queryCommandSupported && document.queryCommandState, // document selector apis are only supported by IE 8+, Safari 4+, Chrome and Firefox 3.5+ hasQuerySelectorSupport = document.querySelector && document.querySelectorAll, // contentEditable is unusable in mobile browsers (tested iOS 4.2.2, Android 2.2, Opera Mobile, WebOS 3.05) isIncompatibleMobileBrowser = (this.isIos() && iosVersion(userAgent) < 5) || (this.isAndroid() && androidVersion(userAgent) < 4) || userAgent.indexOf("opera mobi") !== -1 || userAgent.indexOf("hpwos/") !== -1; return hasContentEditableSupport && hasEditingApiSupport && hasQuerySelectorSupport && !isIncompatibleMobileBrowser; }, isTouchDevice: function() { return this.supportsEvent("touchmove"); }, isIos: function() { return (/ipad|iphone|ipod/i).test(this.USER_AGENT); }, isAndroid: function() { return this.USER_AGENT.indexOf("Android") !== -1; }, /** * Whether the browser supports sandboxed iframes * Currently only IE 6+ offers such feature <iframe security="restricted"> * * http://msdn.microsoft.com/en-us/library/ms534622(v=vs.85).aspx * http://blogs.msdn.com/b/ie/archive/2008/01/18/using-frames-more-securely.aspx * * HTML5 sandboxed iframes are still buggy and their DOM is not reachable from the outside (except when using postMessage) */ supportsSandboxedIframes: function() { return isIE(); }, /** * IE6+7 throw a mixed content warning when the src of an iframe * is empty/unset or about:blank * window.querySelector is implemented as of IE8 */ throwsMixedContentWarningWhenIframeSrcIsEmpty: function() { return !("querySelector" in document); }, /** * Whether the caret is correctly displayed in contentEditable elements * Firefox sometimes shows a huge caret in the beginning after focusing */ displaysCaretInEmptyContentEditableCorrectly: function() { return isIE(); }, /** * Opera and IE are the only browsers who offer the css value * in the original unit, thx to the currentStyle object * All other browsers provide the computed style in px via window.getComputedStyle */ hasCurrentStyleProperty: function() { return "currentStyle" in testElement; }, /** * Whether the browser inserts a <br> when pressing enter in a contentEditable element */ insertsLineBreaksOnReturn: function() { return isGecko; }, supportsPlaceholderAttributeOn: function(element) { return "placeholder" in element; }, supportsEvent: function(eventName) { return "on" + eventName in testElement || (function() { testElement.setAttribute("on" + eventName, "return;"); return typeof(testElement["on" + eventName]) === "function"; })(); }, /** * Opera doesn't correctly fire focus/blur events when clicking in- and outside of iframe */ supportsEventsInIframeCorrectly: function() { return !isOpera; }, /** * Everything below IE9 doesn't know how to treat HTML5 tags * * @param {Object} context The document object on which to check HTML5 support * * @example * wysihtml5.browser.supportsHTML5Tags(document); */ supportsHTML5Tags: function(context) { var element = context.createElement("div"), html5 = "<article>foo</article>"; element.innerHTML = html5; return element.innerHTML.toLowerCase() === html5; }, /** * Checks whether a document supports a certain queryCommand * In particular, Opera needs a reference to a document that has a contentEditable in it's dom tree * in oder to report correct results * * @param {Object} doc Document object on which to check for a query command * @param {String} command The query command to check for * @return {Boolean} * * @example * wysihtml5.browser.supportsCommand(document, "bold"); */ supportsCommand: (function() { // Following commands are supported but contain bugs in some browsers var buggyCommands = { // formatBlock fails with some tags (eg. <blockquote>) "formatBlock": isIE(10, "<="), // When inserting unordered or ordered lists in Firefox, Chrome or Safari, the current selection or line gets // converted into a list (<ul><li>...</li></ul>, <ol><li>...</li></ol>) // IE and Opera act a bit different here as they convert the entire content of the current block element into a list "insertUnorderedList": isIE(9, ">="), "insertOrderedList": isIE(9, ">=") }; // Firefox throws errors for queryCommandSupported, so we have to build up our own object of supported commands var supported = { "insertHTML": isGecko }; return function(doc, command) { var isBuggy = buggyCommands[command]; if (!isBuggy) { // Firefox throws errors when invoking queryCommandSupported or queryCommandEnabled try { return doc.queryCommandSupported(command); } catch(e1) {} try { return doc.queryCommandEnabled(command); } catch(e2) { return !!supported[command]; } } return false; }; })(), /** * IE: URLs starting with: * www., http://, https://, ftp://, gopher://, mailto:, new:, snews:, telnet:, wasis:, file://, * nntp://, newsrc:, ldap://, ldaps://, outlook:, mic:// and url: * will automatically be auto-linked when either the user inserts them via copy&paste or presses the * space bar when the caret is directly after such an url. * This behavior cannot easily be avoided in IE < 9 since the logic is hardcoded in the mshtml.dll * (related blog post on msdn * http://blogs.msdn.com/b/ieinternals/archive/2009/09/17/prevent-automatic-hyperlinking-in-contenteditable-html.aspx). */ doesAutoLinkingInContentEditable: function() { return isIE(); }, /** * As stated above, IE auto links urls typed into contentEditable elements * Since IE9 it's possible to prevent this behavior */ canDisableAutoLinking: function() { return this.supportsCommand(document, "AutoUrlDetect"); }, /** * IE leaves an empty paragraph in the contentEditable element after clearing it * Chrome/Safari sometimes an empty <div> */ clearsContentEditableCorrectly: function() { return isGecko || isOpera || isWebKit; }, /** * IE gives wrong results for getAttribute */ supportsGetAttributeCorrectly: function() { var td = document.createElement("td"); return td.getAttribute("rowspan") != "1"; }, /** * When clicking on images in IE, Opera and Firefox, they are selected, which makes it easy to interact with them. * Chrome and Safari both don't support this */ canSelectImagesInContentEditable: function() { return isGecko || isIE() || isOpera; }, /** * All browsers except Safari and Chrome automatically scroll the range/caret position into view */ autoScrollsToCaret: function() { return !isWebKit; }, /** * Check whether the browser automatically closes tags that don't need to be opened */ autoClosesUnclosedTags: function() { var clonedTestElement = testElement.cloneNode(false), returnValue, innerHTML; clonedTestElement.innerHTML = "<p><div></div>"; innerHTML = clonedTestElement.innerHTML.toLowerCase(); returnValue = innerHTML === "<p></p><div></div>" || innerHTML === "<p><div></div></p>"; // Cache result by overwriting current function this.autoClosesUnclosedTags = function() { return returnValue; }; return returnValue; }, /** * Whether the browser supports the native document.getElementsByClassName which returns live NodeLists */ supportsNativeGetElementsByClassName: function() { return String(document.getElementsByClassName).indexOf("[native code]") !== -1; }, /** * As of now (19.04.2011) only supported by Firefox 4 and Chrome * See https://developer.mozilla.org/en/DOM/Selection/modify */ supportsSelectionModify: function() { return "getSelection" in window && "modify" in window.getSelection(); }, /** * Opera needs a white space after a <br> in order to position the caret correctly */ needsSpaceAfterLineBreak: function() { return isOpera; }, /** * Whether the browser supports the speech api on the given element * See http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/ * * @example * var input = document.createElement("input"); * if (wysihtml5.browser.supportsSpeechApiOn(input)) { * // ... * } */ supportsSpeechApiOn: function(input) { var chromeVersion = userAgent.match(/Chrome\/(\d+)/) || [undefined, 0]; return chromeVersion[1] >= 11 && ("onwebkitspeechchange" in input || "speech" in input); }, /** * IE9 crashes when setting a getter via Object.defineProperty on XMLHttpRequest or XDomainRequest * See https://connect.microsoft.com/ie/feedback/details/650112 * or try the POC http://tifftiff.de/ie9_crash/ */ crashesWhenDefineProperty: function(property) { return isIE(9) && (property === "XMLHttpRequest" || property === "XDomainRequest"); }, /** * IE is the only browser who fires the "focus" event not immediately when .focus() is called on an element */ doesAsyncFocus: function() { return isIE(); }, /** * In IE it's impssible for the user and for the selection library to set the caret after an <img> when it's the lastChild in the document */ hasProblemsSettingCaretAfterImg: function() { return isIE(); }, hasUndoInContextMenu: function() { return isGecko || isChrome || isOpera; }, /** * Opera sometimes doesn't insert the node at the right position when range.insertNode(someNode) * is used (regardless if rangy or native) * This especially happens when the caret is positioned right after a <br> because then * insertNode() will insert the node right before the <br> */ hasInsertNodeIssue: function() { return isOpera; }, /** * IE 8+9 don't fire the focus event of the <body> when the iframe gets focused (even though the caret gets set into the <body>) */ hasIframeFocusIssue: function() { return isIE(); }, /** * Chrome + Safari create invalid nested markup after paste * * <p> * foo * <p>bar</p> <!-- BOO! --> * </p> */ createsNestedInvalidMarkupAfterPaste: function() { return isWebKit; }, supportsMutationEvents: function() { return ("MutationEvent" in window); }, /** IE (at least up to 11) does not support clipboardData on event. It is on window but cannot return text/html Should actually check for clipboardData on paste event, but cannot in firefox */ supportsModernPaste: function () { return !("clipboardData" in window); }, // Unifies the property names of element.style by returning the suitable property name for current browser // Input property key must be the standard fixStyleKey: function(key) { if (key === "cssFloat") { return ("styleFloat" in document.createElement("div").style) ? "styleFloat" : "cssFloat"; } return key; } }; })(); ;wysihtml5.lang.array = function(arr) { return { /** * Check whether a given object exists in an array * * @example * wysihtml5.lang.array([1, 2]).contains(1); * // => true * * Can be used to match array with array. If intersection is found true is returned */ contains: function(needle) { if (Array.isArray(needle)) { for (var i = needle.length; i--;) { if (wysihtml5.lang.array(arr).indexOf(needle[i]) !== -1) { return true; } } return false; } else { return wysihtml5.lang.array(arr).indexOf(needle) !== -1; } }, /** * Check whether a given object exists in an array and return index * If no elelemt found returns -1 * * @example * wysihtml5.lang.array([1, 2]).indexOf(2); * // => 1 */ indexOf: function(needle) { if (arr.indexOf) { return arr.indexOf(needle); } else { for (var i=0, length=arr.length; i<length; i++) { if (arr[i] === needle) { return i; } } return -1; } }, /** * Substract one array from another * * @example * wysihtml5.lang.array([1, 2, 3, 4]).without([3, 4]); * // => [1, 2] */ without: function(arrayToSubstract) { arrayToSubstract = wysihtml5.lang.array(arrayToSubstract); var newArr = [], i = 0, length = arr.length; for (; i<length; i++) { if (!arrayToSubstract.contains(arr[i])) { newArr.push(arr[i]); } } return newArr; }, /** * Return a clean native array * * Following will convert a Live NodeList to a proper Array * @example * var childNodes = wysihtml5.lang.array(document.body.childNodes).get(); */ get: function() { var i = 0, length = arr.length, newArray = []; for (; i<length; i++) { newArray.push(arr[i]); } return newArray; }, /** * Creates a new array with the results of calling a provided function on every element in this array. * optionally this can be provided as second argument * * @example * var childNodes = wysihtml5.lang.array([1,2,3,4]).map(function (value, index, array) { return value * 2; * }); * // => [2,4,6,8] */ map: function(callback, thisArg) { if (Array.prototype.map) { return arr.map(callback, thisArg); } else { var len = arr.length >>> 0, A = new Array(len), i = 0; for (; i < len; i++) { A[i] = callback.call(thisArg, arr[i], i, arr); } return A; } }, /* ReturnS new array without duplicate entries * * @example * var uniq = wysihtml5.lang.array([1,2,3,2,1,4]).unique(); * // => [1,2,3,4] */ unique: function() { var vals = [], max = arr.length, idx = 0; while (idx < max) { if (!wysihtml5.lang.array(vals).contains(arr[idx])) { vals.push(arr[idx]); } idx++; } return vals; } }; }; ;wysihtml5.lang.Dispatcher = Base.extend( /** @scope wysihtml5.lang.Dialog.prototype */ { on: function(eventName, handler) { this.events = this.events || {}; this.events[eventName] = this.events[eventName] || []; this.events[eventName].push(handler); return this; }, off: function(eventName, handler) { this.events = this.events || {}; var i = 0, handlers, newHandlers; if (eventName) { handlers = this.events[eventName] || [], newHandlers = []; for (; i<handlers.length; i++) { if (handlers[i] !== handler && handler) { newHandlers.push(handlers[i]); } } this.events[eventName] = newHandlers; } else { // Clean up all events this.events = {}; } return this; }, fire: function(eventName, payload) { this.events = this.events || {}; var handlers = this.events[eventName] || [], i = 0; for (; i<handlers.length; i++) { handlers[i].call(this, payload); } return this; }, // deprecated, use .on() observe: function() { return this.on.apply(this, arguments); }, // deprecated, use .off() stopObserving: function() { return this.off.apply(this, arguments); } }); ;wysihtml5.lang.object = function(obj) { return { /** * @example * wysihtml5.lang.object({ foo: 1, bar: 1 }).merge({ bar: 2, baz: 3 }).get(); * // => { foo: 1, bar: 2, baz: 3 } */ merge: function(otherObj, deep) { for (var i in otherObj) { if (deep && wysihtml5.lang.object(otherObj[i]).isPlainObject() && (typeof obj[i] === "undefined" || wysihtml5.lang.object(obj[i]).isPlainObject())) { if (typeof obj[i] === "undefined") { obj[i] = wysihtml5.lang.object(otherObj[i]).clone(true); } else { wysihtml5.lang.object(obj[i]).merge(wysihtml5.lang.object(otherObj[i]).clone(true)); } } else { obj[i] = wysihtml5.lang.object(otherObj[i]).isPlainObject() ? wysihtml5.lang.object(otherObj[i]).clone(true) : otherObj[i]; } } return this; }, difference: function (otherObj) { var diffObj = {}; // Get old values not in comparing object for (var i in obj) { if (obj.hasOwnProperty(i)) { if (!otherObj.hasOwnProperty(i)) { diffObj[i] = obj[i]; } } } // Get new and different values in comparing object for (var o in otherObj) { if (otherObj.hasOwnProperty(o)) { if (!obj.hasOwnProperty(o) || obj[o] !== otherObj[o]) { diffObj[0] = obj[0]; } } } return diffObj; }, get: function() { return obj; }, /** * @example * wysihtml5.lang.object({ foo: 1 }).clone(); * // => { foo: 1 } * * v0.4.14 adds options for deep clone : wysihtml5.lang.object({ foo: 1 }).clone(true); */ clone: function(deep) { var newObj = {}, i; if (obj === null || !wysihtml5.lang.object(obj).isPlainObject()) { return obj; } for (i in obj) { if(obj.hasOwnProperty(i)) { if (deep) { newObj[i] = wysihtml5.lang.object(obj[i]).clone(deep); } else { newObj[i] = obj[i]; } } } return newObj; }, /** * @example * wysihtml5.lang.object([]).isArray(); * // => true */ isArray: function() { return Object.prototype.toString.call(obj) === "[object Array]"; }, /** * @example * wysihtml5.lang.object(function() {}).isFunction(); * // => true */ isFunction: function() { return Object.prototype.toString.call(obj) === '[object Function]'; }, isPlainObject: function () { return obj && Object.prototype.toString.call(obj) === '[object Object]' && !(("Node" in window) ? obj instanceof Node : obj instanceof Element || obj instanceof Text); }, /** * @example * wysihtml5.lang.object({}).isEmpty(); * // => true */ isEmpty: function() { for (var i in obj) { if (obj.hasOwnProperty(i)) { return false; } } return true; } }; }; ;(function() { var WHITE_SPACE_START = /^\s+/, WHITE_SPACE_END = /\s+$/, ENTITY_REG_EXP = /[&<>\t"]/g, ENTITY_MAP = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': "&quot;", '\t':"&nbsp; " }; wysihtml5.lang.string = function(str) { str = String(str); return { /** * @example * wysihtml5.lang.string(" foo ").trim(); * // => "foo" */ trim: function() { return str.replace(WHITE_SPACE_START, "").replace(WHITE_SPACE_END, ""); }, /** * @example * wysihtml5.lang.string("Hello #{name}").interpolate({ name: "Christopher" }); * // => "Hello Christopher" */ interpolate: function(vars) { for (var i in vars) { str = this.replace("#{" + i + "}").by(vars[i]); } return str; }, /** * @example * wysihtml5.lang.string("Hello Tom").replace("Tom").with("Hans"); * // => "Hello Hans" */ replace: function(search) { return { by: function(replace) { return str.split(search).join(replace); } }; }, /** * @example * wysihtml5.lang.string("hello<br>").escapeHTML(); * // => "hello&lt;br&gt;" */ escapeHTML: function(linebreaks, convertSpaces) { var html = str.replace(ENTITY_REG_EXP, function(c) { return ENTITY_MAP[c]; }); if (linebreaks) { html = html.replace(/(?:\r\n|\r|\n)/g, '<br />'); } if (convertSpaces) { html = html.replace(/ /gi, "&nbsp; "); } return html; } }; }; })(); ;/** * Find urls in descendant text nodes of an element and auto-links them * Inspired by http://james.padolsey.com/javascript/find-and-replace-text-with-javascript/ * * @param {Element} element Container element in which to search for urls * * @example * <div id="text-container">Please click here: www.google.com</div> * <script>wysihtml5.dom.autoLink(document.getElementById("text-container"));</script> */ (function(wysihtml5) { var /** * Don't auto-link urls that are contained in the following elements: */ IGNORE_URLS_IN = wysihtml5.lang.array(["CODE", "PRE", "A", "SCRIPT", "HEAD", "TITLE", "STYLE"]), /** * revision 1: * /(\S+\.{1}[^\s\,\.\!]+)/g * * revision 2: * /(\b(((https?|ftp):\/\/)|(www\.))[-A-Z0-9+&@#\/%?=~_|!:,.;\[\]]*[-A-Z0-9+&@#\/%=~_|])/gim * * put this in the beginning if you don't wan't to match within a word * (^|[\>\(\{\[\s\>]) */ URL_REG_EXP = /((https?:\/\/|www\.)[^\s<]{3,})/gi, TRAILING_CHAR_REG_EXP = /([^\w\/\-](,?))$/i, MAX_DISPLAY_LENGTH = 100, BRACKETS = { ")": "(", "]": "[", "}": "{" }; function autoLink(element, ignoreInClasses) { if (_hasParentThatShouldBeIgnored(element, ignoreInClasses)) { return element; } if (element === element.ownerDocument.documentElement) { element = element.ownerDocument.body; } return _parseNode(element, ignoreInClasses); } /** * This is basically a rebuild of * the rails auto_link_urls text helper */ function _convertUrlsToLinks(str) { return str.replace(URL_REG_EXP, function(match, url) { var punctuation = (url.match(TRAILING_CHAR_REG_EXP) || [])[1] || "", opening = BRACKETS[punctuation]; url = url.replace(TRAILING_CHAR_REG_EXP, ""); if (url.split(opening).length > url.split(punctuation).length) { url = url + punctuation; punctuation = ""; } var realUrl = url, displayUrl = url; if (url.length > MAX_DISPLAY_LENGTH) { displayUrl = displayUrl.substr(0, MAX_DISPLAY_LENGTH) + "..."; } // Add http prefix if necessary if (realUrl.substr(0, 4) === "www.") { realUrl = "http://" + realUrl; } return '<a href="' + realUrl + '">' + displayUrl + '</a>' + punctuation; }); } /** * Creates or (if already cached) returns a temp element * for the given document object */ function _getTempElement(context) { var tempElement = context._wysihtml5_tempElement; if (!tempElement) { tempElement = context._wysihtml5_tempElement = context.createElement("div"); } return tempElement; } /** * Replaces the original text nodes with the newly auto-linked dom tree */ function _wrapMatchesInNode(textNode) { var parentNode = textNode.parentNode, nodeValue = wysihtml5.lang.string(textNode.data).escapeHTML(), tempElement = _getTempElement(parentNode.ownerDocument); // We need to insert an empty/temporary <span /> to fix IE quirks // Elsewise IE would strip white space in the beginning tempElement.innerHTML = "<span></span>" + _convertUrlsToLinks(nodeValue); tempElement.removeChild(tempElement.firstChild); while (tempElement.firstChild) { // inserts tempElement.firstChild before textNode parentNode.insertBefore(tempElement.firstChild, textNode); } parentNode.removeChild(textNode); } function _hasParentThatShouldBeIgnored(node, ignoreInClasses) { var nodeName; while (node.parentNode) { node = node.parentNode; nodeName = node.nodeName; if (node.className && wysihtml5.lang.array(node.className.split(' ')).contains(ignoreInClasses)) { return true; } if (IGNORE_URLS_IN.contains(nodeName)) { return true; } else if (nodeName === "body") { return false; } } return false; } function _parseNode(element, ignoreInClasses) { if (IGNORE_URLS_IN.contains(element.nodeName)) { return; } if (element.className && wysihtml5.lang.array(element.className.split(' ')).contains(ignoreInClasses)) { return; } if (element.nodeType === wysihtml5.TEXT_NODE && element.data.match(URL_REG_EXP)) { _wrapMatchesInNode(element); return; } var childNodes = wysihtml5.lang.array(element.childNodes).get(), childNodesLength = childNodes.length, i = 0; for (; i<childNodesLength; i++) { _parseNode(childNodes[i], ignoreInClasses); } return element; } wysihtml5.dom.autoLink = autoLink; // Reveal url reg exp to the outside wysihtml5.dom.autoLink.URL_REG_EXP = URL_REG_EXP; })(wysihtml5); ;(function(wysihtml5) { var api = wysihtml5.dom; api.addClass = function(element, className) { var classList = element.classList; if (classList) { return classList.add(className); } if (api.hasClass(element, className)) { return; } element.className += " " + className; }; api.removeClass = function(element, className) { var classList = element.classList; if (classList) { return classList.remove(className); } element.className = element.className.replace(new RegExp("(^|\\s+)" + className + "(\\s+|$)"), " "); }; api.hasClass = function(element, className) { var classList = element.classList; if (classList) { return classList.contains(className); } var elementClassName = element.className; return (elementClassName.length > 0 && (elementClassName == className || new RegExp("(^|\\s)" + className + "(\\s|$)").test(elementClassName))); }; })(wysihtml5); ;wysihtml5.dom.contains = (function() { var documentElement = document.documentElement; if (documentElement.contains) { return function(container, element) { if (element.nodeType !== wysihtml5.ELEMENT_NODE) { if (element.parentNode === container) { return true; } element = element.parentNode; } return container !== element && container.contains(element); }; } else if (documentElement.compareDocumentPosition) { return function(container, element) { // https://developer.mozilla.org/en/DOM/Node.compareDocumentPosition return !!(container.compareDocumentPosition(element) & 16); }; } })(); ;/** * Converts an HTML fragment/element into a unordered/ordered list * * @param {Element} element The element which should be turned into a list * @param {String} listType The list type in which to convert the tree (either "ul" or "ol") * @return {Element} The created list * * @example * <!-- Assume the following dom: --> * <span id="pseudo-list"> * eminem<br> * dr. dre * <div>50 Cent</div> * </span> * * <script> * wysihtml5.dom.convertToList(document.getElementById("pseudo-list"), "ul"); * </script> * * <!-- Will result in: --> * <ul> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> */ wysihtml5.dom.convertToList = (function() { function _createListItem(doc, list) { var listItem = doc.createElement("li"); list.appendChild(listItem); return listItem; } function _createList(doc, type) { return doc.createElement(type); } function convertToList(element, listType, uneditableClass) { if (element.nodeName === "UL" || element.nodeName === "OL" || element.nodeName === "MENU") { // Already a list return element; } var doc = element.ownerDocument, list = _createList(doc, listType), lineBreaks = element.querySelectorAll("br"), lineBreaksLength = lineBreaks.length, childNodes, childNodesLength, childNode, lineBreak, parentNode, isBlockElement, isLineBreak, currentListItem, i; // First find <br> at the end of inline elements and move them behind them for (i=0; i<lineBreaksLength; i++) { lineBreak = lineBreaks[i]; while ((parentNode = lineBreak.parentNode) && parentNode !== element && parentNode.lastChild === lineBreak) { if (wysihtml5.dom.getStyle("display").from(parentNode) === "block") { parentNode.removeChild(lineBreak); break; } wysihtml5.dom.insert(lineBreak).after(lineBreak.parentNode); } } childNodes = wysihtml5.lang.array(element.childNodes).get(); childNodesLength = childNodes.length; for (i=0; i<childNodesLength; i++) { currentListItem = currentListItem || _createListItem(doc, list); childNode = childNodes[i]; isBlockElement = wysihtml5.dom.getStyle("display").from(childNode) === "block"; isLineBreak = childNode.nodeName === "BR"; // consider uneditable as an inline element if (isBlockElement && (!uneditableClass || !wysihtml5.dom.hasClass(childNode, uneditableClass))) { // Append blockElement to current <li> if empty, otherwise create a new one currentListItem = currentListItem.firstChild ? _createListItem(doc, list) : currentListItem; currentListItem.appendChild(childNode); currentListItem = null; continue; } if (isLineBreak) { // Only create a new list item in the next iteration when the current one has already content currentListItem = currentListItem.firstChild ? null : currentListItem; continue; } currentListItem.appendChild(childNode); } if (childNodes.length === 0) { _createListItem(doc, list); } element.parentNode.replaceChild(list, element); return list; } return convertToList; })(); ;/** * Copy a set of attributes from one element to another * * @param {Array} attributesToCopy List of attributes which should be copied * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to * copy the attributes from., this again returns an object which provides a method named "to" which can be invoked * with the element where to copy the attributes to (see example) * * @example * var textarea = document.querySelector("textarea"), * div = document.querySelector("div[contenteditable=true]"), * anotherDiv = document.querySelector("div.preview"); * wysihtml5.dom.copyAttributes(["spellcheck", "value", "placeholder"]).from(textarea).to(div).andTo(anotherDiv); * */ wysihtml5.dom.copyAttributes = function(attributesToCopy) { return { from: function(elementToCopyFrom) { return { to: function(elementToCopyTo) { var attribute, i = 0, length = attributesToCopy.length; for (; i<length; i++) { attribute = attributesToCopy[i]; if (typeof(elementToCopyFrom[attribute]) !== "undefined" && elementToCopyFrom[attribute] !== "") { elementToCopyTo[attribute] = elementToCopyFrom[attribute]; } } return { andTo: arguments.callee }; } }; } }; }; ;/** * Copy a set of styles from one element to another * Please note that this only works properly across browsers when the element from which to copy the styles * is in the dom * * Interesting article on how to copy styles * * @param {Array} stylesToCopy List of styles which should be copied * @return {Object} Returns an object which offers the "from" method which can be invoked with the element where to * copy the styles from., this again returns an object which provides a method named "to" which can be invoked * with the element where to copy the styles to (see example) * * @example * var textarea = document.querySelector("textarea"), * div = document.querySelector("div[contenteditable=true]"), * anotherDiv = document.querySelector("div.preview"); * wysihtml5.dom.copyStyles(["overflow-y", "width", "height"]).from(textarea).to(div).andTo(anotherDiv); * */ (function(dom) { /** * Mozilla, WebKit and Opera recalculate the computed width when box-sizing: boder-box; is set * So if an element has "width: 200px; -moz-box-sizing: border-box; border: 1px;" then * its computed css width will be 198px * * See https://bugzilla.mozilla.org/show_bug.cgi?id=520992 */ var BOX_SIZING_PROPERTIES = ["-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing"]; var shouldIgnoreBoxSizingBorderBox = function(element) { if (hasBoxSizingBorderBox(element)) { return parseInt(dom.getStyle("width").from(element), 10) < element.offsetWidth; } return false; }; var hasBoxSizingBorderBox = function(element) { var i = 0, length = BOX_SIZING_PROPERTIES.length; for (; i<length; i++) { if (dom.getStyle(BOX_SIZING_PROPERTIES[i]).from(element) === "border-box") { return BOX_SIZING_PROPERTIES[i]; } } }; dom.copyStyles = function(stylesToCopy) { return { from: function(element) { if (shouldIgnoreBoxSizingBorderBox(element)) { stylesToCopy = wysihtml5.lang.array(stylesToCopy).without(BOX_SIZING_PROPERTIES); } var cssText = "", length = stylesToCopy.length, i = 0, property; for (; i<length; i++) { property = stylesToCopy[i]; cssText += property + ":" + dom.getStyle(property).from(element) + ";"; } return { to: function(element) { dom.setStyles(cssText).on(element); return { andTo: arguments.callee }; } }; } }; }; })(wysihtml5.dom); ;/** * Event Delegation * * @example * wysihtml5.dom.delegate(document.body, "a", "click", function() { * // foo * }); */ (function(wysihtml5) { wysihtml5.dom.delegate = function(container, selector, eventName, handler) { var callback = function(event) { var target = event.target, element = (target.nodeType === 3) ? target.parentNode : target, // IE has .contains only seeing elements not textnodes matches = container.querySelectorAll(selector); for (var i = 0, max = matches.length; i < max; i++) { if (matches[i].contains(element)) { handler.call(matches[i], event); } } }; container.addEventListener(eventName, callback, false); return { stop: function() { container.removeEventListener(eventName, callback, false); } }; }; })(wysihtml5); ;// TODO: Refactor dom tree traversing here (function(wysihtml5) { // Finds parents of a node, returning the outermost node first in Array // if contain node is given parents search is stopped at the container function parents(node, container) { var nodes = [node], n = node; // iterate parents while parent exists and it is not container element while((container && n && n !== container) || (!container && n)) { nodes.unshift(n); n = n.parentNode; } return nodes; } wysihtml5.dom.domNode = function(node) { var defaultNodeTypes = [wysihtml5.ELEMENT_NODE, wysihtml5.TEXT_NODE]; return { is: { emptyTextNode: function(ignoreWhitespace) { var regx = ignoreWhitespace ? (/^\s*$/g) : (/^[\r\n]*$/g); return node.nodeType === wysihtml5.TEXT_NODE && (regx).test(node.data); }, visible: function() { var isVisible = !(/^\s*$/g).test(wysihtml5.dom.getTextContent(node)); if (!isVisible) { if (node.nodeType === 1 && node.querySelector('img, br, hr, object, embed, canvas, input, textarea')) { isVisible = true; } } return isVisible; } }, // var node = wysihtml5.dom.domNode(element).prev({nodeTypes: [1,3], ignoreBlankTexts: true}); prev: function(options) { var prevNode = node.previousSibling, types = (options && options.nodeTypes) ? options.nodeTypes : defaultNodeTypes; if (!prevNode) { return null; } if ( (!wysihtml5.lang.array(types).contains(prevNode.nodeType)) || // nodeTypes check. (options && options.ignoreBlankTexts && wysihtml5.dom.domNode(prevNode).is.emptyTextNode(true)) // Blank text nodes bypassed if set ) { return wysihtml5.dom.domNode(prevNode).prev(options); } return prevNode; }, // var node = wysihtml5.dom.domNode(element).next({nodeTypes: [1,3], ignoreBlankTexts: true}); next: function(options) { var nextNode = node.nextSibling, types = (options && options.nodeTypes) ? options.nodeTypes : defaultNodeTypes; if (!nextNode) { return null; } if ( (!wysihtml5.lang.array(types).contains(nextNode.nodeType)) || // nodeTypes check. (options && options.ignoreBlankTexts && wysihtml5.dom.domNode(nextNode).is.emptyTextNode(true)) // blank text nodes bypassed if set ) { return wysihtml5.dom.domNode(nextNode).next(options); } return nextNode; }, // Finds the common acnestor container of two nodes // If container given stops search at the container // If no common ancestor found returns null // var node = wysihtml5.dom.domNode(element).commonAncestor(node2, container); commonAncestor: function(node2, container) { var parents1 = parents(node, container), parents2 = parents(node2, container); // Ensure we have found a common ancestor, which will be the first one if anything if (parents1[0] != parents2[0]) { return null; } // Traverse up the hierarchy of parents until we reach where they're no longer // the same. Then return previous which was the common ancestor. for (var i = 0; i < parents1.length; i++) { if (parents1[i] != parents2[i]) { return parents1[i - 1]; } } return null; }, // Traverses a node for last children and their chidren (including itself), and finds the last node that has no children. // Array of classes for forced last-leaves (ex: uneditable-container) can be defined (options = {leafClasses: [...]}) // Useful for finding the actually visible element before cursor lastLeafNode: function(options) { var lastChild; // Returns non-element nodes if (node.nodeType !== 1) { return node; } // Returns if element is leaf lastChild = node.lastChild; if (!lastChild) { return node; } // Returns if element is of of options.leafClasses leaf if (options && options.leafClasses) { for (var i = options.leafClasses.length; i--;) { if (wysihtml5.dom.hasClass(node, options.leafClasses[i])) { return node; } } } return wysihtml5.dom.domNode(lastChild).lastLeafNode(options); }, // Splits element at childnode and extracts the childNode out of the element context // Example: // var node = wysihtml5.dom.domNode(node).escapeParent(parentNode); escapeParent: function(element, newWrapper) { var parent, split2, nodeWrap, curNode = node; // Stop if node is not a descendant of element if (!wysihtml5.dom.contains(element, node)) { throw new Error("Child is not a descendant of node."); } // Climb up the node tree untill node is reached do { // Get current parent of node parent = curNode.parentNode; // Move after nodes to new clone wrapper split2 = parent.cloneNode(false); while (parent.lastChild && parent.lastChild !== curNode) { split2.insertBefore(parent.lastChild, split2.firstChild); } // Move node up a level. If parent is not yet the container to escape, clone the parent around node, so inner nodes are escaped out too if (parent !== element) { nodeWrap = parent.cloneNode(false); nodeWrap.appendChild(curNode); curNode = nodeWrap; } parent.parentNode.insertBefore(curNode, parent.nextSibling); // Add after nodes (unless empty) if (split2.innerHTML !== '') { // if contents are empty insert without wrap if ((/^\s+$/).test(split2.innerHTML)) { while (split2.lastChild) { parent.parentNode.insertBefore(split2.lastChild, curNode.nextSibling); } } else { parent.parentNode.insertBefore(split2, curNode.nextSibling); } } // If the node left behind before the split (parent) is now empty then remove if (parent.innerHTML === '') { parent.parentNode.removeChild(parent); } else if ((/^\s+$/).test(parent.innerHTML)) { while (parent.firstChild) { parent.parentNode.insertBefore(parent.firstChild, parent); } parent.parentNode.removeChild(parent); } } while (parent && parent !== element); if (newWrapper && curNode) { curNode.parentNode.insertBefore(newWrapper, curNode); newWrapper.appendChild(curNode); } }, /* Tests a node against properties, and returns true if matches. Tests on principle that all properties defined must have at least one match. styleValue parameter works in context of styleProperty and has no effect otherwise. Returns true if element matches and false if it does not. Properties for filtering element: { query: selector string, nodeName: string (uppercase), className: string, classRegExp: regex, styleProperty: string or [], styleValue: string, [] or regex } Example: var node = wysihtml5.dom.domNode(element).test({}) */ test: function(properties) { var prop; // retuern false if properties object is not defined if (!properties) { return false; } // Only element nodes can be tested for these properties if (node.nodeType !== 1) { return false; } if (properties.query) { if (!node.matches(properties.query)) { return false; } } if (properties.nodeName && node.nodeName !== properties.nodeName) { return false; } if (properties.className && !node.classList.contains(properties.className)) { return false; } // classRegExp check (useful for classname begins with logic) if (properties.classRegExp) { var matches = (node.className || "").match(properties.classRegExp) || []; if (matches.length === 0) { return false; } } // styleProperty check if (properties.styleProperty && properties.styleProperty.length > 0) { var hasOneStyle = false, styles = (Array.isArray(properties.styleProperty)) ? properties.styleProperty : [properties.styleProperty]; for (var j = 0, maxStyleP = styles.length; j < maxStyleP; j++) { // Some old IE-s have different property name for cssFloat prop = wysihtml5.browser.fixStyleKey(styles[j]); if (node.style[prop]) { if (properties.styleValue) { // Style value as additional parameter if (properties.styleValue instanceof RegExp) { // style value as Regexp if (node.style[prop].trim().match(properties.styleValue).length > 0) { hasOneStyle = true; break; } } else if (Array.isArray(properties.styleValue)) { // style value as array if (properties.styleValue.indexOf(node.style[prop].trim())) { hasOneStyle = true; break; } } else { // style value as string if (properties.styleValue === node.style[prop].trim().replace(/, /g, ",")) { hasOneStyle = true; break; } } } else { hasOneStyle = true; break; } } if (!hasOneStyle) { return false; } } } if (properties.attribute) { var attr = wysihtml5.dom.getAttributes(node), attrList = [], hasOneAttribute = false; if (Array.isArray(properties.attribute)) { attrList = properties.attribute; } else { attrList[properties.attribute] = properties.attributeValue; } for (var a in attrList) { if (attrList.hasOwnProperty(a)) { if (typeof attrList[a] === "undefined") { if (typeof attr[a] !== "undefined") { hasOneAttribute = true; break; } } else if (attr[a] === attrList[a]) { hasOneAttribute = true; break; } } } if (!hasOneAttribute) { return false; } } return true; } }; }; })(wysihtml5); ;/** * Returns the given html wrapped in a div element * * Fixing IE's inability to treat unknown elements (HTML5 section, article, ...) correctly * when inserted via innerHTML * * @param {String} html The html which should be wrapped in a dom element * @param {Obejct} [context] Document object of the context the html belongs to * * @example * wysihtml5.dom.getAsDom("<article>foo</article>"); */ wysihtml5.dom.getAsDom = (function() { var _innerHTMLShiv = function(html, context) { var tempElement = context.createElement("div"); tempElement.style.display = "none"; context.body.appendChild(tempElement); // IE throws an exception when trying to insert <frameset></frameset> via innerHTML try { tempElement.innerHTML = html; } catch(e) {} context.body.removeChild(tempElement); return tempElement; }; /** * Make sure IE supports HTML5 tags, which is accomplished by simply creating one instance of each element */ var _ensureHTML5Compatibility = function(context) { if (context._wysihtml5_supportsHTML5Tags) { return; } for (var i=0, length=HTML5_ELEMENTS.length; i<length; i++) { context.createElement(HTML5_ELEMENTS[i]); } context._wysihtml5_supportsHTML5Tags = true; }; /** * List of html5 tags * taken from http://simon.html5.org/html5-elements */ var HTML5_ELEMENTS = [ "abbr", "article", "aside", "audio", "bdi", "canvas", "command", "datalist", "details", "figcaption", "figure", "footer", "header", "hgroup", "keygen", "mark", "meter", "nav", "output", "progress", "rp", "rt", "ruby", "svg", "section", "source", "summary", "time", "track", "video", "wbr" ]; return function(html, context) { context = context || document; var tempElement; if (typeof(html) === "object" && html.nodeType) { tempElement = context.createElement("div"); tempElement.appendChild(html); } else if (wysihtml5.browser.supportsHTML5Tags(context)) { tempElement = context.createElement("div"); tempElement.innerHTML = html; } else { _ensureHTML5Compatibility(context); tempElement = _innerHTMLShiv(html, context); } return tempElement; }; })(); ;/** * Walks the dom tree from the given node up until it finds a match * * @param {Element} node The from which to check the parent nodes * @param {Object} matchingSet Object to match against, Properties for filtering element: * { * query: selector string, * classRegExp: regex, * styleProperty: string or [], * styleValue: string, [] or regex * } * @param {Number} [levels] How many parents should the function check up from the current node (defaults to 50) * @param {Element} Optional, defines the container that limits the search * * @return {null|Element} Returns the first element that matched the desiredNodeName(s) */ wysihtml5.dom.getParentElement = (function() { return function(node, properties, levels, container) { levels = levels || 50; while (levels-- && node && node.nodeName !== "BODY" && (!container || node !== container)) { if (wysihtml5.dom.domNode(node).test(properties)) { return node; } node = node.parentNode; } return null; }; })(); ;/** * Get element's style for a specific css property * * @param {Element} element The element on which to retrieve the style * @param {String} property The CSS property to retrieve ("float", "display", "text-align", ...) * * @example * wysihtml5.dom.getStyle("display").from(document.body); * // => "block" */ wysihtml5.dom.getStyle = (function() { var stylePropertyMapping = { "float": ("styleFloat" in document.createElement("div").style) ? "styleFloat" : "cssFloat" }, REG_EXP_CAMELIZE = /\-[a-z]/g; function camelize(str) { return str.replace(REG_EXP_CAMELIZE, function(match) { return match.charAt(1).toUpperCase(); }); } return function(property) { return { from: function(element) { if (element.nodeType !== wysihtml5.ELEMENT_NODE) { return; } var doc = element.ownerDocument, camelizedProperty = stylePropertyMapping[property] || camelize(property), style = element.style, currentStyle = element.currentStyle, styleValue = style[camelizedProperty]; if (styleValue) { return styleValue; } // currentStyle is no standard and only supported by Opera and IE but it has one important advantage over the standard-compliant // window.getComputedStyle, since it returns css property values in their original unit: // If you set an elements width to "50%", window.getComputedStyle will give you it's current width in px while currentStyle // gives you the original "50%". // Opera supports both, currentStyle and window.getComputedStyle, that's why checking for currentStyle should have higher prio if (currentStyle) { try { return currentStyle[camelizedProperty]; } catch(e) { //ie will occasionally fail for unknown reasons. swallowing exception } } var win = doc.defaultView || doc.parentWindow, needsOverflowReset = (property === "height" || property === "width") && element.nodeName === "TEXTAREA", originalOverflow, returnValue; if (win.getComputedStyle) { // Chrome and Safari both calculate a wrong width and height for textareas when they have scroll bars // therfore we remove and restore the scrollbar and calculate the value in between if (needsOverflowReset) { originalOverflow = style.overflow; style.overflow = "hidden"; } returnValue = win.getComputedStyle(element, null).getPropertyValue(property); if (needsOverflowReset) { style.overflow = originalOverflow || ""; } return returnValue; } } }; }; })(); ;wysihtml5.dom.getTextNodes = function(node, ingoreEmpty){ var all = []; for (node=node.firstChild;node;node=node.nextSibling){ if (node.nodeType == 3) { if (!ingoreEmpty || !(/^\s*$/).test(node.innerText || node.textContent)) { all.push(node); } } else { all = all.concat(wysihtml5.dom.getTextNodes(node, ingoreEmpty)); } } return all; }; ;/** * High performant way to check whether an element with a specific tag name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithTagName(document, "IMG"); */ wysihtml5.dom.hasElementWithTagName = (function() { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } return function(doc, tagName) { var key = _getDocumentIdentifier(doc) + ":" + tagName, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByTagName(tagName); } return cacheEntry.length > 0; }; })(); ;/** * High performant way to check whether an element with a specific class name is in the given document * Optimized for being heavily executed * Unleashes the power of live node lists * * @param {Object} doc The document object of the context where to check * @param {String} tagName Upper cased tag name * @example * wysihtml5.dom.hasElementWithClassName(document, "foobar"); */ (function(wysihtml5) { var LIVE_CACHE = {}, DOCUMENT_IDENTIFIER = 1; function _getDocumentIdentifier(doc) { return doc._wysihtml5_identifier || (doc._wysihtml5_identifier = DOCUMENT_IDENTIFIER++); } wysihtml5.dom.hasElementWithClassName = function(doc, className) { // getElementsByClassName is not supported by IE<9 // but is sometimes mocked via library code (which then doesn't return live node lists) if (!wysihtml5.browser.supportsNativeGetElementsByClassName()) { return !!doc.querySelector("." + className); } var key = _getDocumentIdentifier(doc) + ":" + className, cacheEntry = LIVE_CACHE[key]; if (!cacheEntry) { cacheEntry = LIVE_CACHE[key] = doc.getElementsByClassName(className); } return cacheEntry.length > 0; }; })(wysihtml5); ;wysihtml5.dom.insert = function(elementToInsert) { return { after: function(element) { element.parentNode.insertBefore(elementToInsert, element.nextSibling); }, before: function(element) { element.parentNode.insertBefore(elementToInsert, element); }, into: function(element) { element.appendChild(elementToInsert); } }; }; ;wysihtml5.dom.insertCSS = function(rules) { rules = rules.join("\n"); return { into: function(doc) { var styleElement = doc.createElement("style"); styleElement.type = "text/css"; if (styleElement.styleSheet) { styleElement.styleSheet.cssText = rules; } else { styleElement.appendChild(doc.createTextNode(rules)); } var link = doc.querySelector("head link"); if (link) { link.parentNode.insertBefore(styleElement, link); return; } else { var head = doc.querySelector("head"); if (head) { head.appendChild(styleElement); } } } }; }; ;// TODO: Refactor dom tree traversing here (function(wysihtml5) { wysihtml5.dom.lineBreaks = function(node) { function _isLineBreak(n) { return n.nodeName === "BR"; } /** * Checks whether the elment causes a visual line break * (<br> or block elements) */ function _isLineBreakOrBlockElement(element) { if (_isLineBreak(element)) { return true; } if (wysihtml5.dom.getStyle("display").from(element) === "block") { return true; } return false; } return { /* wysihtml5.dom.lineBreaks(element).add(); * * Adds line breaks before and after the given node if the previous and next siblings * aren't already causing a visual line break (block element or <br>) */ add: function(options) { var doc = node.ownerDocument, nextSibling = wysihtml5.dom.domNode(node).next({ignoreBlankTexts: true}), previousSibling = wysihtml5.dom.domNode(node).prev({ignoreBlankTexts: true}); if (nextSibling && !_isLineBreakOrBlockElement(nextSibling)) { wysihtml5.dom.insert(doc.createElement("br")).after(node); } if (previousSibling && !_isLineBreakOrBlockElement(previousSibling)) { wysihtml5.dom.insert(doc.createElement("br")).before(node); } }, /* wysihtml5.dom.lineBreaks(element).remove(); * * Removes line breaks before and after the given node */ remove: function(options) { var nextSibling = wysihtml5.dom.domNode(node).next({ignoreBlankTexts: true}), previousSibling = wysihtml5.dom.domNode(node).prev({ignoreBlankTexts: true}); if (nextSibling && _isLineBreak(nextSibling)) { nextSibling.parentNode.removeChild(nextSibling); } if (previousSibling && _isLineBreak(previousSibling)) { previousSibling.parentNode.removeChild(previousSibling); } } }; }; })(wysihtml5);;/** * Method to set dom events * * @example * wysihtml5.dom.observe(iframe.contentWindow.document.body, ["focus", "blur"], function() { ... }); */ wysihtml5.dom.observe = function(element, eventNames, handler) { eventNames = typeof(eventNames) === "string" ? [eventNames] : eventNames; var handlerWrapper, eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.addEventListener) { element.addEventListener(eventName, handler, false); } else { handlerWrapper = function(event) { if (!("target" in event)) { event.target = event.srcElement; } event.preventDefault = event.preventDefault || function() { this.returnValue = false; }; event.stopPropagation = event.stopPropagation || function() { this.cancelBubble = true; }; handler.call(element, event); }; element.attachEvent("on" + eventName, handlerWrapper); } } return { stop: function() { var eventName, i = 0, length = eventNames.length; for (; i<length; i++) { eventName = eventNames[i]; if (element.removeEventListener) { element.removeEventListener(eventName, handler, false); } else { element.detachEvent("on" + eventName, handlerWrapper); } } } }; }; ;/** * HTML Sanitizer * Rewrites the HTML based on given rules * * @param {Element|String} elementOrHtml HTML String to be sanitized OR element whose content should be sanitized * @param {Object} [rules] List of rules for rewriting the HTML, if there's no rule for an element it will * be converted to a "span". Each rule is a key/value pair where key is the tag to convert, and value the * desired substitution. * @param {Object} context Document object in which to parse the html, needed to sandbox the parsing * * @return {Element|String} Depends on the elementOrHtml parameter. When html then the sanitized html as string elsewise the element. * * @example * var userHTML = '<div id="foo" onclick="alert(1);"><p><font color="red">foo</font><script>alert(1);</script></p></div>'; * wysihtml5.dom.parse(userHTML, { * tags { * p: "div", // Rename p tags to div tags * font: "span" // Rename font tags to span tags * div: true, // Keep them, also possible (same result when passing: "div" or true) * script: undefined // Remove script elements * } * }); * // => <div><div><span>foo bar</span></div></div> * * var userHTML = '<table><tbody><tr><td>I'm a table!</td></tr></tbody></table>'; * wysihtml5.dom.parse(userHTML); * // => '<span><span><span><span>I'm a table!</span></span></span></span>' * * var userHTML = '<div>foobar<br>foobar</div>'; * wysihtml5.dom.parse(userHTML, { * tags: { * div: undefined, * br: true * } * }); * // => '' * * var userHTML = '<div class="red">foo</div><div class="pink">bar</div>'; * wysihtml5.dom.parse(userHTML, { * classes: { * red: 1, * green: 1 * }, * tags: { * div: { * rename_tag: "p" * } * } * }); * // => '<p class="red">foo</p><p>bar</p>' */ wysihtml5.dom.parse = function(elementOrHtml_current, config_current) { /* TODO: Currently escaped module pattern as otherwise folloowing default swill be shared among multiple editors. * Refactor whole code as this method while workind is kind of awkward too */ /** * It's not possible to use a XMLParser/DOMParser as HTML5 is not always well-formed XML * new DOMParser().parseFromString('<img src="foo.gif">') will cause a parseError since the * node isn't closed * * Therefore we've to use the browser's ordinary HTML parser invoked by setting innerHTML. */ var NODE_TYPE_MAPPING = { "1": _handleElement, "3": _handleText, "8": _handleComment }, // Rename unknown tags to this DEFAULT_NODE_NAME = "span", WHITE_SPACE_REG_EXP = /\s+/, defaultRules = { tags: {}, classes: {} }, currentRules = {}, blockElements = ["ADDRESS" ,"BLOCKQUOTE" ,"CENTER" ,"DIR" ,"DIV" ,"DL" ,"FIELDSET" , "FORM", "H1" ,"H2" ,"H3" ,"H4" ,"H5" ,"H6" ,"ISINDEX" ,"MENU", "NOFRAMES", "NOSCRIPT" ,"OL" ,"P" ,"PRE","TABLE", "UL"]; /** * Iterates over all childs of the element, recreates them, appends them into a document fragment * which later replaces the entire body content */ function parse(elementOrHtml, config) { wysihtml5.lang.object(currentRules).merge(defaultRules).merge(config.rules).get(); var context = config.context || elementOrHtml.ownerDocument || document, fragment = context.createDocumentFragment(), isString = typeof(elementOrHtml) === "string", clearInternals = false, element, newNode, firstChild; if (config.clearInternals === true) { clearInternals = true; } if (isString) { element = wysihtml5.dom.getAsDom(elementOrHtml, context); } else { element = elementOrHtml; } if (currentRules.selectors) { _applySelectorRules(element, currentRules.selectors); } while (element.firstChild) { firstChild = element.firstChild; newNode = _convert(firstChild, config.cleanUp, clearInternals, config.uneditableClass); if (newNode) { fragment.appendChild(newNode); } if (firstChild !== newNode) { element.removeChild(firstChild); } } if (config.unjoinNbsps) { // replace joined non-breakable spaces with unjoined var txtnodes = wysihtml5.dom.getTextNodes(fragment); for (var n = txtnodes.length; n--;) { txtnodes[n].nodeValue = txtnodes[n].nodeValue.replace(/([\S\u00A0])\u00A0/gi, "$1 "); } } // Clear element contents element.innerHTML = ""; // Insert new DOM tree element.appendChild(fragment); return isString ? wysihtml5.quirks.getCorrectInnerHTML(element) : element; } function _convert(oldNode, cleanUp, clearInternals, uneditableClass) { var oldNodeType = oldNode.nodeType, oldChilds = oldNode.childNodes, oldChildsLength = oldChilds.length, method = NODE_TYPE_MAPPING[oldNodeType], i = 0, fragment, newNode, newChild, nodeDisplay; // Passes directly elemets with uneditable class if (uneditableClass && oldNodeType === 1 && wysihtml5.dom.hasClass(oldNode, uneditableClass)) { return oldNode; } newNode = method && method(oldNode, clearInternals); // Remove or unwrap node in case of return value null or false if (!newNode) { if (newNode === false) { // false defines that tag should be removed but contents should remain (unwrap) fragment = oldNode.ownerDocument.createDocumentFragment(); for (i = oldChildsLength; i--;) { if (oldChilds[i]) { newChild = _convert(oldChilds[i], cleanUp, clearInternals, uneditableClass); if (newChild) { if (oldChilds[i] === newChild) { i--; } fragment.insertBefore(newChild, fragment.firstChild); } } } nodeDisplay = wysihtml5.dom.getStyle("display").from(oldNode); if (nodeDisplay === '') { // Handle display style when element not in dom nodeDisplay = wysihtml5.lang.array(blockElements).contains(oldNode.tagName) ? "block" : ""; } if (wysihtml5.lang.array(["block", "flex", "table"]).contains(nodeDisplay)) { fragment.appendChild(oldNode.ownerDocument.createElement("br")); } // TODO: try to minimize surplus spaces if (wysihtml5.lang.array([ "div", "pre", "p", "table", "td", "th", "ul", "ol", "li", "dd", "dl", "footer", "header", "section", "h1", "h2", "h3", "h4", "h5", "h6" ]).contains(oldNode.nodeName.toLowerCase()) && oldNode.parentNode.lastChild !== oldNode) { // add space at first when unwraping non-textflow elements if (!oldNode.nextSibling || oldNode.nextSibling.nodeType !== 3 || !(/^\s/).test(oldNode.nextSibling.nodeValue)) { fragment.appendChild(oldNode.ownerDocument.createTextNode(" ")); } } if (fragment.normalize) { fragment.normalize(); } return fragment; } else { // Remove return null; } } // Converts all childnodes for (i=0; i<oldChildsLength; i++) { if (oldChilds[i]) { newChild = _convert(oldChilds[i], cleanUp, clearInternals, uneditableClass); if (newChild) { if (oldChilds[i] === newChild) { i--; } newNode.appendChild(newChild); } } } // Cleanup senseless <span> elements if (cleanUp && newNode.nodeName.toLowerCase() === DEFAULT_NODE_NAME && (!newNode.childNodes.length || ((/^\s*$/gi).test(newNode.innerHTML) && (clearInternals || (oldNode.className !== "_wysihtml5-temp-placeholder" && oldNode.className !== "rangySelectionBoundary"))) || !newNode.attributes.length) ) { fragment = newNode.ownerDocument.createDocumentFragment(); while (newNode.firstChild) { fragment.appendChild(newNode.firstChild); } if (fragment.normalize) { fragment.normalize(); } return fragment; } if (newNode.normalize) { newNode.normalize(); } return newNode; } function _applySelectorRules (element, selectorRules) { var sel, method, els; for (sel in selectorRules) { if (selectorRules.hasOwnProperty(sel)) { if (wysihtml5.lang.object(selectorRules[sel]).isFunction()) { method = selectorRules[sel]; } else if (typeof(selectorRules[sel]) === "string" && elementHandlingMethods[selectorRules[sel]]) { method = elementHandlingMethods[selectorRules[sel]]; } els = element.querySelectorAll(sel); for (var i = els.length; i--;) { method(els[i]); } } } } function _handleElement(oldNode, clearInternals) { var rule, newNode, tagRules = currentRules.tags, nodeName = oldNode.nodeName.toLowerCase(), scopeName = oldNode.scopeName, renameTag; /** * We already parsed that element * ignore it! (yes, this sometimes happens in IE8 when the html is invalid) */ if (oldNode._wysihtml5) { return null; } oldNode._wysihtml5 = 1; if (oldNode.className === "wysihtml5-temp") { return null; } /** * IE is the only browser who doesn't include the namespace in the * nodeName, that's why we have to prepend it by ourselves * scopeName is a proprietary IE feature * read more here http://msdn.microsoft.com/en-us/library/ms534388(v=vs.85).aspx */ if (scopeName && scopeName != "HTML") { nodeName = scopeName + ":" + nodeName; } /** * Repair node * IE is a bit bitchy when it comes to invalid nested markup which includes unclosed tags * A <p> doesn't need to be closed according HTML4-5 spec, we simply replace it with a <div> to preserve its content and layout */ if ("outerHTML" in oldNode) { if (!wysihtml5.browser.autoClosesUnclosedTags() && oldNode.nodeName === "P" && oldNode.outerHTML.slice(-4).toLowerCase() !== "</p>") { nodeName = "div"; } } if (nodeName in tagRules) { rule = tagRules[nodeName]; if (!rule || rule.remove) { return null; } else if (rule.unwrap) { return false; } rule = typeof(rule) === "string" ? { rename_tag: rule } : rule; } else if (oldNode.firstChild) { rule = { rename_tag: DEFAULT_NODE_NAME }; } else { // Remove empty unknown elements return null; } // tests if type condition is met or node should be removed/unwrapped/renamed if (rule.one_of_type && !_testTypes(oldNode, currentRules, rule.one_of_type, clearInternals)) { if (rule.remove_action) { if (rule.remove_action === "unwrap") { return false; } else if (rule.remove_action === "rename") { renameTag = rule.remove_action_rename_to || DEFAULT_NODE_NAME; } else { return null; } } else { return null; } } newNode = oldNode.ownerDocument.createElement(renameTag || rule.rename_tag || nodeName); _handleAttributes(oldNode, newNode, rule, clearInternals); _handleStyles(oldNode, newNode, rule); oldNode = null; if (newNode.normalize) { newNode.normalize(); } return newNode; } function _testTypes(oldNode, rules, types, clearInternals) { var definition, type; // do not interfere with placeholder span or pasting caret position is not maintained if (oldNode.nodeName === "SPAN" && !clearInternals && (oldNode.className === "_wysihtml5-temp-placeholder" || oldNode.className === "rangySelectionBoundary")) { return true; } for (type in types) { if (types.hasOwnProperty(type) && rules.type_definitions && rules.type_definitions[type]) { definition = rules.type_definitions[type]; if (_testType(oldNode, definition)) { return true; } } } return false; } function array_contains(a, obj) { var i = a.length; while (i--) { if (a[i] === obj) { return true; } } return false; } function _testType(oldNode, definition) { var nodeClasses = oldNode.getAttribute("class"), nodeStyles = oldNode.getAttribute("style"), classesLength, s, s_corrected, a, attr, currentClass, styleProp; // test for methods if (definition.methods) { for (var m in definition.methods) { if (definition.methods.hasOwnProperty(m) && typeCeckMethods[m]) { if (typeCeckMethods[m](oldNode)) { return true; } } } } // test for classes, if one found return true if (nodeClasses && definition.classes) { nodeClasses = nodeClasses.replace(/^\s+/g, '').replace(/\s+$/g, '').split(WHITE_SPACE_REG_EXP); classesLength = nodeClasses.length; for (var i = 0; i < classesLength; i++) { if (definition.classes[nodeClasses[i]]) { return true; } } } // test for styles, if one found return true if (nodeStyles && definition.styles) { nodeStyles = nodeStyles.split(';'); for (s in definition.styles) { if (definition.styles.hasOwnProperty(s)) { for (var sp = nodeStyles.length; sp--;) { styleProp = nodeStyles[sp].split(':'); if (styleProp[0].replace(/\s/g, '').toLowerCase() === s) { if (definition.styles[s] === true || definition.styles[s] === 1 || wysihtml5.lang.array(definition.styles[s]).contains(styleProp[1].replace(/\s/g, '').toLowerCase()) ) { return true; } } } } } } // test for attributes in general against regex match if (definition.attrs) { for (a in definition.attrs) { if (definition.attrs.hasOwnProperty(a)) { attr = wysihtml5.dom.getAttribute(oldNode, a); if (typeof(attr) === "string") { if (attr.search(definition.attrs[a]) > -1) { return true; } } } } } return false; } function _handleStyles(oldNode, newNode, rule) { var s, v; if(rule && rule.keep_styles) { for (s in rule.keep_styles) { if (rule.keep_styles.hasOwnProperty(s)) { v = (s === "float") ? oldNode.style.styleFloat || oldNode.style.cssFloat : oldNode.style[s]; // value can be regex and if so should match or style skipped if (rule.keep_styles[s] instanceof RegExp && !(rule.keep_styles[s].test(v))) { continue; } if (s === "float") { // IE compability newNode.style[(oldNode.style.styleFloat) ? 'styleFloat': 'cssFloat'] = v; } else if (oldNode.style[s]) { newNode.style[s] = v; } } } } }; function _getAttributesBeginningWith(beginning, attributes) { var returnAttributes = []; for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr.indexOf(beginning) === 0) { returnAttributes.push(attr); } } return returnAttributes; } function _checkAttribute(attributeName, attributeValue, methodName, nodeName) { var method = wysihtml5.lang.object(methodName).isFunction() ? methodName : attributeCheckMethods[methodName], newAttributeValue; if (method) { newAttributeValue = method(attributeValue, nodeName); if (typeof(newAttributeValue) === "string") { return newAttributeValue; } } return false; } function _checkAttributes(oldNode, local_attributes) { var globalAttributes = wysihtml5.lang.object(currentRules.attributes || {}).clone(), // global values for check/convert values of attributes checkAttributes = wysihtml5.lang.object(globalAttributes).merge( wysihtml5.lang.object(local_attributes || {}).clone()).get(), attributes = {}, oldAttributes = wysihtml5.dom.getAttributes(oldNode), attributeName, newValue, matchingAttributes; for (attributeName in checkAttributes) { if ((/\*$/).test(attributeName)) { matchingAttributes = _getAttributesBeginningWith(attributeName.slice(0,-1), oldAttributes); for (var i = 0, imax = matchingAttributes.length; i < imax; i++) { newValue = _checkAttribute(matchingAttributes[i], oldAttributes[matchingAttributes[i]], checkAttributes[attributeName], oldNode.nodeName); if (newValue !== false) { attributes[matchingAttributes[i]] = newValue; } } } else { newValue = _checkAttribute(attributeName, oldAttributes[attributeName], checkAttributes[attributeName], oldNode.nodeName); if (newValue !== false) { attributes[attributeName] = newValue; } } } return attributes; } // TODO: refactor. Too long to read function _handleAttributes(oldNode, newNode, rule, clearInternals) { var attributes = {}, // fresh new set of attributes to set on newNode setClass = rule.set_class, // classes to set addClass = rule.add_class, // add classes based on existing attributes addStyle = rule.add_style, // add styles based on existing attributes setAttributes = rule.set_attributes, // attributes to set on the current node allowedClasses = currentRules.classes, i = 0, classes = [], styles = [], newClasses = [], oldClasses = [], classesLength, newClassesLength, currentClass, newClass, attributeName, method; if (setAttributes) { attributes = wysihtml5.lang.object(setAttributes).clone(); } // check/convert values of attributes attributes = wysihtml5.lang.object(attributes).merge(_checkAttributes(oldNode, rule.check_attributes)).get(); if (setClass) { classes.push(setClass); } if (addClass) { for (attributeName in addClass) { method = addClassMethods[addClass[attributeName]]; if (!method) { continue; } newClass = method(wysihtml5.dom.getAttribute(oldNode, attributeName)); if (typeof(newClass) === "string") { classes.push(newClass); } } } if (addStyle) { for (attributeName in addStyle) { method = addStyleMethods[addStyle[attributeName]]; if (!method) { continue; } newStyle = method(wysihtml5.dom.getAttribute(oldNode, attributeName)); if (typeof(newStyle) === "string") { styles.push(newStyle); } } } if (typeof(allowedClasses) === "string" && allowedClasses === "any" && oldNode.getAttribute("class")) { if (currentRules.classes_blacklist) { oldClasses = oldNode.getAttribute("class"); if (oldClasses) { classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP)); } classesLength = classes.length; for (; i<classesLength; i++) { currentClass = classes[i]; if (!currentRules.classes_blacklist[currentClass]) { newClasses.push(currentClass); } } if (newClasses.length) { attributes["class"] = wysihtml5.lang.array(newClasses).unique().join(" "); } } else { attributes["class"] = oldNode.getAttribute("class"); } } else { // make sure that wysihtml5 temp class doesn't get stripped out if (!clearInternals) { allowedClasses["_wysihtml5-temp-placeholder"] = 1; allowedClasses["_rangySelectionBoundary"] = 1; allowedClasses["wysiwyg-tmp-selected-cell"] = 1; } // add old classes last oldClasses = oldNode.getAttribute("class"); if (oldClasses) { classes = classes.concat(oldClasses.split(WHITE_SPACE_REG_EXP)); } classesLength = classes.length; for (; i<classesLength; i++) { currentClass = classes[i]; if (allowedClasses[currentClass]) { newClasses.push(currentClass); } } if (newClasses.length) { attributes["class"] = wysihtml5.lang.array(newClasses).unique().join(" "); } } // remove table selection class if present if (attributes["class"] && clearInternals) { attributes["class"] = attributes["class"].replace("wysiwyg-tmp-selected-cell", ""); if ((/^\s*$/g).test(attributes["class"])) { delete attributes["class"]; } } if (styles.length) { attributes["style"] = wysihtml5.lang.array(styles).unique().join(" "); } // set attributes on newNode for (attributeName in attributes) { // Setting attributes can cause a js error in IE under certain circumstances // eg. on a <img> under https when it's new attribute value is non-https // TODO: Investigate this further and check for smarter handling try { newNode.setAttribute(attributeName, attributes[attributeName]); } catch(e) {} } // IE8 sometimes loses the width/height attributes when those are set before the "src" // so we make sure to set them again if (attributes.src) { if (typeof(attributes.width) !== "undefined") { newNode.setAttribute("width", attributes.width); } if (typeof(attributes.height) !== "undefined") { newNode.setAttribute("height", attributes.height); } } } function _handleText(oldNode) { var nextSibling = oldNode.nextSibling; if (nextSibling && nextSibling.nodeType === wysihtml5.TEXT_NODE) { // Concatenate text nodes nextSibling.data = oldNode.data.replace(wysihtml5.INVISIBLE_SPACE_REG_EXP, "") + nextSibling.data.replace(wysihtml5.INVISIBLE_SPACE_REG_EXP, ""); } else { // \uFEFF = wysihtml5.INVISIBLE_SPACE (used as a hack in certain rich text editing situations) var data = oldNode.data.replace(wysihtml5.INVISIBLE_SPACE_REG_EXP, ""); return oldNode.ownerDocument.createTextNode(data); } } function _handleComment(oldNode) { if (currentRules.comments) { return oldNode.ownerDocument.createComment(oldNode.nodeValue); } } // ------------ attribute checks ------------ \\ var attributeCheckMethods = { url: (function() { var REG_EXP = /^https?:\/\//i; return function(attributeValue) { if (!attributeValue || !attributeValue.match(REG_EXP)) { return null; } return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); }); }; })(), src: (function() { var REG_EXP = /^(\/|https?:\/\/)/i; return function(attributeValue) { if (!attributeValue || !attributeValue.match(REG_EXP)) { return null; } return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); }); }; })(), href: (function() { var REG_EXP = /^(#|\/|https?:\/\/|mailto:|tel:)/i; return function(attributeValue) { if (!attributeValue || !attributeValue.match(REG_EXP)) { return null; } return attributeValue.replace(REG_EXP, function(match) { return match.toLowerCase(); }); }; })(), alt: (function() { var REG_EXP = /[^ a-z0-9_\-]/gi; return function(attributeValue, nodeName) { if (!attributeValue) { if (nodeName === "IMG") { return ""; } else { return null; } } return attributeValue.replace(REG_EXP, ""); }; })(), // Integers. Does not work with floating point numbers and units numbers: (function() { var REG_EXP = /\D/g; return function(attributeValue) { attributeValue = (attributeValue || "").replace(REG_EXP, ""); return attributeValue || null; }; })(), // Useful for with/height attributes where floating points and percentages are allowed dimension: (function() { var REG_EXP = /\D*(\d+)(\.\d+)?\s?(%)?\D*/; return function(attributeValue) { attributeValue = (attributeValue || "").replace(REG_EXP, "$1$2$3"); return attributeValue || null; }; })(), any: (function() { return function(attributeValue) { if (!attributeValue) { return null; } return attributeValue; }; })() }; // ------------ style converter (converts an html attribute to a style) ------------ \\ var addStyleMethods = { align_text: (function() { var mapping = { left: "text-align: left;", right: "text-align: right;", center: "text-align: center;" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), }; // ------------ class converter (converts an html attribute to a class name) ------------ \\ var addClassMethods = { align_img: (function() { var mapping = { left: "wysiwyg-float-left", right: "wysiwyg-float-right" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), align_text: (function() { var mapping = { left: "wysiwyg-text-align-left", right: "wysiwyg-text-align-right", center: "wysiwyg-text-align-center", justify: "wysiwyg-text-align-justify" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), clear_br: (function() { var mapping = { left: "wysiwyg-clear-left", right: "wysiwyg-clear-right", both: "wysiwyg-clear-both", all: "wysiwyg-clear-both" }; return function(attributeValue) { return mapping[String(attributeValue).toLowerCase()]; }; })(), size_font: (function() { var mapping = { "1": "wysiwyg-font-size-xx-small", "2": "wysiwyg-font-size-small", "3": "wysiwyg-font-size-medium", "4": "wysiwyg-font-size-large", "5": "wysiwyg-font-size-x-large", "6": "wysiwyg-font-size-xx-large", "7": "wysiwyg-font-size-xx-large", "-": "wysiwyg-font-size-smaller", "+": "wysiwyg-font-size-larger" }; return function(attributeValue) { return mapping[String(attributeValue).charAt(0)]; }; })() }; // checks if element is possibly visible var typeCeckMethods = { has_visible_contet: (function() { var txt, isVisible = false, visibleElements = ['img', 'video', 'picture', 'br', 'script', 'noscript', 'style', 'table', 'iframe', 'object', 'embed', 'audio', 'svg', 'input', 'button', 'select','textarea', 'canvas']; return function(el) { // has visible innertext. so is visible txt = (el.innerText || el.textContent).replace(/\s/g, ''); if (txt && txt.length > 0) { return true; } // matches list of visible dimensioned elements for (var i = visibleElements.length; i--;) { if (el.querySelector(visibleElements[i])) { return true; } } // try to measure dimesions in last resort. (can find only of elements in dom) if (el.offsetWidth && el.offsetWidth > 0 && el.offsetHeight && el.offsetHeight > 0) { return true; } return false; }; })() }; var elementHandlingMethods = { unwrap: function (element) { wysihtml5.dom.unwrap(element); }, remove: function (element) { element.parentNode.removeChild(element); } }; return parse(elementOrHtml_current, config_current); }; ;/** * Checks for empty text node childs and removes them * * @param {Element} node The element in which to cleanup * @example * wysihtml5.dom.removeEmptyTextNodes(element); */ wysihtml5.dom.removeEmptyTextNodes = function(node) { var childNode, childNodes = wysihtml5.lang.array(node.childNodes).get(), childNodesLength = childNodes.length, i = 0; for (; i<childNodesLength; i++) { childNode = childNodes[i]; if (childNode.nodeType === wysihtml5.TEXT_NODE && (/^[\n\r]*$/).test(childNode.data)) { childNode.parentNode.removeChild(childNode); } } }; ;/** * Renames an element (eg. a <div> to a <p>) and keeps its childs * * @param {Element} element The list element which should be renamed * @param {Element} newNodeName The desired tag name * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.renameElement(document.getElementById("list"), "ol"); * </script> * * <!-- Will result in: --> * <ol> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ol> */ wysihtml5.dom.renameElement = function(element, newNodeName) { var newElement = element.ownerDocument.createElement(newNodeName), firstChild; while (firstChild = element.firstChild) { newElement.appendChild(firstChild); } wysihtml5.dom.copyAttributes(["align", "className"]).from(element).to(newElement); if (element.parentNode) { element.parentNode.replaceChild(newElement, element); } return newElement; }; ;/** * Takes an element, removes it and replaces it with it's childs * * @param {Object} node The node which to replace with it's child nodes * @example * <div id="foo"> * <span>hello</span> * </div> * <script> * // Remove #foo and replace with it's children * wysihtml5.dom.replaceWithChildNodes(document.getElementById("foo")); * </script> */ wysihtml5.dom.replaceWithChildNodes = function(node) { if (!node.parentNode) { return; } if (!node.firstChild) { node.parentNode.removeChild(node); return; } var fragment = node.ownerDocument.createDocumentFragment(); while (node.firstChild) { fragment.appendChild(node.firstChild); } node.parentNode.replaceChild(fragment, node); node = fragment = null; }; ;/** * Unwraps an unordered/ordered list * * @param {Element} element The list element which should be unwrapped * * @example * <!-- Assume the following dom: --> * <ul id="list"> * <li>eminem</li> * <li>dr. dre</li> * <li>50 Cent</li> * </ul> * * <script> * wysihtml5.dom.resolveList(document.getElementById("list")); * </script> * * <!-- Will result in: --> * eminem<br> * dr. dre<br> * 50 Cent<br> */ (function(dom) { function _isBlockElement(node) { return dom.getStyle("display").from(node) === "block"; } function _isLineBreak(node) { return node.nodeName === "BR"; } function _appendLineBreak(element) { var lineBreak = element.ownerDocument.createElement("br"); element.appendChild(lineBreak); } function resolveList(list, useLineBreaks) { if (!list.nodeName.match(/^(MENU|UL|OL)$/)) { return; } var doc = list.ownerDocument, fragment = doc.createDocumentFragment(), previousSibling = wysihtml5.dom.domNode(list).prev({ignoreBlankTexts: true}), nextSibling = wysihtml5.dom.domNode(list).next({ignoreBlankTexts: true}), firstChild, lastChild, isLastChild, shouldAppendLineBreak, paragraph, listItem, lastListItem = list.lastElementChild || list.lastChild, isLastItem; if (useLineBreaks) { // Insert line break if list is after a non-block element if (previousSibling && !_isBlockElement(previousSibling) && !_isLineBreak(previousSibling)) { _appendLineBreak(fragment); } while (listItem = (list.firstElementChild || list.firstChild)) { lastChild = listItem.lastChild; isLastItem = listItem === lastListItem; while (firstChild = listItem.firstChild) { isLastChild = firstChild === lastChild; // This needs to be done before appending it to the fragment, as it otherwise will lose style information shouldAppendLineBreak = (!isLastItem || (nextSibling && !_isBlockElement(nextSibling))) && isLastChild && !_isBlockElement(firstChild) && !_isLineBreak(firstChild); fragment.appendChild(firstChild); if (shouldAppendLineBreak) { _appendLineBreak(fragment); } } listItem.parentNode.removeChild(listItem); } } else { while (listItem = (list.firstElementChild || list.firstChild)) { if (listItem.querySelector && listItem.querySelector("div, p, ul, ol, menu, blockquote, h1, h2, h3, h4, h5, h6")) { while (firstChild = listItem.firstChild) { fragment.appendChild(firstChild); } } else { paragraph = doc.createElement("p"); while (firstChild = listItem.firstChild) { paragraph.appendChild(firstChild); } fragment.appendChild(paragraph); } listItem.parentNode.removeChild(listItem); } } list.parentNode.replaceChild(fragment, list); } dom.resolveList = resolveList; })(wysihtml5.dom); ;/** * Sandbox for executing javascript, parsing css styles and doing dom operations in a secure way * * Browser Compatibility: * - Secure in MSIE 6+, but only when the user hasn't made changes to his security level "restricted" * - Partially secure in other browsers (Firefox, Opera, Safari, Chrome, ...) * * Please note that this class can't benefit from the HTML5 sandbox attribute for the following reasons: * - sandboxing doesn't work correctly with inlined content (src="javascript:'<html>...</html>'") * - sandboxing of physical documents causes that the dom isn't accessible anymore from the outside (iframe.contentWindow, ...) * - setting the "allow-same-origin" flag would fix that, but then still javascript and dom events refuse to fire * - therefore the "allow-scripts" flag is needed, which then would deactivate any security, as the js executed inside the iframe * can do anything as if the sandbox attribute wasn't set * * @param {Function} [readyCallback] Method that gets invoked when the sandbox is ready * @param {Object} [config] Optional parameters * * @example * new wysihtml5.dom.Sandbox(function(sandbox) { * sandbox.getWindow().document.body.innerHTML = '<img src=foo.gif onerror="alert(document.cookie)">'; * }); */ (function(wysihtml5) { var /** * Default configuration */ doc = document, /** * Properties to unset/protect on the window object */ windowProperties = [ "parent", "top", "opener", "frameElement", "frames", "localStorage", "globalStorage", "sessionStorage", "indexedDB" ], /** * Properties on the window object which are set to an empty function */ windowProperties2 = [ "open", "close", "openDialog", "showModalDialog", "alert", "confirm", "prompt", "openDatabase", "postMessage", "XMLHttpRequest", "XDomainRequest" ], /** * Properties to unset/protect on the document object */ documentProperties = [ "referrer", "write", "open", "close" ]; wysihtml5.dom.Sandbox = Base.extend( /** @scope wysihtml5.dom.Sandbox.prototype */ { constructor: function(readyCallback, config) { this.callback = readyCallback || wysihtml5.EMPTY_FUNCTION; this.config = wysihtml5.lang.object({}).merge(config).get(); if (!this.config.className) { this.config.className = "wysihtml5-sandbox"; } this.editableArea = this._createIframe(); }, insertInto: function(element) { if (typeof(element) === "string") { element = doc.getElementById(element); } element.appendChild(this.editableArea); }, getIframe: function() { return this.editableArea; }, getWindow: function() { this._readyError(); }, getDocument: function() { this._readyError(); }, destroy: function() { var iframe = this.getIframe(); iframe.parentNode.removeChild(iframe); }, _readyError: function() { throw new Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet"); }, /** * Creates the sandbox iframe * * Some important notes: * - We can't use HTML5 sandbox for now: * setting it causes that the iframe's dom can't be accessed from the outside * Therefore we need to set the "allow-same-origin" flag which enables accessing the iframe's dom * But then there's another problem, DOM events (focus, blur, change, keypress, ...) aren't fired. * In order to make this happen we need to set the "allow-scripts" flag. * A combination of allow-scripts and allow-same-origin is almost the same as setting no sandbox attribute at all. * - Chrome & Safari, doesn't seem to support sandboxing correctly when the iframe's html is inlined (no physical document) * - IE needs to have the security="restricted" attribute set before the iframe is * inserted into the dom tree * - Believe it or not but in IE "security" in document.createElement("iframe") is false, even * though it supports it * - When an iframe has security="restricted", in IE eval() & execScript() don't work anymore * - IE doesn't fire the onload event when the content is inlined in the src attribute, therefore we rely * on the onreadystatechange event */ _createIframe: function() { var that = this, iframe = doc.createElement("iframe"); iframe.className = this.config.className; wysihtml5.dom.setAttributes({ "security": "restricted", "allowtransparency": "true", "frameborder": 0, "width": 0, "height": 0, "marginwidth": 0, "marginheight": 0 }).on(iframe); // Setting the src like this prevents ssl warnings in IE6 if (wysihtml5.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()) { iframe.src = "javascript:'<html></html>'"; } iframe.onload = function() { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); }; iframe.onreadystatechange = function() { if (/loaded|complete/.test(iframe.readyState)) { iframe.onreadystatechange = iframe.onload = null; that._onLoadIframe(iframe); } }; return iframe; }, /** * Callback for when the iframe has finished loading */ _onLoadIframe: function(iframe) { // don't resume when the iframe got unloaded (eg. by removing it from the dom) if (!wysihtml5.dom.contains(doc.documentElement, iframe)) { return; } var that = this, iframeWindow = iframe.contentWindow, iframeDocument = iframe.contentWindow.document, charset = doc.characterSet || doc.charset || "utf-8", sandboxHtml = this._getHtml({ charset: charset, stylesheets: this.config.stylesheets }); // Create the basic dom tree including proper DOCTYPE and charset iframeDocument.open("text/html", "replace"); iframeDocument.write(sandboxHtml); iframeDocument.close(); this.getWindow = function() { return iframe.contentWindow; }; this.getDocument = function() { return iframe.contentWindow.document; }; // Catch js errors and pass them to the parent's onerror event // addEventListener("error") doesn't work properly in some browsers // TODO: apparently this doesn't work in IE9! iframeWindow.onerror = function(errorMessage, fileName, lineNumber) { throw new Error("wysihtml5.Sandbox: " + errorMessage, fileName, lineNumber); }; if (!wysihtml5.browser.supportsSandboxedIframes()) { // Unset a bunch of sensitive variables // Please note: This isn't hack safe! // It more or less just takes care of basic attacks and prevents accidental theft of sensitive information // IE is secure though, which is the most important thing, since IE is the only browser, who // takes over scripts & styles into contentEditable elements when copied from external websites // or applications (Microsoft Word, ...) var i, length; for (i=0, length=windowProperties.length; i<length; i++) { this._unset(iframeWindow, windowProperties[i]); } for (i=0, length=windowProperties2.length; i<length; i++) { this._unset(iframeWindow, windowProperties2[i], wysihtml5.EMPTY_FUNCTION); } for (i=0, length=documentProperties.length; i<length; i++) { this._unset(iframeDocument, documentProperties[i]); } // This doesn't work in Safari 5 // See http://stackoverflow.com/questions/992461/is-it-possible-to-override-document-cookie-in-webkit this._unset(iframeDocument, "cookie", "", true); } if (wysihtml5.polyfills) { wysihtml5.polyfills(iframeWindow, iframeDocument); } this.loaded = true; // Trigger the callback setTimeout(function() { that.callback(that); }, 0); }, _getHtml: function(templateVars) { var stylesheets = templateVars.stylesheets, html = "", i = 0, length; stylesheets = typeof(stylesheets) === "string" ? [stylesheets] : stylesheets; if (stylesheets) { length = stylesheets.length; for (; i<length; i++) { html += '<link rel="stylesheet" href="' + stylesheets[i] + '">'; } } templateVars.stylesheets = html; return wysihtml5.lang.string( '<!DOCTYPE html><html><head>' + '<meta charset="#{charset}">#{stylesheets}</head>' + '<body></body></html>' ).interpolate(templateVars); }, /** * Method to unset/override existing variables * @example * // Make cookie unreadable and unwritable * this._unset(document, "cookie", "", true); */ _unset: function(object, property, value, setter) { try { object[property] = value; } catch(e) {} try { object.__defineGetter__(property, function() { return value; }); } catch(e) {} if (setter) { try { object.__defineSetter__(property, function() {}); } catch(e) {} } if (!wysihtml5.browser.crashesWhenDefineProperty(property)) { try { var config = { get: function() { return value; } }; if (setter) { config.set = function() {}; } Object.defineProperty(object, property, config); } catch(e) {} } } }); })(wysihtml5); ;(function(wysihtml5) { var doc = document; wysihtml5.dom.ContentEditableArea = Base.extend({ getContentEditable: function() { return this.element; }, getWindow: function() { return this.element.ownerDocument.defaultView || this.element.ownerDocument.parentWindow; }, getDocument: function() { return this.element.ownerDocument; }, constructor: function(readyCallback, config, contentEditable) { this.callback = readyCallback || wysihtml5.EMPTY_FUNCTION; this.config = wysihtml5.lang.object({}).merge(config).get(); if (!this.config.className) { this.config.className = "wysihtml5-sandbox"; } if (contentEditable) { this.element = this._bindElement(contentEditable); } else { this.element = this._createElement(); } }, // creates a new contenteditable and initiates it _createElement: function() { var element = doc.createElement("div"); element.className = this.config.className; this._loadElement(element); return element; }, // initiates an allready existent contenteditable _bindElement: function(contentEditable) { contentEditable.className = contentEditable.className ? contentEditable.className + " wysihtml5-sandbox" : "wysihtml5-sandbox"; this._loadElement(contentEditable, true); return contentEditable; }, _loadElement: function(element, contentExists) { var that = this; if (!contentExists) { var innerHtml = this._getHtml(); element.innerHTML = innerHtml; } this.loaded = true; // Trigger the callback setTimeout(function() { that.callback(that); }, 0); }, _getHtml: function(templateVars) { return ''; } }); })(wysihtml5); ;(function() { var mapping = { "className": "class" }; wysihtml5.dom.setAttributes = function(attributes) { return { on: function(element) { for (var i in attributes) { element.setAttribute(mapping[i] || i, attributes[i]); } } }; }; })(); ;wysihtml5.dom.setStyles = function(styles) { return { on: function(element) { var style = element.style; if (typeof(styles) === "string") { style.cssText += ";" + styles; return; } for (var i in styles) { if (i === "float") { style.cssFloat = styles[i]; style.styleFloat = styles[i]; } else { style[i] = styles[i]; } } } }; }; ;/** * Simulate HTML5 placeholder attribute * * Needed since * - div[contentEditable] elements don't support it * - older browsers (such as IE8 and Firefox 3.6) don't support it at all * * @param {Object} parent Instance of main wysihtml5.Editor class * @param {Element} view Instance of wysihtml5.views.* class * @param {String} placeholderText * * @example * wysihtml.dom.simulatePlaceholder(this, composer, "Foobar"); */ (function(dom) { dom.simulatePlaceholder = function(editor, view, placeholderText, placeholderClassName) { var CLASS_NAME = placeholderClassName || "wysihtml5-placeholder", unset = function() { var composerIsVisible = view.element.offsetWidth > 0 && view.element.offsetHeight > 0; if (view.hasPlaceholderSet()) { view.clear(); view.element.focus(); if (composerIsVisible ) { setTimeout(function() { var sel = view.selection.getSelection(); if (!sel.focusNode || !sel.anchorNode) { view.selection.selectNode(view.element.firstChild || view.element); } }, 0); } } view.placeholderSet = false; dom.removeClass(view.element, CLASS_NAME); }, set = function() { if (view.isEmpty() && !view.placeholderSet) { view.placeholderSet = true; view.setValue(placeholderText); dom.addClass(view.element, CLASS_NAME); } }; editor .on("set_placeholder", set) .on("unset_placeholder", unset) .on("focus:composer", unset) .on("paste:composer", unset) .on("blur:composer", set); set(); }; })(wysihtml5.dom); ;(function(dom) { var documentElement = document.documentElement; if ("textContent" in documentElement) { dom.setTextContent = function(element, text) { element.textContent = text; }; dom.getTextContent = function(element) { return element.textContent; }; } else if ("innerText" in documentElement) { dom.setTextContent = function(element, text) { element.innerText = text; }; dom.getTextContent = function(element) { return element.innerText; }; } else { dom.setTextContent = function(element, text) { element.nodeValue = text; }; dom.getTextContent = function(element) { return element.nodeValue; }; } })(wysihtml5.dom); ;/** * Get a set of attribute from one element * * IE gives wrong results for hasAttribute/getAttribute, for example: * var td = document.createElement("td"); * td.getAttribute("rowspan"); // => "1" in IE * * Therefore we have to check the element's outerHTML for the attribute */ wysihtml5.dom.getAttribute = function(node, attributeName) { var HAS_GET_ATTRIBUTE_BUG = !wysihtml5.browser.supportsGetAttributeCorrectly(); attributeName = attributeName.toLowerCase(); var nodeName = node.nodeName; if (nodeName == "IMG" && attributeName == "src" && wysihtml5.dom.isLoadedImage(node) === true) { // Get 'src' attribute value via object property since this will always contain the // full absolute url (http://...) // this fixes a very annoying bug in firefox (ver 3.6 & 4) and IE 8 where images copied from the same host // will have relative paths, which the sanitizer strips out (see attributeCheckMethods.url) return node.src; } else if (HAS_GET_ATTRIBUTE_BUG && "outerHTML" in node) { // Don't trust getAttribute/hasAttribute in IE 6-8, instead check the element's outerHTML var outerHTML = node.outerHTML.toLowerCase(), // TODO: This might not work for attributes without value: <input disabled> hasAttribute = outerHTML.indexOf(" " + attributeName + "=") != -1; return hasAttribute ? node.getAttribute(attributeName) : null; } else{ return node.getAttribute(attributeName); } }; ;/** * Get all attributes of an element * * IE gives wrong results for hasAttribute/getAttribute, for example: * var td = document.createElement("td"); * td.getAttribute("rowspan"); // => "1" in IE * * Therefore we have to check the element's outerHTML for the attribute */ wysihtml5.dom.getAttributes = function(node) { var HAS_GET_ATTRIBUTE_BUG = !wysihtml5.browser.supportsGetAttributeCorrectly(), nodeName = node.nodeName, attributes = [], attr; for (attr in node.attributes) { if ((node.attributes.hasOwnProperty && node.attributes.hasOwnProperty(attr)) || (!node.attributes.hasOwnProperty && Object.prototype.hasOwnProperty.call(node.attributes, attr))) { if (node.attributes[attr].specified) { if (nodeName == "IMG" && node.attributes[attr].name.toLowerCase() == "src" && wysihtml5.dom.isLoadedImage(node) === true) { attributes['src'] = node.src; } else if (wysihtml5.lang.array(['rowspan', 'colspan']).contains(node.attributes[attr].name.toLowerCase()) && HAS_GET_ATTRIBUTE_BUG) { if (node.attributes[attr].value !== 1) { attributes[node.attributes[attr].name] = node.attributes[attr].value; } } else { attributes[node.attributes[attr].name] = node.attributes[attr].value; } } } } return attributes; }; ;/** * Check whether the given node is a proper loaded image * FIXME: Returns undefined when unknown (Chrome, Safari) */ wysihtml5.dom.isLoadedImage = function (node) { try { return node.complete && !node.mozMatchesSelector(":-moz-broken"); } catch(e) { if (node.complete && node.readyState === "complete") { return true; } } }; ;(function(wysihtml5) { var api = wysihtml5.dom; var MapCell = function(cell) { this.el = cell; this.isColspan= false; this.isRowspan= false; this.firstCol= true; this.lastCol= true; this.firstRow= true; this.lastRow= true; this.isReal= true; this.spanCollection= []; this.modified = false; }; var TableModifyerByCell = function (cell, table) { if (cell) { this.cell = cell; this.table = api.getParentElement(cell, { query: "table" }); } else if (table) { this.table = table; this.cell = this.table.querySelectorAll('th, td')[0]; } }; function queryInList(list, query) { var ret = [], q; for (var e = 0, len = list.length; e < len; e++) { q = list[e].querySelectorAll(query); if (q) { for(var i = q.length; i--; ret.unshift(q[i])); } } return ret; } function removeElement(el) { el.parentNode.removeChild(el); } function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } function nextNode(node, tag) { var element = node.nextSibling; while (element.nodeType !=1) { element = element.nextSibling; if (!tag || tag == element.tagName.toLowerCase()) { return element; } } return null; } TableModifyerByCell.prototype = { addSpannedCellToMap: function(cell, map, r, c, cspan, rspan) { var spanCollect = [], rmax = r + ((rspan) ? parseInt(rspan, 10) - 1 : 0), cmax = c + ((cspan) ? parseInt(cspan, 10) - 1 : 0); for (var rr = r; rr <= rmax; rr++) { if (typeof map[rr] == "undefined") { map[rr] = []; } for (var cc = c; cc <= cmax; cc++) { map[rr][cc] = new MapCell(cell); map[rr][cc].isColspan = (cspan && parseInt(cspan, 10) > 1); map[rr][cc].isRowspan = (rspan && parseInt(rspan, 10) > 1); map[rr][cc].firstCol = cc == c; map[rr][cc].lastCol = cc == cmax; map[rr][cc].firstRow = rr == r; map[rr][cc].lastRow = rr == rmax; map[rr][cc].isReal = cc == c && rr == r; map[rr][cc].spanCollection = spanCollect; spanCollect.push(map[rr][cc]); } } }, setCellAsModified: function(cell) { cell.modified = true; if (cell.spanCollection.length > 0) { for (var s = 0, smax = cell.spanCollection.length; s < smax; s++) { cell.spanCollection[s].modified = true; } } }, setTableMap: function() { var map = []; var tableRows = this.getTableRows(), ridx, row, cells, cidx, cell, c, cspan, rspan; for (ridx = 0; ridx < tableRows.length; ridx++) { row = tableRows[ridx]; cells = this.getRowCells(row); c = 0; if (typeof map[ridx] == "undefined") { map[ridx] = []; } for (cidx = 0; cidx < cells.length; cidx++) { cell = cells[cidx]; // If cell allready set means it is set by col or rowspan, // so increase cols index until free col is found while (typeof map[ridx][c] != "undefined") { c++; } cspan = api.getAttribute(cell, 'colspan'); rspan = api.getAttribute(cell, 'rowspan'); if (cspan || rspan) { this.addSpannedCellToMap(cell, map, ridx, c, cspan, rspan); c = c + ((cspan) ? parseInt(cspan, 10) : 1); } else { map[ridx][c] = new MapCell(cell); c++; } } } this.map = map; return map; }, getRowCells: function(row) { var inlineTables = this.table.querySelectorAll('table'), inlineCells = (inlineTables) ? queryInList(inlineTables, 'th, td') : [], allCells = row.querySelectorAll('th, td'), tableCells = (inlineCells.length > 0) ? wysihtml5.lang.array(allCells).without(inlineCells) : allCells; return tableCells; }, getTableRows: function() { var inlineTables = this.table.querySelectorAll('table'), inlineRows = (inlineTables) ? queryInList(inlineTables, 'tr') : [], allRows = this.table.querySelectorAll('tr'), tableRows = (inlineRows.length > 0) ? wysihtml5.lang.array(allRows).without(inlineRows) : allRows; return tableRows; }, getMapIndex: function(cell) { var r_length = this.map.length, c_length = (this.map && this.map[0]) ? this.map[0].length : 0; for (var r_idx = 0;r_idx < r_length; r_idx++) { for (var c_idx = 0;c_idx < c_length; c_idx++) { if (this.map[r_idx][c_idx].el === cell) { return {'row': r_idx, 'col': c_idx}; } } } return false; }, getElementAtIndex: function(idx) { this.setTableMap(); if (this.map[idx.row] && this.map[idx.row][idx.col] && this.map[idx.row][idx.col].el) { return this.map[idx.row][idx.col].el; } return null; }, getMapElsTo: function(to_cell) { var els = []; this.setTableMap(); this.idx_start = this.getMapIndex(this.cell); this.idx_end = this.getMapIndex(to_cell); // switch indexes if start is bigger than end if (this.idx_start.row > this.idx_end.row || (this.idx_start.row == this.idx_end.row && this.idx_start.col > this.idx_end.col)) { var temp_idx = this.idx_start; this.idx_start = this.idx_end; this.idx_end = temp_idx; } if (this.idx_start.col > this.idx_end.col) { var temp_cidx = this.idx_start.col; this.idx_start.col = this.idx_end.col; this.idx_end.col = temp_cidx; } if (this.idx_start != null && this.idx_end != null) { for (var row = this.idx_start.row, maxr = this.idx_end.row; row <= maxr; row++) { for (var col = this.idx_start.col, maxc = this.idx_end.col; col <= maxc; col++) { els.push(this.map[row][col].el); } } } return els; }, orderSelectionEnds: function(secondcell) { this.setTableMap(); this.idx_start = this.getMapIndex(this.cell); this.idx_end = this.getMapIndex(secondcell); // switch indexes if start is bigger than end if (this.idx_start.row > this.idx_end.row || (this.idx_start.row == this.idx_end.row && this.idx_start.col > this.idx_end.col)) { var temp_idx = this.idx_start; this.idx_start = this.idx_end; this.idx_end = temp_idx; } if (this.idx_start.col > this.idx_end.col) { var temp_cidx = this.idx_start.col; this.idx_start.col = this.idx_end.col; this.idx_end.col = temp_cidx; } return { "start": this.map[this.idx_start.row][this.idx_start.col].el, "end": this.map[this.idx_end.row][this.idx_end.col].el }; }, createCells: function(tag, nr, attrs) { var doc = this.table.ownerDocument, frag = doc.createDocumentFragment(), cell; for (var i = 0; i < nr; i++) { cell = doc.createElement(tag); if (attrs) { for (var attr in attrs) { if (attrs.hasOwnProperty(attr)) { cell.setAttribute(attr, attrs[attr]); } } } // add non breaking space cell.appendChild(document.createTextNode("\u00a0")); frag.appendChild(cell); } return frag; }, // Returns next real cell (not part of spanned cell unless first) on row if selected index is not real. I no real cells -1 will be returned correctColIndexForUnreals: function(col, row) { var r = this.map[row], corrIdx = -1; for (var i = 0, max = col; i < col; i++) { if (r[i].isReal){ corrIdx++; } } return corrIdx; }, getLastNewCellOnRow: function(row, rowLimit) { var cells = this.getRowCells(row), cell, idx; for (var cidx = 0, cmax = cells.length; cidx < cmax; cidx++) { cell = cells[cidx]; idx = this.getMapIndex(cell); if (idx === false || (typeof rowLimit != "undefined" && idx.row != rowLimit)) { return cell; } } return null; }, removeEmptyTable: function() { var cells = this.table.querySelectorAll('td, th'); if (!cells || cells.length == 0) { removeElement(this.table); return true; } else { return false; } }, // Splits merged cell on row to unique cells splitRowToCells: function(cell) { if (cell.isColspan) { var colspan = parseInt(api.getAttribute(cell.el, 'colspan') || 1, 10), cType = cell.el.tagName.toLowerCase(); if (colspan > 1) { var newCells = this.createCells(cType, colspan -1); insertAfter(cell.el, newCells); } cell.el.removeAttribute('colspan'); } }, getRealRowEl: function(force, idx) { var r = null, c = null; idx = idx || this.idx; for (var cidx = 0, cmax = this.map[idx.row].length; cidx < cmax; cidx++) { c = this.map[idx.row][cidx]; if (c.isReal) { r = api.getParentElement(c.el, { query: "tr" }); if (r) { return r; } } } if (r === null && force) { r = api.getParentElement(this.map[idx.row][idx.col].el, { query: "tr" }) || null; } return r; }, injectRowAt: function(row, col, colspan, cType, c) { var r = this.getRealRowEl(false, {'row': row, 'col': col}), new_cells = this.createCells(cType, colspan); if (r) { var n_cidx = this.correctColIndexForUnreals(col, row); if (n_cidx >= 0) { insertAfter(this.getRowCells(r)[n_cidx], new_cells); } else { r.insertBefore(new_cells, r.firstChild); } } else { var rr = this.table.ownerDocument.createElement('tr'); rr.appendChild(new_cells); insertAfter(api.getParentElement(c.el, { query: "tr" }), rr); } }, canMerge: function(to) { this.to = to; this.setTableMap(); this.idx_start = this.getMapIndex(this.cell); this.idx_end = this.getMapIndex(this.to); // switch indexes if start is bigger than end if (this.idx_start.row > this.idx_end.row || (this.idx_start.row == this.idx_end.row && this.idx_start.col > this.idx_end.col)) { var temp_idx = this.idx_start; this.idx_start = this.idx_end; this.idx_end = temp_idx; } if (this.idx_start.col > this.idx_end.col) { var temp_cidx = this.idx_start.col; this.idx_start.col = this.idx_end.col; this.idx_end.col = temp_cidx; } for (var row = this.idx_start.row, maxr = this.idx_end.row; row <= maxr; row++) { for (var col = this.idx_start.col, maxc = this.idx_end.col; col <= maxc; col++) { if (this.map[row][col].isColspan || this.map[row][col].isRowspan) { return false; } } } return true; }, decreaseCellSpan: function(cell, span) { var nr = parseInt(api.getAttribute(cell.el, span), 10) - 1; if (nr >= 1) { cell.el.setAttribute(span, nr); } else { cell.el.removeAttribute(span); if (span == 'colspan') { cell.isColspan = false; } if (span == 'rowspan') { cell.isRowspan = false; } cell.firstCol = true; cell.lastCol = true; cell.firstRow = true; cell.lastRow = true; cell.isReal = true; } }, removeSurplusLines: function() { var row, cell, ridx, rmax, cidx, cmax, allRowspan; this.setTableMap(); if (this.map) { ridx = 0; rmax = this.map.length; for (;ridx < rmax; ridx++) { row = this.map[ridx]; allRowspan = true; cidx = 0; cmax = row.length; for (; cidx < cmax; cidx++) { cell = row[cidx]; if (!(api.getAttribute(cell.el, "rowspan") && parseInt(api.getAttribute(cell.el, "rowspan"), 10) > 1 && cell.firstRow !== true)) { allRowspan = false; break; } } if (allRowspan) { cidx = 0; for (; cidx < cmax; cidx++) { this.decreaseCellSpan(row[cidx], 'rowspan'); } } } // remove rows without cells var tableRows = this.getTableRows(); ridx = 0; rmax = tableRows.length; for (;ridx < rmax; ridx++) { row = tableRows[ridx]; if (row.childNodes.length == 0 && (/^\s*$/.test(row.textContent || row.innerText))) { removeElement(row); } } } }, fillMissingCells: function() { var r_max = 0, c_max = 0, prevcell = null; this.setTableMap(); if (this.map) { // find maximal dimensions of broken table r_max = this.map.length; for (var ridx = 0; ridx < r_max; ridx++) { if (this.map[ridx].length > c_max) { c_max = this.map[ridx].length; } } for (var row = 0; row < r_max; row++) { for (var col = 0; col < c_max; col++) { if (this.map[row] && !this.map[row][col]) { if (col > 0) { this.map[row][col] = new MapCell(this.createCells('td', 1)); prevcell = this.map[row][col-1]; if (prevcell && prevcell.el && prevcell.el.parent) { // if parent does not exist element is removed from dom insertAfter(this.map[row][col-1].el, this.map[row][col].el); } } } } } } }, rectify: function() { if (!this.removeEmptyTable()) { this.removeSurplusLines(); this.fillMissingCells(); return true; } else { return false; } }, unmerge: function() { if (this.rectify()) { this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx) { var thisCell = this.map[this.idx.row][this.idx.col], colspan = (api.getAttribute(thisCell.el, "colspan")) ? parseInt(api.getAttribute(thisCell.el, "colspan"), 10) : 1, cType = thisCell.el.tagName.toLowerCase(); if (thisCell.isRowspan) { var rowspan = parseInt(api.getAttribute(thisCell.el, "rowspan"), 10); if (rowspan > 1) { for (var nr = 1, maxr = rowspan - 1; nr <= maxr; nr++){ this.injectRowAt(this.idx.row + nr, this.idx.col, colspan, cType, thisCell); } } thisCell.el.removeAttribute('rowspan'); } this.splitRowToCells(thisCell); } } }, // merges cells from start cell (defined in creating obj) to "to" cell merge: function(to) { if (this.rectify()) { if (this.canMerge(to)) { var rowspan = this.idx_end.row - this.idx_start.row + 1, colspan = this.idx_end.col - this.idx_start.col + 1; for (var row = this.idx_start.row, maxr = this.idx_end.row; row <= maxr; row++) { for (var col = this.idx_start.col, maxc = this.idx_end.col; col <= maxc; col++) { if (row == this.idx_start.row && col == this.idx_start.col) { if (rowspan > 1) { this.map[row][col].el.setAttribute('rowspan', rowspan); } if (colspan > 1) { this.map[row][col].el.setAttribute('colspan', colspan); } } else { // transfer content if (!(/^\s*<br\/?>\s*$/.test(this.map[row][col].el.innerHTML.toLowerCase()))) { this.map[this.idx_start.row][this.idx_start.col].el.innerHTML += ' ' + this.map[row][col].el.innerHTML; } removeElement(this.map[row][col].el); } } } this.rectify(); } else { if (window.console) { console.log('Do not know how to merge allready merged cells.'); } } } }, // Decreases rowspan of a cell if it is done on first cell of rowspan row (real cell) // Cell is moved to next row (if it is real) collapseCellToNextRow: function(cell) { var cellIdx = this.getMapIndex(cell.el), newRowIdx = cellIdx.row + 1, newIdx = {'row': newRowIdx, 'col': cellIdx.col}; if (newRowIdx < this.map.length) { var row = this.getRealRowEl(false, newIdx); if (row !== null) { var n_cidx = this.correctColIndexForUnreals(newIdx.col, newIdx.row); if (n_cidx >= 0) { insertAfter(this.getRowCells(row)[n_cidx], cell.el); } else { var lastCell = this.getLastNewCellOnRow(row, newRowIdx); if (lastCell !== null) { insertAfter(lastCell, cell.el); } else { row.insertBefore(cell.el, row.firstChild); } } if (parseInt(api.getAttribute(cell.el, 'rowspan'), 10) > 2) { cell.el.setAttribute('rowspan', parseInt(api.getAttribute(cell.el, 'rowspan'), 10) - 1); } else { cell.el.removeAttribute('rowspan'); } } } }, // Removes a cell when removing a row // If is rowspan cell then decreases the rowspan // and moves cell to next row if needed (is first cell of rowspan) removeRowCell: function(cell) { if (cell.isReal) { if (cell.isRowspan) { this.collapseCellToNextRow(cell); } else { removeElement(cell.el); } } else { if (parseInt(api.getAttribute(cell.el, 'rowspan'), 10) > 2) { cell.el.setAttribute('rowspan', parseInt(api.getAttribute(cell.el, 'rowspan'), 10) - 1); } else { cell.el.removeAttribute('rowspan'); } } }, getRowElementsByCell: function() { var cells = []; this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { var modRow = this.map[this.idx.row]; for (var cidx = 0, cmax = modRow.length; cidx < cmax; cidx++) { if (modRow[cidx].isReal) { cells.push(modRow[cidx].el); } } } return cells; }, getColumnElementsByCell: function() { var cells = []; this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { for (var ridx = 0, rmax = this.map.length; ridx < rmax; ridx++) { if (this.map[ridx][this.idx.col] && this.map[ridx][this.idx.col].isReal) { cells.push(this.map[ridx][this.idx.col].el); } } } return cells; }, // Removes the row of selected cell removeRow: function() { var oldRow = api.getParentElement(this.cell, { query: "tr" }); if (oldRow) { this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { var modRow = this.map[this.idx.row]; for (var cidx = 0, cmax = modRow.length; cidx < cmax; cidx++) { if (!modRow[cidx].modified) { this.setCellAsModified(modRow[cidx]); this.removeRowCell(modRow[cidx]); } } } removeElement(oldRow); } }, removeColCell: function(cell) { if (cell.isColspan) { if (parseInt(api.getAttribute(cell.el, 'colspan'), 10) > 2) { cell.el.setAttribute('colspan', parseInt(api.getAttribute(cell.el, 'colspan'), 10) - 1); } else { cell.el.removeAttribute('colspan'); } } else if (cell.isReal) { removeElement(cell.el); } }, removeColumn: function() { this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (this.idx !== false) { for (var ridx = 0, rmax = this.map.length; ridx < rmax; ridx++) { if (!this.map[ridx][this.idx.col].modified) { this.setCellAsModified(this.map[ridx][this.idx.col]); this.removeColCell(this.map[ridx][this.idx.col]); } } } }, // removes row or column by selected cell element remove: function(what) { if (this.rectify()) { switch (what) { case 'row': this.removeRow(); break; case 'column': this.removeColumn(); break; } this.rectify(); } }, addRow: function(where) { var doc = this.table.ownerDocument; this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (where == "below" && api.getAttribute(this.cell, 'rowspan')) { this.idx.row = this.idx.row + parseInt(api.getAttribute(this.cell, 'rowspan'), 10) - 1; } if (this.idx !== false) { var modRow = this.map[this.idx.row], newRow = doc.createElement('tr'); for (var ridx = 0, rmax = modRow.length; ridx < rmax; ridx++) { if (!modRow[ridx].modified) { this.setCellAsModified(modRow[ridx]); this.addRowCell(modRow[ridx], newRow, where); } } switch (where) { case 'below': insertAfter(this.getRealRowEl(true), newRow); break; case 'above': var cr = api.getParentElement(this.map[this.idx.row][this.idx.col].el, { query: "tr" }); if (cr) { cr.parentNode.insertBefore(newRow, cr); } break; } } }, addRowCell: function(cell, row, where) { var colSpanAttr = (cell.isColspan) ? {"colspan" : api.getAttribute(cell.el, 'colspan')} : null; if (cell.isReal) { if (where != 'above' && cell.isRowspan) { cell.el.setAttribute('rowspan', parseInt(api.getAttribute(cell.el,'rowspan'), 10) + 1); } else { row.appendChild(this.createCells('td', 1, colSpanAttr)); } } else { if (where != 'above' && cell.isRowspan && cell.lastRow) { row.appendChild(this.createCells('td', 1, colSpanAttr)); } else if (c.isRowspan) { cell.el.attr('rowspan', parseInt(api.getAttribute(cell.el, 'rowspan'), 10) + 1); } } }, add: function(where) { if (this.rectify()) { if (where == 'below' || where == 'above') { this.addRow(where); } if (where == 'before' || where == 'after') { this.addColumn(where); } } }, addColCell: function (cell, ridx, where) { var doAdd, cType = cell.el.tagName.toLowerCase(); // defines add cell vs expand cell conditions // true means add switch (where) { case "before": doAdd = (!cell.isColspan || cell.firstCol); break; case "after": doAdd = (!cell.isColspan || cell.lastCol || (cell.isColspan && c.el == this.cell)); break; } if (doAdd){ // adds a cell before or after current cell element switch (where) { case "before": cell.el.parentNode.insertBefore(this.createCells(cType, 1), cell.el); break; case "after": insertAfter(cell.el, this.createCells(cType, 1)); break; } // handles if cell has rowspan if (cell.isRowspan) { this.handleCellAddWithRowspan(cell, ridx+1, where); } } else { // expands cell cell.el.setAttribute('colspan', parseInt(api.getAttribute(cell.el, 'colspan'), 10) + 1); } }, addColumn: function(where) { var row, modCell; this.setTableMap(); this.idx = this.getMapIndex(this.cell); if (where == "after" && api.getAttribute(this.cell, 'colspan')) { this.idx.col = this.idx.col + parseInt(api.getAttribute(this.cell, 'colspan'), 10) - 1; } if (this.idx !== false) { for (var ridx = 0, rmax = this.map.length; ridx < rmax; ridx++ ) { row = this.map[ridx]; if (row[this.idx.col]) { modCell = row[this.idx.col]; if (!modCell.modified) { this.setCellAsModified(modCell); this.addColCell(modCell, ridx , where); } } } } }, handleCellAddWithRowspan: function (cell, ridx, where) { var addRowsNr = parseInt(api.getAttribute(this.cell, 'rowspan'), 10) - 1, crow = api.getParentElement(cell.el, { query: "tr" }), cType = cell.el.tagName.toLowerCase(), cidx, temp_r_cells, doc = this.table.ownerDocument, nrow; for (var i = 0; i < addRowsNr; i++) { cidx = this.correctColIndexForUnreals(this.idx.col, (ridx + i)); crow = nextNode(crow, 'tr'); if (crow) { if (cidx > 0) { switch (where) { case "before": temp_r_cells = this.getRowCells(crow); if (cidx > 0 && this.map[ridx + i][this.idx.col].el != temp_r_cells[cidx] && cidx == temp_r_cells.length - 1) { insertAfter(temp_r_cells[cidx], this.createCells(cType, 1)); } else { temp_r_cells[cidx].parentNode.insertBefore(this.createCells(cType, 1), temp_r_cells[cidx]); } break; case "after": insertAfter(this.getRowCells(crow)[cidx], this.createCells(cType, 1)); break; } } else { crow.insertBefore(this.createCells(cType, 1), crow.firstChild); } } else { nrow = doc.createElement('tr'); nrow.appendChild(this.createCells(cType, 1)); this.table.appendChild(nrow); } } } }; api.table = { getCellsBetween: function(cell1, cell2) { var c1 = new TableModifyerByCell(cell1); return c1.getMapElsTo(cell2); }, addCells: function(cell, where) { var c = new TableModifyerByCell(cell); c.add(where); }, removeCells: function(cell, what) { var c = new TableModifyerByCell(cell); c.remove(what); }, mergeCellsBetween: function(cell1, cell2) { var c1 = new TableModifyerByCell(cell1); c1.merge(cell2); }, unmergeCell: function(cell) { var c = new TableModifyerByCell(cell); c.unmerge(); }, orderSelectionEnds: function(cell, cell2) { var c = new TableModifyerByCell(cell); return c.orderSelectionEnds(cell2); }, indexOf: function(cell) { var c = new TableModifyerByCell(cell); c.setTableMap(); return c.getMapIndex(cell); }, findCell: function(table, idx) { var c = new TableModifyerByCell(null, table); return c.getElementAtIndex(idx); }, findRowByCell: function(cell) { var c = new TableModifyerByCell(cell); return c.getRowElementsByCell(); }, findColumnByCell: function(cell) { var c = new TableModifyerByCell(cell); return c.getColumnElementsByCell(); }, canMerge: function(cell1, cell2) { var c = new TableModifyerByCell(cell1); return c.canMerge(cell2); } }; })(wysihtml5); ;// does a selector query on element or array of elements wysihtml5.dom.query = function(elements, query) { var ret = [], q; if (elements.nodeType) { elements = [elements]; } for (var e = 0, len = elements.length; e < len; e++) { q = elements[e].querySelectorAll(query); if (q) { for(var i = q.length; i--; ret.unshift(q[i])); } } return ret; }; ;wysihtml5.dom.compareDocumentPosition = (function() { var documentElement = document.documentElement; if (documentElement.compareDocumentPosition) { return function(container, element) { return container.compareDocumentPosition(element); }; } else { return function( container, element ) { // implementation borrowed from https://github.com/tmpvar/jsdom/blob/681a8524b663281a0f58348c6129c8c184efc62c/lib/jsdom/level3/core.js // MIT license var thisOwner, otherOwner; if( container.nodeType === 9) // Node.DOCUMENT_NODE thisOwner = container; else thisOwner = container.ownerDocument; if( element.nodeType === 9) // Node.DOCUMENT_NODE otherOwner = element; else otherOwner = element.ownerDocument; if( container === element ) return 0; if( container === element.ownerDocument ) return 4 + 16; //Node.DOCUMENT_POSITION_FOLLOWING + Node.DOCUMENT_POSITION_CONTAINED_BY; if( container.ownerDocument === element ) return 2 + 8; //Node.DOCUMENT_POSITION_PRECEDING + Node.DOCUMENT_POSITION_CONTAINS; if( thisOwner !== otherOwner ) return 1; // Node.DOCUMENT_POSITION_DISCONNECTED; // Text nodes for attributes does not have a _parentNode. So we need to find them as attribute child. if( container.nodeType === 2 /*Node.ATTRIBUTE_NODE*/ && container.childNodes && wysihtml5.lang.array(container.childNodes).indexOf( element ) !== -1) return 4 + 16; //Node.DOCUMENT_POSITION_FOLLOWING + Node.DOCUMENT_POSITION_CONTAINED_BY; if( element.nodeType === 2 /*Node.ATTRIBUTE_NODE*/ && element.childNodes && wysihtml5.lang.array(element.childNodes).indexOf( container ) !== -1) return 2 + 8; //Node.DOCUMENT_POSITION_PRECEDING + Node.DOCUMENT_POSITION_CONTAINS; var point = container; var parents = [ ]; var previous = null; while( point ) { if( point == element ) return 2 + 8; //Node.DOCUMENT_POSITION_PRECEDING + Node.DOCUMENT_POSITION_CONTAINS; parents.push( point ); point = point.parentNode; } point = element; previous = null; while( point ) { if( point == container ) return 4 + 16; //Node.DOCUMENT_POSITION_FOLLOWING + Node.DOCUMENT_POSITION_CONTAINED_BY; var location_index = wysihtml5.lang.array(parents).indexOf( point ); if( location_index !== -1) { var smallest_common_ancestor = parents[ location_index ]; var this_index = wysihtml5.lang.array(smallest_common_ancestor.childNodes).indexOf( parents[location_index - 1]);//smallest_common_ancestor.childNodes.toArray().indexOf( parents[location_index - 1] ); var other_index = wysihtml5.lang.array(smallest_common_ancestor.childNodes).indexOf( previous ); //smallest_common_ancestor.childNodes.toArray().indexOf( previous ); if( this_index > other_index ) { return 2; //Node.DOCUMENT_POSITION_PRECEDING; } else { return 4; //Node.DOCUMENT_POSITION_FOLLOWING; } } previous = point; point = point.parentNode; } return 1; //Node.DOCUMENT_POSITION_DISCONNECTED; }; } })(); ;/* Unwraps element and returns list of childNodes that the node contained. * * Example: * var childnodes = wysihtml5.dom.unwrap(document.querySelector('.unwrap-me')); */ wysihtml5.dom.unwrap = function(node) { var children = []; if (node.parentNode) { while (node.lastChild) { children.unshift(node.lastChild); wysihtml5.dom.insert(node.lastChild).after(node); } node.parentNode.removeChild(node); } return children; }; ;/* * Methods for fetching pasted html before it gets inserted into content **/ /* Modern event.clipboardData driven approach. * Advantage is that it does not have to loose selection or modify dom to catch the data. * IE does not support though. **/ wysihtml5.dom.getPastedHtml = function(event) { var html; if (event.clipboardData) { if (wysihtml5.lang.array(event.clipboardData.types).contains('text/html')) { html = event.clipboardData.getData('text/html'); } else if (wysihtml5.lang.array(event.clipboardData.types).contains('text/plain')) { html = wysihtml5.lang.string(event.clipboardData.getData('text/plain')).escapeHTML(true, true); } } return html; }; /* Older temprorary contenteditable as paste source catcher method for fallbacks */ wysihtml5.dom.getPastedHtmlWithDiv = function (composer, f) { var selBookmark = composer.selection.getBookmark(), doc = composer.element.ownerDocument, cleanerDiv = doc.createElement('DIV'), scrollPos = composer.getScrollPos(); doc.body.appendChild(cleanerDiv); cleanerDiv.style.width = "1px"; cleanerDiv.style.height = "1px"; cleanerDiv.style.overflow = "hidden"; cleanerDiv.style.position = "absolute"; cleanerDiv.style.top = scrollPos.y + "px"; cleanerDiv.style.left = scrollPos.x + "px"; cleanerDiv.setAttribute('contenteditable', 'true'); cleanerDiv.focus(); setTimeout(function () { var html; composer.selection.setBookmark(selBookmark); html = cleanerDiv.innerHTML; if (html && (/^<br\/?>$/i).test(html.trim())) { html = false; } f(html); cleanerDiv.parentNode.removeChild(cleanerDiv); }, 0); }; ;wysihtml5.dom.removeInvisibleSpaces = function(node) { var textNodes = wysihtml5.dom.getTextNodes(node); for (var n = textNodes.length; n--;) { textNodes[n].nodeValue = textNodes[n].nodeValue.replace(wysihtml5.INVISIBLE_SPACE_REG_EXP, ""); } }; ;/** * Fix most common html formatting misbehaviors of browsers implementation when inserting * content via copy & paste contentEditable * * @author Christopher Blum */ wysihtml5.quirks.cleanPastedHTML = (function() { var styleToRegex = function (styleStr) { var trimmedStr = wysihtml5.lang.string(styleStr).trim(), escapedStr = trimmedStr.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); return new RegExp("^((?!^" + escapedStr + "$).)*$", "i"); }; var extendRulesWithStyleExceptions = function (rules, exceptStyles) { var newRules = wysihtml5.lang.object(rules).clone(true), tag, style; for (tag in newRules.tags) { if (newRules.tags.hasOwnProperty(tag)) { if (newRules.tags[tag].keep_styles) { for (style in newRules.tags[tag].keep_styles) { if (newRules.tags[tag].keep_styles.hasOwnProperty(style)) { if (exceptStyles[style]) { newRules.tags[tag].keep_styles[style] = styleToRegex(exceptStyles[style]); } } } } } } return newRules; }; var pickRuleset = function(ruleset, html) { var pickedSet, defaultSet; if (!ruleset) { return null; } for (var i = 0, max = ruleset.length; i < max; i++) { if (!ruleset[i].condition) { defaultSet = ruleset[i].set; } if (ruleset[i].condition && ruleset[i].condition.test(html)) { return ruleset[i].set; } } return defaultSet; }; return function(html, options) { var exceptStyles = { 'color': wysihtml5.dom.getStyle("color").from(options.referenceNode), 'fontSize': wysihtml5.dom.getStyle("font-size").from(options.referenceNode) }, rules = extendRulesWithStyleExceptions(pickRuleset(options.rules, html) || {}, exceptStyles), newHtml; newHtml = wysihtml5.dom.parse(html, { "rules": rules, "cleanUp": true, // <span> elements, empty or without attributes, should be removed/replaced with their content "context": options.referenceNode.ownerDocument, "uneditableClass": options.uneditableClass, "clearInternals" : true, // don't paste temprorary selection and other markings "unjoinNbsps" : true }); return newHtml; }; })(); ;/** * IE and Opera leave an empty paragraph in the contentEditable element after clearing it * * @param {Object} contentEditableElement The contentEditable element to observe for clearing events * @exaple * wysihtml5.quirks.ensureProperClearing(myContentEditableElement); */ wysihtml5.quirks.ensureProperClearing = (function() { var clearIfNecessary = function() { var element = this; setTimeout(function() { var innerHTML = element.innerHTML.toLowerCase(); if (innerHTML == "<p>&nbsp;</p>" || innerHTML == "<p>&nbsp;</p><p>&nbsp;</p>") { element.innerHTML = ""; } }, 0); }; return function(composer) { wysihtml5.dom.observe(composer.element, ["cut", "keydown"], clearIfNecessary); }; })(); ;// See https://bugzilla.mozilla.org/show_bug.cgi?id=664398 // // In Firefox this: // var d = document.createElement("div"); // d.innerHTML ='<a href="~"></a>'; // d.innerHTML; // will result in: // <a href="%7E"></a> // which is wrong (function(wysihtml5) { var TILDE_ESCAPED = "%7E"; wysihtml5.quirks.getCorrectInnerHTML = function(element) { var innerHTML = element.innerHTML; if (innerHTML.indexOf(TILDE_ESCAPED) === -1) { return innerHTML; } var elementsWithTilde = element.querySelectorAll("[href*='~'], [src*='~']"), url, urlToSearch, length, i; for (i=0, length=elementsWithTilde.length; i<length; i++) { url = elementsWithTilde[i].href || elementsWithTilde[i].src; urlToSearch = wysihtml5.lang.string(url).replace("~").by(TILDE_ESCAPED); innerHTML = wysihtml5.lang.string(innerHTML).replace(urlToSearch).by(url); } return innerHTML; }; })(wysihtml5); ;/** * Force rerendering of a given element * Needed to fix display misbehaviors of IE * * @param {Element} element The element object which needs to be rerendered * @example * wysihtml5.quirks.redraw(document.body); */ (function(wysihtml5) { var CLASS_NAME = "wysihtml5-quirks-redraw"; wysihtml5.quirks.redraw = function(element) { wysihtml5.dom.addClass(element, CLASS_NAME); wysihtml5.dom.removeClass(element, CLASS_NAME); // Following hack is needed for firefox to make sure that image resize handles are properly removed try { var doc = element.ownerDocument; doc.execCommand("italic", false, null); doc.execCommand("italic", false, null); } catch(e) {} }; })(wysihtml5); ;wysihtml5.quirks.tableCellsSelection = function(editable, editor) { var dom = wysihtml5.dom, select = { table: null, start: null, end: null, cells: null, select: selectCells }, selection_class = "wysiwyg-tmp-selected-cell"; function init () { editable.addEventListener("mousedown", handleMouseDown); return select; } var handleMouseDown = function(event) { var target = wysihtml5.dom.getParentElement(event.target, { query: "td, th" }, false, editable); if (target) { handleSelectionMousedown(target); } }; function handleSelectionMousedown (target) { select.start = target; select.end = target; select.cells = [target]; select.table = dom.getParentElement(select.start, { query: "table" }, false, editable); if (select.table) { removeCellSelections(); dom.addClass(target, selection_class); editable.addEventListener("mousemove", handleMouseMove); editable.addEventListener("mouseup", handleMouseUp); editor.fire("tableselectstart").fire("tableselectstart:composer"); } } // remove all selection classes function removeCellSelections () { if (editable) { var selectedCells = editable.querySelectorAll('.' + selection_class); if (selectedCells.length > 0) { for (var i = 0; i < selectedCells.length; i++) { dom.removeClass(selectedCells[i], selection_class); } } } } function addSelections (cells) { for (var i = 0; i < cells.length; i++) { dom.addClass(cells[i], selection_class); } } function handleMouseMove (event) { var curTable = null, cell = dom.getParentElement(event.target, { query: "td, th" }, false, editable), oldEnd; if (cell && select.table && select.start) { curTable = dom.getParentElement(cell, { query: "table" }, false, editable); if (curTable && curTable === select.table) { removeCellSelections(); oldEnd = select.end; select.end = cell; select.cells = dom.table.getCellsBetween(select.start, cell); if (select.cells.length > 1) { editor.composer.selection.deselect(); } addSelections(select.cells); if (select.end !== oldEnd) { editor.fire("tableselectchange").fire("tableselectchange:composer"); } } } } function handleMouseUp (event) { editable.removeEventListener("mousemove", handleMouseMove); editable.removeEventListener("mouseup", handleMouseUp); editor.fire("tableselect").fire("tableselect:composer"); setTimeout(function() { bindSideclick(); },0); } var sideClickHandler = function(event) { editable.ownerDocument.removeEventListener("click", sideClickHandler); if (dom.getParentElement(event.target, { query: "table" }, false, editable) != select.table) { removeCellSelections(); select.table = null; select.start = null; select.end = null; editor.fire("tableunselect").fire("tableunselect:composer"); } }; function bindSideclick () { editable.ownerDocument.addEventListener("click", sideClickHandler); } function selectCells (start, end) { select.start = start; select.end = end; select.table = dom.getParentElement(select.start, { query: "table" }, false, editable); selectedCells = dom.table.getCellsBetween(select.start, select.end); addSelections(selectedCells); bindSideclick(); editor.fire("tableselect").fire("tableselect:composer"); } return init(); }; ;(function(wysihtml5) { // List of supported color format parsing methods // If radix is not defined 10 is expected as default var colorParseMethods = { rgba : { regex: /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([\d\.]+)\s*\)/i, name: "rgba" }, rgb : { regex: /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/i, name: "rgb" }, hex6 : { regex: /^#([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])/i, name: "hex", radix: 16 }, hex3 : { regex: /^#([0-9a-f])([0-9a-f])([0-9a-f])/i, name: "hex", radix: 16 } }, // Takes a style key name as an argument and makes a regex that can be used to the match key:value pair from style string makeParamRegExp = function (p) { return new RegExp("(^|\\s|;)" + p + "\\s*:\\s*[^;$]+", "gi"); }; // Takes color string value ("#abc", "rgb(1,2,3)", ...) as an argument and returns suitable parsing method for it function getColorParseMethod (colorStr) { var prop, colorTypeConf; for (prop in colorParseMethods) { if (!colorParseMethods.hasOwnProperty(prop)) { continue; } colorTypeConf = colorParseMethods[prop]; if (colorTypeConf.regex.test(colorStr)) { return colorTypeConf; } } } // Takes color string value ("#abc", "rgb(1,2,3)", ...) as an argument and returns the type of that color format "hex", "rgb", "rgba". function getColorFormat (colorStr) { var type = getColorParseMethod(colorStr); return type ? type.name : undefined; } // Public API functions for styleParser wysihtml5.quirks.styleParser = { // Takes color string value as an argument and returns suitable parsing method for it getColorParseMethod : getColorParseMethod, // Takes color string value as an argument and returns the type of that color format "hex", "rgb", "rgba". getColorFormat : getColorFormat, /* Parses a color string to and array of [red, green, blue, alpha]. * paramName: optional argument to parse color value directly from style string parameter * * Examples: * var colorArray = wysihtml5.quirks.styleParser.parseColor("#ABC"); // [170, 187, 204, 1] * var colorArray = wysihtml5.quirks.styleParser.parseColor("#AABBCC"); // [170, 187, 204, 1] * var colorArray = wysihtml5.quirks.styleParser.parseColor("rgb(1,2,3)"); // [1, 2, 3, 1] * var colorArray = wysihtml5.quirks.styleParser.parseColor("rgba(1,2,3,0.5)"); // [1, 2, 3, 0.5] * * var colorArray = wysihtml5.quirks.styleParser.parseColor("background-color: #ABC; color: #000;", "background-color"); // [170, 187, 204, 1] * var colorArray = wysihtml5.quirks.styleParser.parseColor("background-color: #ABC; color: #000;", "color"); // [0, 0, 0, 1] */ parseColor : function (stylesStr, paramName) { var paramsRegex, params, colorType, colorMatch, radix, colorStr = stylesStr; if (paramName) { paramsRegex = makeParamRegExp(paramName); if (!(params = stylesStr.match(paramsRegex))) { return false; } params = params.pop().split(":")[1]; colorStr = wysihtml5.lang.string(params).trim(); } if (!(colorType = getColorParseMethod(colorStr))) { return false; } if (!(colorMatch = colorStr.match(colorType.regex))) { return false; } radix = colorType.radix || 10; if (colorType === colorParseMethods.hex3) { colorMatch.shift(); colorMatch.push(1); return wysihtml5.lang.array(colorMatch).map(function(d, idx) { return (idx < 3) ? (parseInt(d, radix) * radix) + parseInt(d, radix): parseFloat(d); }); } colorMatch.shift(); if (!colorMatch[3]) { colorMatch.push(1); } return wysihtml5.lang.array(colorMatch).map(function(d, idx) { return (idx < 3) ? parseInt(d, radix): parseFloat(d); }); }, /* Takes rgba color array [r,g,b,a] as a value and formats it to color string with given format type * If no format is given, rgba/rgb is returned based on alpha value * * Example: * var colorStr = wysihtml5.quirks.styleParser.unparseColor([170, 187, 204, 1], "hash"); // "#AABBCC" * var colorStr = wysihtml5.quirks.styleParser.unparseColor([170, 187, 204, 1], "hex"); // "AABBCC" * var colorStr = wysihtml5.quirks.styleParser.unparseColor([170, 187, 204, 1], "csv"); // "170, 187, 204, 1" * var colorStr = wysihtml5.quirks.styleParser.unparseColor([170, 187, 204, 1], "rgba"); // "rgba(170,187,204,1)" * var colorStr = wysihtml5.quirks.styleParser.unparseColor([170, 187, 204, 1], "rgb"); // "rgb(170,187,204)" * * var colorStr = wysihtml5.quirks.styleParser.unparseColor([170, 187, 204, 0.5]); // "rgba(170,187,204,0.5)" * var colorStr = wysihtml5.quirks.styleParser.unparseColor([170, 187, 204, 1]); // "rgb(170,187,204)" */ unparseColor: function(val, colorFormat) { var hexRadix = 16; if (colorFormat === "hex") { return (val[0].toString(hexRadix) + val[1].toString(hexRadix) + val[2].toString(hexRadix)).toUpperCase(); } else if (colorFormat === "hash") { return "#" + (val[0].toString(hexRadix) + val[1].toString(hexRadix) + val[2].toString(hexRadix)).toUpperCase(); } else if (colorFormat === "rgb") { return "rgb(" + val[0] + "," + val[1] + "," + val[2] + ")"; } else if (colorFormat === "rgba") { return "rgba(" + val[0] + "," + val[1] + "," + val[2] + "," + val[3] + ")"; } else if (colorFormat === "csv") { return val[0] + "," + val[1] + "," + val[2] + "," + val[3]; } if (val[3] && val[3] !== 1) { return "rgba(" + val[0] + "," + val[1] + "," + val[2] + "," + val[3] + ")"; } else { return "rgb(" + val[0] + "," + val[1] + "," + val[2] + ")"; } }, // Parses font size value from style string parseFontSize: function(stylesStr) { var params = stylesStr.match(makeParamRegExp("font-size")); if (params) { return wysihtml5.lang.string(params[params.length - 1].split(":")[1]).trim(); } return false; } }; })(wysihtml5); ;/** * Selection API * * @example * var selection = new wysihtml5.Selection(editor); */ (function(wysihtml5) { var dom = wysihtml5.dom; function _getCumulativeOffsetTop(element) { var top = 0; if (element.parentNode) { do { top += element.offsetTop || 0; element = element.offsetParent; } while (element); } return top; } // Provides the depth of ``descendant`` relative to ``ancestor`` function getDepth(ancestor, descendant) { var ret = 0; while (descendant !== ancestor) { ret++; descendant = descendant.parentNode; if (!descendant) throw new Error("not a descendant of ancestor!"); } return ret; } function getWebkitSelectionFixNode(container) { var blankNode = document.createElement('span'); var placeholderRemover = function(event) { // Self-destructs the caret and keeps the text inserted into it by user var lastChild; container.removeEventListener('mouseup', placeholderRemover); container.removeEventListener('keydown', placeholderRemover); container.removeEventListener('touchstart', placeholderRemover); container.removeEventListener('focus', placeholderRemover); container.removeEventListener('blur', placeholderRemover); container.removeEventListener('paste', delayedPlaceholderRemover); container.removeEventListener('drop', delayedPlaceholderRemover); container.removeEventListener('beforepaste', delayedPlaceholderRemover); if (blankNode && blankNode.parentNode) { blankNode.parentNode.removeChild(blankNode); } }, delayedPlaceholderRemover = function (event) { if (blankNode && blankNode.parentNode) { setTimeout(placeholderRemover, 0); } }; blankNode.appendChild(document.createTextNode(wysihtml5.INVISIBLE_SPACE)); blankNode.className = '_wysihtml5-temp-caret-fix'; blankNode.style.display = 'block'; blankNode.style.minWidth = '1px'; blankNode.style.height = '0px'; container.addEventListener('mouseup', placeholderRemover); container.addEventListener('keydown', placeholderRemover); container.addEventListener('touchstart', placeholderRemover); container.addEventListener('focus', placeholderRemover); container.addEventListener('blur', placeholderRemover); container.addEventListener('paste', delayedPlaceholderRemover); container.addEventListener('drop', delayedPlaceholderRemover); container.addEventListener('beforepaste', delayedPlaceholderRemover); return blankNode; } // Should fix the obtained ranges that cannot surrond contents normally to apply changes upon // Being considerate to firefox that sets range start start out of span and end inside on doubleclick initiated selection function expandRangeToSurround(range) { if (range.canSurroundContents()) return; var common = range.commonAncestorContainer, start_depth = getDepth(common, range.startContainer), end_depth = getDepth(common, range.endContainer); while(!range.canSurroundContents()) { // In the following branches, we cannot just decrement the depth variables because the setStartBefore/setEndAfter may move the start or end of the range more than one level relative to ``common``. So we need to recompute the depth. if (start_depth > end_depth) { range.setStartBefore(range.startContainer); start_depth = getDepth(common, range.startContainer); } else { range.setEndAfter(range.endContainer); end_depth = getDepth(common, range.endContainer); } } } wysihtml5.Selection = Base.extend( /** @scope wysihtml5.Selection.prototype */ { constructor: function(editor, contain, unselectableClass) { // Make sure that our external range library is initialized window.rangy.init(); this.editor = editor; this.composer = editor.composer; this.doc = this.composer.doc; this.win = this.composer.win; this.contain = contain; this.unselectableClass = unselectableClass || false; }, /** * Get the current selection as a bookmark to be able to later restore it * * @return {Object} An object that represents the current selection */ getBookmark: function() { var range = this.getRange(); return range && range.cloneRange(); }, /** * Restore a selection retrieved via wysihtml5.Selection.prototype.getBookmark * * @param {Object} bookmark An object that represents the current selection */ setBookmark: function(bookmark) { if (!bookmark) { return; } this.setSelection(bookmark); }, /** * Set the caret in front of the given node * * @param {Object} node The element or text node where to position the caret in front of * @example * selection.setBefore(myElement); */ setBefore: function(node) { var range = rangy.createRange(this.doc); range.setStartBefore(node); range.setEndBefore(node); return this.setSelection(range); }, // Constructs a self removing whitespace (ain absolute positioned span) for placing selection caret when normal methods fail. // Webkit has an issue with placing caret into places where there are no textnodes near by. createTemporaryCaretSpaceAfter: function (node) { var caretPlaceholder = this.doc.createElement('span'), caretPlaceholderText = this.doc.createTextNode(wysihtml5.INVISIBLE_SPACE), placeholderRemover = (function(event) { // Self-destructs the caret and keeps the text inserted into it by user var lastChild; this.contain.removeEventListener('mouseup', placeholderRemover); this.contain.removeEventListener('keydown', keyDownHandler); this.contain.removeEventListener('touchstart', placeholderRemover); this.contain.removeEventListener('focus', placeholderRemover); this.contain.removeEventListener('blur', placeholderRemover); this.contain.removeEventListener('paste', delayedPlaceholderRemover); this.contain.removeEventListener('drop', delayedPlaceholderRemover); this.contain.removeEventListener('beforepaste', delayedPlaceholderRemover); // If user inserted sth it is in the placeholder and sgould be unwrapped and stripped of invisible whitespace hack // Otherwise the wrapper can just be removed if (caretPlaceholder && caretPlaceholder.parentNode) { caretPlaceholder.innerHTML = caretPlaceholder.innerHTML.replace(wysihtml5.INVISIBLE_SPACE_REG_EXP, ""); if ((/[^\s]+/).test(caretPlaceholder.innerHTML)) { lastChild = caretPlaceholder.lastChild; wysihtml5.dom.unwrap(caretPlaceholder); this.setAfter(lastChild); } else { caretPlaceholder.parentNode.removeChild(caretPlaceholder); } } }).bind(this), delayedPlaceholderRemover = function (event) { if (caretPlaceholder && caretPlaceholder.parentNode) { setTimeout(placeholderRemover, 0); } }, keyDownHandler = function(event) { if (event.which !== 8 && event.which !== 91 && event.which !== 17 && (event.which !== 86 || (!event.ctrlKey && !event.metaKey))) { placeholderRemover(); } }; caretPlaceholder.className = '_wysihtml5-temp-caret-fix'; caretPlaceholder.style.position = 'absolute'; caretPlaceholder.style.display = 'block'; caretPlaceholder.style.minWidth = '1px'; caretPlaceholder.style.zIndex = '99999'; caretPlaceholder.appendChild(caretPlaceholderText); node.parentNode.insertBefore(caretPlaceholder, node.nextSibling); this.setBefore(caretPlaceholderText); // Remove the caret fix on any of the following events (some are delayed as content change happens after event) this.contain.addEventListener('mouseup', placeholderRemover); this.contain.addEventListener('keydown', keyDownHandler); this.contain.addEventListener('touchstart', placeholderRemover); this.contain.addEventListener('focus', placeholderRemover); this.contain.addEventListener('blur', placeholderRemover); this.contain.addEventListener('paste', delayedPlaceholderRemover); this.contain.addEventListener('drop', delayedPlaceholderRemover); this.contain.addEventListener('beforepaste', delayedPlaceholderRemover); return caretPlaceholder; }, /** * Set the caret after the given node * * @param {Object} node The element or text node where to position the caret in front of * @example * selection.setBefore(myElement); * callback is an optional parameter accepting a function to execute when selection ahs been set */ setAfter: function(node, notVisual, callback) { var win = this.win, range = rangy.createRange(this.doc), fixWebkitSelection = function() { // Webkit fails to add selection if there are no textnodes in that region // (like an uneditable container at the end of content). var parent = node.parentNode, lastSibling = parent ? parent.childNodes[parent.childNodes.length - 1] : null; if (!sel || (lastSibling === node && node.nodeType === 1 && win.getComputedStyle(node).display === "block")) { if (notVisual) { // If setAfter is used as internal between actions, self-removing caretPlaceholder has simpler implementation // and remove itself in call stack end instead on user interaction var caretPlaceholder = this.doc.createTextNode(wysihtml5.INVISIBLE_SPACE); node.parentNode.insertBefore(caretPlaceholder, node.nextSibling); this.selectNode(caretPlaceholder); setTimeout(function() { if (caretPlaceholder && caretPlaceholder.parentNode) { caretPlaceholder.parentNode.removeChild(caretPlaceholder); } }, 0); } else { this.createTemporaryCaretSpaceAfter(node); } } }.bind(this), sel; range.setStartAfter(node); range.setEndAfter(node); // In IE contenteditable must be focused before we can set selection // thus setting the focus if activeElement is not this composer if (!document.activeElement || document.activeElement !== this.composer.element) { var scrollPos = this.composer.getScrollPos(); this.composer.element.focus(); this.composer.setScrollPos(scrollPos); setTimeout(function() { sel = this.setSelection(range); fixWebkitSelection(); if (callback) { callback(sel); } }.bind(this), 0); } else { sel = this.setSelection(range); fixWebkitSelection(); if (callback) { callback(sel); } } }, /** * Ability to select/mark nodes * * @param {Element} node The node/element to select * @example * selection.selectNode(document.getElementById("my-image")); */ selectNode: function(node, avoidInvisibleSpace) { var range = rangy.createRange(this.doc), isElement = node.nodeType === wysihtml5.ELEMENT_NODE, canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : (node.nodeName !== "IMG"), content = isElement ? node.innerHTML : node.data, isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE), displayStyle = dom.getStyle("display").from(node), isBlockElement = (displayStyle === "block" || displayStyle === "list-item"); if (isEmpty && isElement && canHaveHTML && !avoidInvisibleSpace) { // Make sure that caret is visible in node by inserting a zero width no breaking space try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {} } if (canHaveHTML) { range.selectNodeContents(node); } else { range.selectNode(node); } if (canHaveHTML && isEmpty && isElement) { range.collapse(isBlockElement); } else if (canHaveHTML && isEmpty) { range.setStartAfter(node); range.setEndAfter(node); } this.setSelection(range); }, /** * Get the node which contains the selection * * @param {Boolean} [controlRange] (only IE) Whether it should return the selected ControlRange element when the selection type is a "ControlRange" * @return {Object} The node that contains the caret * @example * var nodeThatContainsCaret = selection.getSelectedNode(); */ getSelectedNode: function(controlRange) { var selection, range; if (controlRange && this.doc.selection && this.doc.selection.type === "Control") { range = this.doc.selection.createRange(); if (range && range.length) { return range.item(0); } } selection = this.getSelection(this.doc); if (selection.focusNode === selection.anchorNode) { return selection.focusNode; } else { range = this.getRange(this.doc); return range ? range.commonAncestorContainer : this.doc.body; } }, fixSelBorders: function() { var range = this.getRange(); expandRangeToSurround(range); this.setSelection(range); }, getSelectedOwnNodes: function(controlRange) { var selection, ranges = this.getOwnRanges(), ownNodes = []; for (var i = 0, maxi = ranges.length; i < maxi; i++) { ownNodes.push(ranges[i].commonAncestorContainer || this.doc.body); } return ownNodes; }, findNodesInSelection: function(nodeTypes) { var ranges = this.getOwnRanges(), nodes = [], curNodes; for (var i = 0, maxi = ranges.length; i < maxi; i++) { curNodes = ranges[i].getNodes([1], function(node) { return wysihtml5.lang.array(nodeTypes).contains(node.nodeName); }); nodes = nodes.concat(curNodes); } return nodes; }, filterElements: function(filter) { var ranges = this.getOwnRanges(), nodes = [], curNodes; for (var i = 0, maxi = ranges.length; i < maxi; i++) { curNodes = ranges[i].getNodes([1], function(element){ return filter(element, ranges[i]); }); nodes = nodes.concat(curNodes); } return nodes; }, containsUneditable: function() { var uneditables = this.getOwnUneditables(), selection = this.getSelection(); for (var i = 0, maxi = uneditables.length; i < maxi; i++) { if (selection.containsNode(uneditables[i])) { return true; } } return false; }, // Deletes selection contents making sure uneditables/unselectables are not partially deleted // Triggers wysihtml5:uneditable:delete custom event on all deleted uneditables if customevents suppoorted deleteContents: function() { var range = this.getRange(), startParent, endParent, uneditables, ev; if (this.unselectableClass) { if ((startParent = wysihtml5.dom.getParentElement(range.startContainer, { query: "." + this.unselectableClass }, false, this.contain))) { range.setStartBefore(startParent); } if ((endParent = wysihtml5.dom.getParentElement(range.endContainer, { query: "." + this.unselectableClass }, false, this.contain))) { range.setEndAfter(endParent); } // If customevents present notify uneditable elements of being deleted uneditables = range.getNodes([1], (function (node) { return wysihtml5.dom.hasClass(node, this.unselectableClass); }).bind(this)); for (var i = uneditables.length; i--;) { try { ev = new CustomEvent("wysihtml5:uneditable:delete"); uneditables[i].dispatchEvent(ev); } catch (err) {} } } range.deleteContents(); this.setSelection(range); }, getPreviousNode: function(node, ignoreEmpty) { var displayStyle; if (!node) { var selection = this.getSelection(); node = selection.anchorNode; } if (node === this.contain) { return false; } var ret = node.previousSibling, parent; if (ret === this.contain) { return false; } if (ret && ret.nodeType !== 3 && ret.nodeType !== 1) { // do not count comments and other node types ret = this.getPreviousNode(ret, ignoreEmpty); } else if (ret && ret.nodeType === 3 && (/^\s*$/).test(ret.textContent)) { // do not count empty textnodes as previous nodes ret = this.getPreviousNode(ret, ignoreEmpty); } else if (ignoreEmpty && ret && ret.nodeType === 1) { // Do not count empty nodes if param set. // Contenteditable tends to bypass and delete these silently when deleting with caret when element is inline-like displayStyle = wysihtml5.dom.getStyle("display").from(ret); if ( !wysihtml5.lang.array(["BR", "HR", "IMG"]).contains(ret.nodeName) && !wysihtml5.lang.array(["block", "inline-block", "flex", "list-item", "table"]).contains(displayStyle) && (/^[\s]*$/).test(ret.innerHTML) ) { ret = this.getPreviousNode(ret, ignoreEmpty); } } else if (!ret && node !== this.contain) { parent = node.parentNode; if (parent !== this.contain) { ret = this.getPreviousNode(parent, ignoreEmpty); } } return (ret !== this.contain) ? ret : false; }, getSelectionParentsByTag: function(tagName) { var nodes = this.getSelectedOwnNodes(), curEl, parents = []; for (var i = 0, maxi = nodes.length; i < maxi; i++) { curEl = (nodes[i].nodeName && nodes[i].nodeName === 'LI') ? nodes[i] : wysihtml5.dom.getParentElement(nodes[i], { query: 'li'}, false, this.contain); if (curEl) { parents.push(curEl); } } return (parents.length) ? parents : null; }, getRangeToNodeEnd: function() { if (this.isCollapsed()) { var range = this.getRange(), sNode = range.startContainer, pos = range.startOffset, lastR = rangy.createRange(this.doc); lastR.selectNodeContents(sNode); lastR.setStart(sNode, pos); return lastR; } }, caretIsLastInSelection: function() { var r = rangy.createRange(this.doc), s = this.getSelection(), endc = this.getRangeToNodeEnd().cloneContents(), endtxt = endc.textContent; return (/^\s*$/).test(endtxt); }, caretIsFirstInSelection: function() { var r = rangy.createRange(this.doc), s = this.getSelection(), range = this.getRange(), startNode = range.startContainer; if (startNode) { if (startNode.nodeType === wysihtml5.TEXT_NODE) { return this.isCollapsed() && (startNode.nodeType === wysihtml5.TEXT_NODE && (/^\s*$/).test(startNode.data.substr(0,range.startOffset))); } else { r.selectNodeContents(this.getRange().commonAncestorContainer); r.collapse(true); return (this.isCollapsed() && (r.startContainer === s.anchorNode || r.endContainer === s.anchorNode) && r.startOffset === s.anchorOffset); } } }, caretIsInTheBeginnig: function(ofNode) { var selection = this.getSelection(), node = selection.anchorNode, offset = selection.anchorOffset; if (ofNode && node) { return (offset === 0 && (node.nodeName && node.nodeName === ofNode.toUpperCase() || wysihtml5.dom.getParentElement(node.parentNode, { query: ofNode }, 1))); } else if (node) { return (offset === 0 && !this.getPreviousNode(node, true)); } }, // Returns object describing node/text before selection // If includePrevLeaves is true returns also previous last leaf child if selection is in the beginning of current node getBeforeSelection: function(includePrevLeaves) { var sel = this.getSelection(), startNode = (sel.isBackwards()) ? sel.focusNode : sel.anchorNode, startOffset = (sel.isBackwards()) ? sel.focusOffset : sel.anchorOffset, rng = this.createRange(), endNode, inTmpCaret; // Escape temproray helper nodes if selection in them inTmpCaret = wysihtml5.dom.getParentElement(startNode, { query: '._wysihtml5-temp-caret-fix' }, 1); if (inTmpCaret) { startNode = inTmpCaret.parentNode; startOffset = Array.prototype.indexOf.call(startNode.childNodes, inTmpCaret); } if (startNode) { if (startOffset > 0) { if (startNode.nodeType === 3) { rng.setStart(startNode, 0); rng.setEnd(startNode, startOffset); return { type: "text", range: rng, offset : startOffset, node: startNode }; } else { rng.setStartBefore(startNode.childNodes[0]); endNode = startNode.childNodes[startOffset - 1]; rng.setEndAfter(endNode); return { type: "element", range: rng, offset : startOffset, node: endNode }; } } else { rng.setStartAndEnd(startNode, 0); if (includePrevLeaves) { var prevNode = this.getPreviousNode(startNode, true), prevLeaf = null; if(prevNode) { if (prevNode.nodeType === 1 && wysihtml5.dom.hasClass(prevNode, this.unselectableClass)) { prevLeaf = prevNode; } else { prevLeaf = wysihtml5.dom.domNode(prevNode).lastLeafNode(); } } if (prevLeaf) { return { type: "leafnode", range: rng, offset : startOffset, node: prevLeaf }; } } return { type: "none", range: rng, offset : startOffset, node: startNode }; } } return null; }, // TODO: Figure out a method from following 2 that would work universally executeAndRestoreRangy: function(method, restoreScrollPosition) { var sel = rangy.saveSelection(this.win); if (!sel) { method(); } else { try { method(); } catch(e) { setTimeout(function() { throw e; }, 0); } } rangy.restoreSelection(sel); }, // TODO: has problems in chrome 12. investigate block level and uneditable area inbetween executeAndRestore: function(method, restoreScrollPosition) { var body = this.doc.body, oldScrollTop = restoreScrollPosition && body.scrollTop, oldScrollLeft = restoreScrollPosition && body.scrollLeft, className = "_wysihtml5-temp-placeholder", placeholderHtml = '<span class="' + className + '">' + wysihtml5.INVISIBLE_SPACE + '</span>', range = this.getRange(true), caretPlaceholder, newCaretPlaceholder, nextSibling, prevSibling, node, node2, range2, newRange; // Nothing selected, execute and say goodbye if (!range) { method(body, body); return; } if (!range.collapsed) { range2 = range.cloneRange(); node2 = range2.createContextualFragment(placeholderHtml); range2.collapse(false); range2.insertNode(node2); range2.detach(); } node = range.createContextualFragment(placeholderHtml); range.insertNode(node); if (node2) { caretPlaceholder = this.contain.querySelectorAll("." + className); range.setStartBefore(caretPlaceholder[0]); range.setEndAfter(caretPlaceholder[caretPlaceholder.length -1]); } this.setSelection(range); // Make sure that a potential error doesn't cause our placeholder element to be left as a placeholder try { method(range.startContainer, range.endContainer); } catch(e) { setTimeout(function() { throw e; }, 0); } caretPlaceholder = this.contain.querySelectorAll("." + className); if (caretPlaceholder && caretPlaceholder.length) { newRange = rangy.createRange(this.doc); nextSibling = caretPlaceholder[0].nextSibling; if (caretPlaceholder.length > 1) { prevSibling = caretPlaceholder[caretPlaceholder.length -1].previousSibling; } if (prevSibling && nextSibling) { newRange.setStartBefore(nextSibling); newRange.setEndAfter(prevSibling); } else { newCaretPlaceholder = this.doc.createTextNode(wysihtml5.INVISIBLE_SPACE); dom.insert(newCaretPlaceholder).after(caretPlaceholder[0]); newRange.setStartBefore(newCaretPlaceholder); newRange.setEndAfter(newCaretPlaceholder); } this.setSelection(newRange); for (var i = caretPlaceholder.length; i--;) { caretPlaceholder[i].parentNode.removeChild(caretPlaceholder[i]); } } else { // fallback for when all hell breaks loose this.contain.focus(); } if (restoreScrollPosition) { body.scrollTop = oldScrollTop; body.scrollLeft = oldScrollLeft; } // Remove it again, just to make sure that the placeholder is definitely out of the dom tree try { caretPlaceholder.parentNode.removeChild(caretPlaceholder); } catch(e2) {} }, set: function(node, offset) { var newRange = rangy.createRange(this.doc); newRange.setStart(node, offset || 0); this.setSelection(newRange); }, /** * Insert html at the caret position and move the cursor after the inserted html * * @param {String} html HTML string to insert * @example * selection.insertHTML("<p>foobar</p>"); */ insertHTML: function(html) { var range = rangy.createRange(this.doc), node = this.doc.createElement('DIV'), fragment = this.doc.createDocumentFragment(), lastChild; node.innerHTML = html; lastChild = node.lastChild; while (node.firstChild) { fragment.appendChild(node.firstChild); } this.insertNode(fragment); if (lastChild) { this.setAfter(lastChild); } }, /** * Insert a node at the caret position and move the cursor behind it * * @param {Object} node HTML string to insert * @example * selection.insertNode(document.createTextNode("foobar")); */ insertNode: function(node) { var range = this.getRange(); if (range) { range.insertNode(node); } }, canAppendChild: function (node) { var anchorNode, anchorNodeTagNameLower, voidElements = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"], range = this.getRange(); anchorNode = node || range.startContainer; if (anchorNode) { anchorNodeTagNameLower = (anchorNode.tagName || anchorNode.nodeName).toLowerCase(); } return voidElements.indexOf(anchorNodeTagNameLower) === -1; }, splitElementAtCaret: function (element, insertNode) { var sel = this.getSelection(), range, contentAfterRangeStart, firstChild, lastChild, childNodes; if (sel.rangeCount > 0) { range = sel.getRangeAt(0).cloneRange(); // Create a copy of the selection range to work with range.setEndAfter(element); // Place the end of the range after the element contentAfterRangeStart = range.extractContents(); // Extract the contents of the element after the caret into a fragment childNodes = contentAfterRangeStart.childNodes; // Empty elements are cleaned up from extracted content for (var i = childNodes.length; i --;) { if (!wysihtml5.dom.domNode(childNodes[i]).is.visible()) { contentAfterRangeStart.removeChild(childNodes[i]); } } element.parentNode.insertBefore(contentAfterRangeStart, element.nextSibling); if (insertNode) { firstChild = insertNode.firstChild || insertNode; lastChild = insertNode.lastChild || insertNode; element.parentNode.insertBefore(insertNode, element.nextSibling); // Select inserted node contents if (firstChild && lastChild) { range.setStartBefore(firstChild); range.setEndAfter(lastChild); this.setSelection(range); } } else { range.setStartAfter(element); range.setEndAfter(element); } if (!wysihtml5.dom.domNode(element).is.visible()) { if (wysihtml5.dom.getTextContent(element) === '') { element.parentNode.removeChild(element); } else { element.parentNode.replaceChild(this.doc.createTextNode(" "), element); } } } }, /** * Wraps current selection with the given node * * @param {Object} node The node to surround the selected elements with */ surround: function(nodeOptions) { var ranges = this.getOwnRanges(), node, nodes = []; if (ranges.length == 0) { return nodes; } for (var i = ranges.length; i--;) { node = this.doc.createElement(nodeOptions.nodeName); nodes.push(node); if (nodeOptions.className) { node.className = nodeOptions.className; } if (nodeOptions.cssStyle) { node.setAttribute('style', nodeOptions.cssStyle); } try { // This only works when the range boundaries are not overlapping other elements ranges[i].surroundContents(node); this.selectNode(node); } catch(e) { // fallback node.appendChild(ranges[i].extractContents()); ranges[i].insertNode(node); } } return nodes; }, deblockAndSurround: function(nodeOptions) { var tempElement = this.doc.createElement('div'), range = rangy.createRange(this.doc), tempDivElements, tempElements, firstChild; tempElement.className = nodeOptions.className; this.composer.commands.exec("formatBlock", nodeOptions); tempDivElements = this.contain.querySelectorAll("." + nodeOptions.className); if (tempDivElements[0]) { tempDivElements[0].parentNode.insertBefore(tempElement, tempDivElements[0]); range.setStartBefore(tempDivElements[0]); range.setEndAfter(tempDivElements[tempDivElements.length - 1]); tempElements = range.extractContents(); while (tempElements.firstChild) { firstChild = tempElements.firstChild; if (firstChild.nodeType == 1 && wysihtml5.dom.hasClass(firstChild, nodeOptions.className)) { while (firstChild.firstChild) { tempElement.appendChild(firstChild.firstChild); } if (firstChild.nodeName !== "BR") { tempElement.appendChild(this.doc.createElement('br')); } tempElements.removeChild(firstChild); } else { tempElement.appendChild(firstChild); } } } else { tempElement = null; } return tempElement; }, /** * Scroll the current caret position into the view * FIXME: This is a bit hacky, there might be a smarter way of doing this * * @example * selection.scrollIntoView(); */ scrollIntoView: function() { var doc = this.doc, tolerance = 5, // px hasScrollBars = doc.documentElement.scrollHeight > doc.documentElement.offsetHeight, tempElement = doc._wysihtml5ScrollIntoViewElement = doc._wysihtml5ScrollIntoViewElement || (function() { var element = doc.createElement("span"); // The element needs content in order to be able to calculate it's position properly element.innerHTML = wysihtml5.INVISIBLE_SPACE; return element; })(), offsetTop; if (hasScrollBars) { this.insertNode(tempElement); offsetTop = _getCumulativeOffsetTop(tempElement); tempElement.parentNode.removeChild(tempElement); if (offsetTop >= (doc.body.scrollTop + doc.documentElement.offsetHeight - tolerance)) { doc.body.scrollTop = offsetTop; } } }, /** * Select line where the caret is in */ selectLine: function() { if (wysihtml5.browser.supportsSelectionModify()) { this._selectLine_W3C(); } else if (this.doc.selection) { this._selectLine_MSIE(); } }, /** * See https://developer.mozilla.org/en/DOM/Selection/modify */ _selectLine_W3C: function() { var selection = this.win.getSelection(); selection.modify("move", "left", "lineboundary"); selection.modify("extend", "right", "lineboundary"); }, // collapses selection to current line beginning or end toLineBoundary: function (location, collapse) { collapse = (typeof collapse === 'undefined') ? false : collapse; if (wysihtml5.browser.supportsSelectionModify()) { var selection = this.win.getSelection(); selection.modify("extend", location, "lineboundary"); if (collapse) { if (location === "left") { selection.collapseToStart(); } else if (location === "right") { selection.collapseToEnd(); } } } }, _selectLine_MSIE: function() { var range = this.doc.selection.createRange(), rangeTop = range.boundingTop, scrollWidth = this.doc.body.scrollWidth, rangeBottom, rangeEnd, measureNode, i, j; if (!range.moveToPoint) { return; } if (rangeTop === 0) { // Don't know why, but when the selection ends at the end of a line // range.boundingTop is 0 measureNode = this.doc.createElement("span"); this.insertNode(measureNode); rangeTop = measureNode.offsetTop; measureNode.parentNode.removeChild(measureNode); } rangeTop += 1; for (i=-10; i<scrollWidth; i+=2) { try { range.moveToPoint(i, rangeTop); break; } catch(e1) {} } // Investigate the following in order to handle multi line selections // rangeBottom = rangeTop + (rangeHeight ? (rangeHeight - 1) : 0); rangeBottom = rangeTop; rangeEnd = this.doc.selection.createRange(); for (j=scrollWidth; j>=0; j--) { try { rangeEnd.moveToPoint(j, rangeBottom); break; } catch(e2) {} } range.setEndPoint("EndToEnd", rangeEnd); range.select(); }, getText: function() { var selection = this.getSelection(); return selection ? selection.toString() : ""; }, getNodes: function(nodeType, filter) { var range = this.getRange(); if (range) { return range.getNodes(Array.isArray(nodeType) ? nodeType : [nodeType], filter); } else { return []; } }, // Gets all the elements in selection with nodeType // Ignores the elements not belonging to current editable area // If filter is defined nodes must pass the filter function with true to be included in list getOwnNodes: function(nodeType, filter, splitBounds) { var ranges = this.getOwnRanges(), nodes = []; for (var r = 0, rmax = ranges.length; r < rmax; r++) { if (ranges[r]) { if (splitBounds) { ranges[r].splitBoundaries(); } nodes = nodes.concat(ranges[r].getNodes(Array.isArray(nodeType) ? nodeType : [nodeType], filter)); } } return nodes; }, fixRangeOverflow: function(range) { if (this.contain && this.contain.firstChild && range) { var containment = range.compareNode(this.contain); if (containment !== 2) { if (containment === 1) { range.setStartBefore(this.contain.firstChild); } if (containment === 0) { range.setEndAfter(this.contain.lastChild); } if (containment === 3) { range.setStartBefore(this.contain.firstChild); range.setEndAfter(this.contain.lastChild); } } else if (this._detectInlineRangeProblems(range)) { var previousElementSibling = range.endContainer.previousElementSibling; if (previousElementSibling) { range.setEnd(previousElementSibling, this._endOffsetForNode(previousElementSibling)); } } } }, _endOffsetForNode: function(node) { var range = document.createRange(); range.selectNodeContents(node); return range.endOffset; }, _detectInlineRangeProblems: function(range) { var position = dom.compareDocumentPosition(range.startContainer, range.endContainer); return ( range.endOffset == 0 && position & 4 //Node.DOCUMENT_POSITION_FOLLOWING ); }, getRange: function(dontFix) { var selection = this.getSelection(), range = selection && selection.rangeCount && selection.getRangeAt(0); if (dontFix !== true) { this.fixRangeOverflow(range); } return range; }, getOwnUneditables: function() { var allUneditables = dom.query(this.contain, '.' + this.unselectableClass), deepUneditables = dom.query(allUneditables, '.' + this.unselectableClass); return wysihtml5.lang.array(allUneditables).without(deepUneditables); }, // Returns an array of ranges that belong only to this editable // Needed as uneditable block in contenteditabel can split range into pieces // If manipulating content reverse loop is usually needed as manipulation can shift subsequent ranges getOwnRanges: function() { var ranges = [], r = this.getRange(), tmpRanges; if (r) { ranges.push(r); } if (this.unselectableClass && this.contain && r) { var uneditables = this.getOwnUneditables(), tmpRange; if (uneditables.length > 0) { for (var i = 0, imax = uneditables.length; i < imax; i++) { tmpRanges = []; for (var j = 0, jmax = ranges.length; j < jmax; j++) { if (ranges[j]) { switch (ranges[j].compareNode(uneditables[i])) { case 2: // all selection inside uneditable. remove break; case 3: //section begins before and ends after uneditable. spilt tmpRange = ranges[j].cloneRange(); tmpRange.setEndBefore(uneditables[i]); tmpRanges.push(tmpRange); tmpRange = ranges[j].cloneRange(); tmpRange.setStartAfter(uneditables[i]); tmpRanges.push(tmpRange); break; default: // in all other cases uneditable does not touch selection. dont modify tmpRanges.push(ranges[j]); } } ranges = tmpRanges; } } } } return ranges; }, getSelection: function() { return rangy.getSelection(this.win); }, // Sets selection in document to a given range // Set selection method detects if it fails to set any selection in document and returns null on fail // (especially needed in webkit where some ranges just can not create selection for no reason) setSelection: function(range) { var selection = rangy.getSelection(this.win); selection.setSingleRange(range); return (selection && selection.anchorNode && selection.focusNode) ? selection : null; }, // Webkit has an ancient error of not selecting all contents when uneditable block element is first or last in editable area selectAll: function() { var range = this.createRange(), composer = this.composer, that = this, blankEndNode = getWebkitSelectionFixNode(this.composer.element), blankStartNode = getWebkitSelectionFixNode(this.composer.element), s; var doSelect = function() { range.setStart(composer.element, 0); range.setEnd(composer.element, composer.element.childNodes.length); s = that.setSelection(range); }; var notSelected = function() { return !s || (s.nativeSelection && s.nativeSelection.type && (s.nativeSelection.type === "Caret" || s.nativeSelection.type === "None")); } wysihtml5.dom.removeInvisibleSpaces(this.composer.element); doSelect(); if (this.composer.element.firstChild && notSelected()) { // Try fixing end this.composer.element.appendChild(blankEndNode); doSelect(); if (notSelected()) { // Remove end fix blankEndNode.parentNode.removeChild(blankEndNode); // Try fixing beginning this.composer.element.insertBefore(blankStartNode, this.composer.element.firstChild); doSelect(); if (notSelected()) { // Try fixing both this.composer.element.appendChild(blankEndNode); doSelect(); } } } }, createRange: function() { return rangy.createRange(this.doc); }, isCollapsed: function() { return this.getSelection().isCollapsed; }, getHtml: function() { return this.getSelection().toHtml(); }, getPlainText: function () { return this.getSelection().toString(); }, isEndToEndInNode: function(nodeNames) { var range = this.getRange(), parentElement = range.commonAncestorContainer, startNode = range.startContainer, endNode = range.endContainer; if (parentElement.nodeType === wysihtml5.TEXT_NODE) { parentElement = parentElement.parentNode; } if (startNode.nodeType === wysihtml5.TEXT_NODE && !(/^\s*$/).test(startNode.data.substr(range.startOffset))) { return false; } if (endNode.nodeType === wysihtml5.TEXT_NODE && !(/^\s*$/).test(endNode.data.substr(range.endOffset))) { return false; } while (startNode && startNode !== parentElement) { if (startNode.nodeType !== wysihtml5.TEXT_NODE && !wysihtml5.dom.contains(parentElement, startNode)) { return false; } if (wysihtml5.dom.domNode(startNode).prev({ignoreBlankTexts: true})) { return false; } startNode = startNode.parentNode; } while (endNode && endNode !== parentElement) { if (endNode.nodeType !== wysihtml5.TEXT_NODE && !wysihtml5.dom.contains(parentElement, endNode)) { return false; } if (wysihtml5.dom.domNode(endNode).next({ignoreBlankTexts: true})) { return false; } endNode = endNode.parentNode; } return (wysihtml5.lang.array(nodeNames).contains(parentElement.nodeName)) ? parentElement : false; }, isInThisEditable: function() { var sel = this.getSelection(), fnode = sel.focusNode, anode = sel.anchorNode; // In IE node contains will not work for textnodes, thus taking parentNode if (fnode && fnode.nodeType !== 1) { fnode = fnode.parentNode; } if (anode && anode.nodeType !== 1) { anode = anode.parentNode; } return anode && fnode && (wysihtml5.dom.contains(this.composer.element, fnode) || this.composer.element === fnode) && (wysihtml5.dom.contains(this.composer.element, anode) || this.composer.element === anode); }, deselect: function() { var sel = this.getSelection(); sel && sel.removeAllRanges(); } }); })(wysihtml5); ;/** * Inspired by the rangy CSS Applier module written by Tim Down and licensed under the MIT license. * http://code.google.com/p/rangy/ * * changed in order to be able ... * - to use custom tags * - to detect and replace similar css classes via reg exp */ (function(wysihtml5, rangy) { var defaultTagName = "span"; var REG_EXP_WHITE_SPACE = /\s+/g; function hasClass(el, cssClass, regExp) { if (!el.className) { return false; } var matchingClassNames = el.className.match(regExp) || []; return matchingClassNames[matchingClassNames.length - 1] === cssClass; } function hasStyleAttr(el, regExp) { if (!el.getAttribute || !el.getAttribute('style')) { return false; } var matchingStyles = el.getAttribute('style').match(regExp); return (el.getAttribute('style').match(regExp)) ? true : false; } function addStyle(el, cssStyle, regExp) { if (el.getAttribute('style')) { removeStyle(el, regExp); if (el.getAttribute('style') && !(/^\s*$/).test(el.getAttribute('style'))) { el.setAttribute('style', cssStyle + ";" + el.getAttribute('style')); } else { el.setAttribute('style', cssStyle); } } else { el.setAttribute('style', cssStyle); } } function addClass(el, cssClass, regExp) { if (el.className) { removeClass(el, regExp); el.className += " " + cssClass; } else { el.className = cssClass; } } function removeClass(el, regExp) { if (el.className) { el.className = el.className.replace(regExp, ""); } } function removeStyle(el, regExp) { var s, s2 = []; if (el.getAttribute('style')) { s = el.getAttribute('style').split(';'); for (var i = s.length; i--;) { if (!s[i].match(regExp) && !(/^\s*$/).test(s[i])) { s2.push(s[i]); } } if (s2.length) { el.setAttribute('style', s2.join(';')); } else { el.removeAttribute('style'); } } } function getMatchingStyleRegexp(el, style) { var regexes = [], sSplit = style.split(';'), elStyle = el.getAttribute('style'); if (elStyle) { elStyle = elStyle.replace(/\s/gi, '').toLowerCase(); regexes.push(new RegExp("(^|\\s|;)" + style.replace(/\s/gi, '').replace(/([\(\)])/gi, "\\$1").toLowerCase().replace(";", ";?").replace(/rgb\\\((\d+),(\d+),(\d+)\\\)/gi, "\\s?rgb\\($1,\\s?$2,\\s?$3\\)"), "gi")); for (var i = sSplit.length; i-- > 0;) { if (!(/^\s*$/).test(sSplit[i])) { regexes.push(new RegExp("(^|\\s|;)" + sSplit[i].replace(/\s/gi, '').replace(/([\(\)])/gi, "\\$1").toLowerCase().replace(";", ";?").replace(/rgb\\\((\d+),(\d+),(\d+)\\\)/gi, "\\s?rgb\\($1,\\s?$2,\\s?$3\\)"), "gi")); } } for (var j = 0, jmax = regexes.length; j < jmax; j++) { if (elStyle.match(regexes[j])) { return regexes[j]; } } } return false; } function isMatchingAllready(node, tags, style, className) { if (style) { return getMatchingStyleRegexp(node, style); } else if (className) { return wysihtml5.dom.hasClass(node, className); } else { return rangy.dom.arrayContains(tags, node.tagName.toLowerCase()); } } function areMatchingAllready(nodes, tags, style, className) { for (var i = nodes.length; i--;) { if (!isMatchingAllready(nodes[i], tags, style, className)) { return false; } } return nodes.length ? true : false; } function removeOrChangeStyle(el, style, regExp) { var exactRegex = getMatchingStyleRegexp(el, style); if (exactRegex) { // adding same style value on property again removes style removeStyle(el, exactRegex); return "remove"; } else { // adding new style value changes value addStyle(el, style, regExp); return "change"; } } function hasSameClasses(el1, el2) { return el1.className.replace(REG_EXP_WHITE_SPACE, " ") == el2.className.replace(REG_EXP_WHITE_SPACE, " "); } function replaceWithOwnChildren(el) { var parent = el.parentNode; while (el.firstChild) { parent.insertBefore(el.firstChild, el); } parent.removeChild(el); } function elementsHaveSameNonClassAttributes(el1, el2) { if (el1.attributes.length != el2.attributes.length) { return false; } for (var i = 0, len = el1.attributes.length, attr1, attr2, name; i < len; ++i) { attr1 = el1.attributes[i]; name = attr1.name; if (name != "class") { attr2 = el2.attributes.getNamedItem(name); if (attr1.specified != attr2.specified) { return false; } if (attr1.specified && attr1.nodeValue !== attr2.nodeValue) { return false; } } } return true; } function isSplitPoint(node, offset) { if (rangy.dom.isCharacterDataNode(node)) { if (offset == 0) { return !!node.previousSibling; } else if (offset == node.length) { return !!node.nextSibling; } else { return true; } } return offset > 0 && offset < node.childNodes.length; } function splitNodeAt(node, descendantNode, descendantOffset, container) { var newNode; if (rangy.dom.isCharacterDataNode(descendantNode)) { if (descendantOffset == 0) { descendantOffset = rangy.dom.getNodeIndex(descendantNode); descendantNode = descendantNode.parentNode; } else if (descendantOffset == descendantNode.length) { descendantOffset = rangy.dom.getNodeIndex(descendantNode) + 1; descendantNode = descendantNode.parentNode; } else { newNode = rangy.dom.splitDataNode(descendantNode, descendantOffset); } } if (!newNode) { if (!container || descendantNode !== container) { newNode = descendantNode.cloneNode(false); if (newNode.id) { newNode.removeAttribute("id"); } var child; while ((child = descendantNode.childNodes[descendantOffset])) { newNode.appendChild(child); } rangy.dom.insertAfter(newNode, descendantNode); } } return (descendantNode == node) ? newNode : splitNodeAt(node, newNode.parentNode, rangy.dom.getNodeIndex(newNode), container); } function Merge(firstNode) { this.isElementMerge = (firstNode.nodeType == wysihtml5.ELEMENT_NODE); this.firstTextNode = this.isElementMerge ? firstNode.lastChild : firstNode; this.textNodes = [this.firstTextNode]; } Merge.prototype = { doMerge: function() { var textBits = [], textNode, parent, text; for (var i = 0, len = this.textNodes.length; i < len; ++i) { textNode = this.textNodes[i]; parent = textNode.parentNode; textBits[i] = textNode.data; if (i) { parent.removeChild(textNode); if (!parent.hasChildNodes()) { parent.parentNode.removeChild(parent); } } } this.firstTextNode.data = text = textBits.join(""); return text; }, getLength: function() { var i = this.textNodes.length, len = 0; while (i--) { len += this.textNodes[i].length; } return len; }, toString: function() { var textBits = []; for (var i = 0, len = this.textNodes.length; i < len; ++i) { textBits[i] = "'" + this.textNodes[i].data + "'"; } return "[Merge(" + textBits.join(",") + ")]"; } }; function HTMLApplier(tagNames, cssClass, similarClassRegExp, normalize, cssStyle, similarStyleRegExp, container) { this.tagNames = tagNames || [defaultTagName]; this.cssClass = cssClass || ((cssClass === false) ? false : ""); this.similarClassRegExp = similarClassRegExp; this.cssStyle = cssStyle || ""; this.similarStyleRegExp = similarStyleRegExp; this.normalize = normalize; this.applyToAnyTagName = false; this.container = container; } HTMLApplier.prototype = { getAncestorWithClass: function(node) { var cssClassMatch; while (node) { cssClassMatch = this.cssClass ? hasClass(node, this.cssClass, this.similarClassRegExp) : (this.cssStyle !== "") ? false : true; if (node.nodeType == wysihtml5.ELEMENT_NODE && node.getAttribute("contenteditable") != "false" && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssClassMatch) { return node; } node = node.parentNode; } return false; }, // returns parents of node with given style attribute getAncestorWithStyle: function(node) { var cssStyleMatch; while (node) { cssStyleMatch = this.cssStyle ? hasStyleAttr(node, this.similarStyleRegExp) : false; if (node.nodeType == wysihtml5.ELEMENT_NODE && node.getAttribute("contenteditable") != "false" && rangy.dom.arrayContains(this.tagNames, node.tagName.toLowerCase()) && cssStyleMatch) { return node; } node = node.parentNode; } return false; }, getMatchingAncestor: function(node) { var ancestor = this.getAncestorWithClass(node), matchType = false; if (!ancestor) { ancestor = this.getAncestorWithStyle(node); if (ancestor) { matchType = "style"; } } else { if (this.cssStyle) { matchType = "class"; } } return { "element": ancestor, "type": matchType }; }, // Normalizes nodes after applying a CSS class to a Range. postApply: function(textNodes, range) { var firstNode = textNodes[0], lastNode = textNodes[textNodes.length - 1]; var merges = [], currentMerge; var rangeStartNode = firstNode, rangeEndNode = lastNode; var rangeStartOffset = 0, rangeEndOffset = lastNode.length; var textNode, precedingTextNode; for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; precedingTextNode = null; if (textNode && textNode.parentNode) { precedingTextNode = this.getAdjacentMergeableTextNode(textNode.parentNode, false); } if (precedingTextNode) { if (!currentMerge) { currentMerge = new Merge(precedingTextNode); merges.push(currentMerge); } currentMerge.textNodes.push(textNode); if (textNode === firstNode) { rangeStartNode = currentMerge.firstTextNode; rangeStartOffset = rangeStartNode.length; } if (textNode === lastNode) { rangeEndNode = currentMerge.firstTextNode; rangeEndOffset = currentMerge.getLength(); } } else { currentMerge = null; } } // Test whether the first node after the range needs merging if(lastNode && lastNode.parentNode) { var nextTextNode = this.getAdjacentMergeableTextNode(lastNode.parentNode, true); if (nextTextNode) { if (!currentMerge) { currentMerge = new Merge(lastNode); merges.push(currentMerge); } currentMerge.textNodes.push(nextTextNode); } } // Do the merges if (merges.length) { for (i = 0, len = merges.length; i < len; ++i) { merges[i].doMerge(); } // Set the range boundaries range.setStart(rangeStartNode, rangeStartOffset); range.setEnd(rangeEndNode, rangeEndOffset); } }, getAdjacentMergeableTextNode: function(node, forward) { var isTextNode = (node.nodeType == wysihtml5.TEXT_NODE); var el = isTextNode ? node.parentNode : node; var adjacentNode; var propName = forward ? "nextSibling" : "previousSibling"; if (isTextNode) { // Can merge if the node's previous/next sibling is a text node adjacentNode = node[propName]; if (adjacentNode && adjacentNode.nodeType == wysihtml5.TEXT_NODE) { return adjacentNode; } } else { // Compare element with its sibling adjacentNode = el[propName]; if (adjacentNode && this.areElementsMergeable(node, adjacentNode)) { return adjacentNode[forward ? "firstChild" : "lastChild"]; } } return null; }, areElementsMergeable: function(el1, el2) { return rangy.dom.arrayContains(this.tagNames, (el1.tagName || "").toLowerCase()) && rangy.dom.arrayContains(this.tagNames, (el2.tagName || "").toLowerCase()) && hasSameClasses(el1, el2) && elementsHaveSameNonClassAttributes(el1, el2); }, createContainer: function(doc) { var el = doc.createElement(this.tagNames[0]); if (this.cssClass) { el.className = this.cssClass; } if (this.cssStyle) { el.setAttribute('style', this.cssStyle); } return el; }, applyToTextNode: function(textNode) { var parent = textNode.parentNode; if (parent.childNodes.length == 1 && rangy.dom.arrayContains(this.tagNames, parent.tagName.toLowerCase())) { if (this.cssClass) { addClass(parent, this.cssClass, this.similarClassRegExp); } if (this.cssStyle) { addStyle(parent, this.cssStyle, this.similarStyleRegExp); } } else { var el = this.createContainer(rangy.dom.getDocument(textNode)); textNode.parentNode.insertBefore(el, textNode); el.appendChild(textNode); } }, isRemovable: function(el) { return rangy.dom.arrayContains(this.tagNames, el.tagName.toLowerCase()) && wysihtml5.lang.string(el.className).trim() === "" && ( !el.getAttribute('style') || wysihtml5.lang.string(el.getAttribute('style')).trim() === "" ); }, undoToTextNode: function(textNode, range, ancestorWithClass, ancestorWithStyle) { var styleMode = (ancestorWithClass) ? false : true, ancestor = ancestorWithClass || ancestorWithStyle, styleChanged = false; if (!range.containsNode(ancestor)) { // Split out the portion of the ancestor from which we can remove the CSS class var ancestorRange = range.cloneRange(); ancestorRange.selectNode(ancestor); if (ancestorRange.isPointInRange(range.endContainer, range.endOffset) && isSplitPoint(range.endContainer, range.endOffset)) { splitNodeAt(ancestor, range.endContainer, range.endOffset, this.container); range.setEndAfter(ancestor); } if (ancestorRange.isPointInRange(range.startContainer, range.startOffset) && isSplitPoint(range.startContainer, range.startOffset)) { ancestor = splitNodeAt(ancestor, range.startContainer, range.startOffset, this.container); } } if (!styleMode && this.similarClassRegExp) { removeClass(ancestor, this.similarClassRegExp); } if (styleMode && this.similarStyleRegExp) { styleChanged = (removeOrChangeStyle(ancestor, this.cssStyle, this.similarStyleRegExp) === "change"); } if (this.isRemovable(ancestor) && !styleChanged) { replaceWithOwnChildren(ancestor); } }, applyToRange: function(range) { var textNodes; for (var ri = range.length; ri--;) { textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); if (!textNodes.length) { try { var node = this.createContainer(range[ri].endContainer.ownerDocument); range[ri].surroundContents(node); this.selectNode(range[ri], node); return; } catch(e) {} } range[ri].splitBoundaries(); textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); if (textNodes.length) { var textNode; for (var i = 0, len = textNodes.length; i < len; ++i) { textNode = textNodes[i]; if (!this.getMatchingAncestor(textNode).element) { this.applyToTextNode(textNode); } } range[ri].setStart(textNodes[0], 0); textNode = textNodes[textNodes.length - 1]; range[ri].setEnd(textNode, textNode.length); if (this.normalize) { this.postApply(textNodes, range[ri]); } } } }, undoToRange: function(range) { var textNodes, textNode, ancestorWithClass, ancestorWithStyle, ancestor; for (var ri = range.length; ri--;) { textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); if (textNodes.length) { range[ri].splitBoundaries(); textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); } else { var doc = range[ri].endContainer.ownerDocument, node = doc.createTextNode(wysihtml5.INVISIBLE_SPACE); range[ri].insertNode(node); range[ri].selectNode(node); textNodes = [node]; } for (var i = 0, len = textNodes.length; i < len; ++i) { if (range[ri].isValid()) { textNode = textNodes[i]; ancestor = this.getMatchingAncestor(textNode); if (ancestor.type === "style") { this.undoToTextNode(textNode, range[ri], false, ancestor.element); } else if (ancestor.element) { this.undoToTextNode(textNode, range[ri], ancestor.element); } } } if (len == 1) { this.selectNode(range[ri], textNodes[0]); } else { range[ri].setStart(textNodes[0], 0); textNode = textNodes[textNodes.length - 1]; range[ri].setEnd(textNode, textNode.length); if (this.normalize) { this.postApply(textNodes, range[ri]); } } } }, selectNode: function(range, node) { var isElement = node.nodeType === wysihtml5.ELEMENT_NODE, canHaveHTML = "canHaveHTML" in node ? node.canHaveHTML : true, content = isElement ? node.innerHTML : node.data, isEmpty = (content === "" || content === wysihtml5.INVISIBLE_SPACE); if (isEmpty && isElement && canHaveHTML) { // Make sure that caret is visible in node by inserting a zero width no breaking space try { node.innerHTML = wysihtml5.INVISIBLE_SPACE; } catch(e) {} } range.selectNodeContents(node); if (isEmpty && isElement) { range.collapse(false); } else if (isEmpty) { range.setStartAfter(node); range.setEndAfter(node); } }, getTextSelectedByRange: function(textNode, range) { var textRange = range.cloneRange(); textRange.selectNodeContents(textNode); var intersectionRange = textRange.intersection(range); var text = intersectionRange ? intersectionRange.toString() : ""; textRange.detach(); return text; }, isAppliedToRange: function(range) { var ancestors = [], appliedType = "full", ancestor, styleAncestor, textNodes; for (var ri = range.length; ri--;) { textNodes = range[ri].getNodes([wysihtml5.TEXT_NODE]); if (!textNodes.length) { ancestor = this.getMatchingAncestor(range[ri].startContainer).element; return (ancestor) ? { "elements": [ancestor], "coverage": appliedType } : false; } for (var i = 0, len = textNodes.length, selectedText; i < len; ++i) { selectedText = this.getTextSelectedByRange(textNodes[i], range[ri]); ancestor = this.getMatchingAncestor(textNodes[i]).element; if (ancestor && selectedText != "") { ancestors.push(ancestor); if (wysihtml5.dom.getTextNodes(ancestor, true).length === 1) { appliedType = "full"; } else if (appliedType === "full") { appliedType = "inline"; } } else if (!ancestor) { appliedType = "partial"; } } } return (ancestors.length) ? { "elements": ancestors, "coverage": appliedType } : false; }, toggleRange: function(range) { var isApplied = this.isAppliedToRange(range), parentsExactMatch; if (isApplied) { if (isApplied.coverage === "full") { this.undoToRange(range); } else if (isApplied.coverage === "inline") { parentsExactMatch = areMatchingAllready(isApplied.elements, this.tagNames, this.cssStyle, this.cssClass); this.undoToRange(range); if (!parentsExactMatch) { this.applyToRange(range); } } else { // partial if (!areMatchingAllready(isApplied.elements, this.tagNames, this.cssStyle, this.cssClass)) { this.undoToRange(range); } this.applyToRange(range); } } else { this.applyToRange(range); } } }; wysihtml5.selection.HTMLApplier = HTMLApplier; })(wysihtml5, rangy); ;/** * Rich Text Query/Formatting Commands * * @example * var commands = new wysihtml5.Commands(editor); */ wysihtml5.Commands = Base.extend( /** @scope wysihtml5.Commands.prototype */ { constructor: function(editor) { this.editor = editor; this.composer = editor.composer; this.doc = this.composer.doc; }, /** * Check whether the browser supports the given command * * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") * @example * commands.supports("createLink"); */ support: function(command) { return wysihtml5.browser.supportsCommand(this.doc, command); }, /** * Check whether the browser supports the given command * * @param {String} command The command string which to execute (eg. "bold", "italic", "insertUnorderedList") * @param {String} [value] The command value parameter, needed for some commands ("createLink", "insertImage", ...), optional for commands that don't require one ("bold", "underline", ...) * @example * commands.exec("insertImage", "http://a1.twimg.com/profile_images/113868655/schrei_twitter_reasonably_small.jpg"); */ exec: function(command, value) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.exec, result = null; // If composer ahs placeholder unset it before command // Do not apply on commands that are behavioral if (this.composer.hasPlaceholderSet() && !wysihtml5.lang.array(['styleWithCSS', 'enableObjectResizing', 'enableInlineTableEditing']).contains(command)) { this.composer.element.innerHTML = ""; this.composer.selection.selectNode(this.composer.element); } this.editor.fire("beforecommand:composer"); if (method) { args.unshift(this.composer); result = method.apply(obj, args); } else { try { // try/catch for buggy firefox result = this.doc.execCommand(command, false, value); } catch(e) {} } this.editor.fire("aftercommand:composer"); return result; }, remove: function(command, commandValue) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.remove; if (method) { args.unshift(this.composer); return method.apply(obj, args); } }, /** * Check whether the current command is active * If the caret is within a bold text, then calling this with command "bold" should return true * * @param {String} command The command string which to check (eg. "bold", "italic", "insertUnorderedList") * @param {String} [commandValue] The command value parameter (eg. for "insertImage" the image src) * @return {Boolean} Whether the command is active * @example * var isCurrentSelectionBold = commands.state("bold"); */ state: function(command, commandValue) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.state; if (method) { args.unshift(this.composer); return method.apply(obj, args); } else { try { // try/catch for buggy firefox return this.doc.queryCommandState(command); } catch(e) { return false; } } }, /* Get command state parsed value if command has stateValue parsing function */ stateValue: function(command) { var obj = wysihtml5.commands[command], args = wysihtml5.lang.array(arguments).get(), method = obj && obj.stateValue; if (method) { args.unshift(this.composer); return method.apply(obj, args); } else { return false; } } }); ;(function(wysihtml5) { var nodeOptions = { nodeName: "B", toggle: true }; wysihtml5.commands.bold = { exec: function(composer, command) { wysihtml5.commands.formatInline.exec(composer, command, nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, nodeOptions); } }; }(wysihtml5)); ;(function(wysihtml5) { var nodeOptions = { nodeName: "A", toggle: false }; function getOptions(value) { var options = typeof value === 'object' ? value : {'href': value}; return wysihtml5.lang.object({}).merge(nodeOptions).merge({'attribute': value}).get(); } wysihtml5.commands.createLink = { exec: function(composer, command, value) { var opts = getOptions(value); if (composer.selection.isCollapsed() && !this.state(composer, command)) { var textNode = composer.doc.createTextNode(opts.attribute.href); composer.selection.insertNode(textNode); composer.selection.selectNode(textNode); } wysihtml5.commands.formatInline.exec(composer, command, opts); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5) { var nodeOptions = { nodeName: "A" }; wysihtml5.commands.removeLink = { exec: function(composer, command) { wysihtml5.commands.formatInline.remove(composer, command, nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, nodeOptions); } }; })(wysihtml5); ;/** * Set font size css class */ (function(wysihtml5) { var REG_EXP = /wysiwyg-font-size-[0-9a-z\-]+/g; wysihtml5.commands.fontSize = { exec: function(composer, command, size) { wysihtml5.commands.formatInline.exec(composer, command, {className: "wysiwyg-font-size-" + size, classRegExp: REG_EXP, toggle: true}); }, state: function(composer, command, size) { return wysihtml5.commands.formatInline.state(composer, command, {className: "wysiwyg-font-size-" + size}); } }; })(wysihtml5); ;/** * Set font size by inline style */ (function(wysihtml5) { wysihtml5.commands.fontSizeStyle = { exec: function(composer, command, size) { size = size.size || size; if (!(/^\s*$/).test(size)) { wysihtml5.commands.formatInline.exec(composer, command, {styleProperty: "fontSize", styleValue: size, toggle: false}); } }, state: function(composer, command, size) { return wysihtml5.commands.formatInline.state(composer, command, {styleProperty: "fontSize", styleValue: size || undefined}); }, remove: function(composer, command) { return wysihtml5.commands.formatInline.remove(composer, command, {styleProperty: "fontSize"}); }, stateValue: function(composer, command) { var styleStr, st = this.state(composer, command); if (st && wysihtml5.lang.object(st).isArray()) { st = st[0]; } if (st) { styleStr = st.getAttribute("style"); if (styleStr) { return wysihtml5.quirks.styleParser.parseFontSize(styleStr); } } return false; } }; })(wysihtml5); ;/** * Set color css class */ (function(wysihtml5) { var REG_EXP = /wysiwyg-color-[0-9a-z]+/g; wysihtml5.commands.foreColor = { exec: function(composer, command, color) { wysihtml5.commands.formatInline.exec(composer, command, {className: "wysiwyg-color-" + color, classRegExp: REG_EXP, toggle: true}); }, state: function(composer, command, color) { return wysihtml5.commands.formatInline.state(composer, command, {className: "wysiwyg-color-" + color}); } }; })(wysihtml5); ;/** * Sets text color by inline styles */ (function(wysihtml5) { wysihtml5.commands.foreColorStyle = { exec: function(composer, command, color) { var colorVals, colString; if (!color) { return; } colorVals = wysihtml5.quirks.styleParser.parseColor("color:" + (color.color || color), "color"); if (colorVals) { colString = (colorVals[3] === 1 ? "rgb(" + [colorVals[0], colorVals[1], colorVals[2]].join(", ") : "rgba(" + colorVals.join(', ')) + ')'; wysihtml5.commands.formatInline.exec(composer, command, {styleProperty: "color", styleValue: colString}); } }, state: function(composer, command, color) { var colorVals = color ? wysihtml5.quirks.styleParser.parseColor("color:" + (color.color || color), "color") : null, colString; if (colorVals) { colString = (colorVals[3] === 1 ? "rgb(" + [colorVals[0], colorVals[1], colorVals[2]].join(", ") : "rgba(" + colorVals.join(', ')) + ')'; } return wysihtml5.commands.formatInline.state(composer, command, {styleProperty: "color", styleValue: colString}); }, remove: function(composer, command) { return wysihtml5.commands.formatInline.remove(composer, command, {styleProperty: "color"}); }, stateValue: function(composer, command, props) { var st = this.state(composer, command), colorStr, val = false; if (st && wysihtml5.lang.object(st).isArray()) { st = st[0]; } if (st) { colorStr = st.getAttribute("style"); if (colorStr) { val = wysihtml5.quirks.styleParser.parseColor(colorStr, "color"); return wysihtml5.quirks.styleParser.unparseColor(val, props); } } return false; } }; })(wysihtml5); ;/** * Sets text background color by inline styles */ (function(wysihtml5) { wysihtml5.commands.bgColorStyle = { exec: function(composer, command, color) { var colorVals = wysihtml5.quirks.styleParser.parseColor("background-color:" + (color.color || color), "background-color"), colString; if (colorVals) { colString = (colorVals[3] === 1 ? "rgb(" + [colorVals[0], colorVals[1], colorVals[2]].join(', ') : "rgba(" + colorVals.join(', ')) + ')'; wysihtml5.commands.formatInline.exec(composer, command, {styleProperty: 'backgroundColor', styleValue: colString}); } }, state: function(composer, command, color) { var colorVals = color ? wysihtml5.quirks.styleParser.parseColor("background-color:" + (color.color || color), "background-color") : null, colString; if (colorVals) { colString = (colorVals[3] === 1 ? "rgb(" + [colorVals[0], colorVals[1], colorVals[2]].join(', ') : "rgba(" + colorVals.join(', ')) + ')'; } return wysihtml5.commands.formatInline.state(composer, command, {styleProperty: 'backgroundColor', styleValue: colString}); }, remove: function(composer, command) { return wysihtml5.commands.formatInline.remove(composer, command, {styleProperty: 'backgroundColor'}); }, stateValue: function(composer, command, props) { var st = this.state(composer, command), colorStr, val = false; if (st && wysihtml5.lang.object(st).isArray()) { st = st[0]; } if (st) { colorStr = st.getAttribute('style'); if (colorStr) { val = wysihtml5.quirks.styleParser.parseColor(colorStr, "background-color"); return wysihtml5.quirks.styleParser.unparseColor(val, props); } } return false; } }; })(wysihtml5); ;/* Formatblock * Is used to insert block level elements * It tries to solve the case that some block elements should not contain other block level elements (h1-6, p, ...) * */ (function(wysihtml5) { var dom = wysihtml5.dom, // When the caret is within a H1 and the H4 is invoked, the H1 should turn into H4 // instead of creating a H4 within a H1 which would result in semantically invalid html UNNESTABLE_BLOCK_ELEMENTS = "h1, h2, h3, h4, h5, h6, p, pre", BLOCK_ELEMENTS = "h1, h2, h3, h4, h5, h6, p, pre, div, blockquote", INLINE_ELEMENTS = "b, big, i, small, tt, abbr, acronym, cite, code, dfn, em, kbd, strong, samp, var, a, bdo, br, q, span, sub, sup, button, label, textarea, input, select, u"; function correctOptionsForSimilarityCheck(options) { return { nodeName: options.nodeName || null, className: (!options.classRegExp) ? options.className || null : null, classRegExp: options.classRegExp || null, styleProperty: options.styleProperty || null }; } // Removes empty block level elements function cleanup(composer) { var container = composer.element, allElements = container.querySelectorAll(BLOCK_ELEMENTS), uneditables = container.querySelectorAll(composer.config.classNames.uneditableContainer), elements = wysihtml5.lang.array(allElements).without(uneditables); for (var i = elements.length; i--;) { if (elements[i].innerHTML.replace(/[\uFEFF]/g, '') === "") { elements[i].parentNode.removeChild(elements[i]); } } } function defaultNodeName(composer) { return composer.config.useLineBreaks ? "DIV" : "P"; } // The outermost un-nestable block element parent of from node function findOuterBlock(node, container, allBlocks) { var n = node, block = null; while (n && container && n !== container) { if (n.nodeType === 1 && n.matches(allBlocks ? BLOCK_ELEMENTS : UNNESTABLE_BLOCK_ELEMENTS)) { block = n; } n = n.parentNode; } return block; } function cloneOuterInlines(node, container) { var n = node, innerNode, parentNode, el = null, el2; while (n && container && n !== container) { if (n.nodeType === 1 && n.matches(INLINE_ELEMENTS)) { parentNode = n; if (el === null) { el = n.cloneNode(false); innerNode = el; } else { el2 = n.cloneNode(false); el2.appendChild(el); el = el2; } } n = n.parentNode; } return { parent: parentNode, outerNode: el, innerNode: innerNode }; } // Formats an element according to options nodeName, className, styleProperty, styleValue // If element is not defined, creates new element // if opotions is null, remove format instead function applyOptionsToElement(element, options, composer) { if (!element) { element = composer.doc.createElement(options.nodeName || defaultNodeName(composer)); // Add invisible space as otherwise webkit cannot set selection or range to it correctly element.appendChild(composer.doc.createTextNode(wysihtml5.INVISIBLE_SPACE)); } if (options.nodeName && element.nodeName !== options.nodeName) { element = dom.renameElement(element, options.nodeName); } // Remove similar classes before applying className if (options.classRegExp) { element.className = element.className.replace(options.classRegExp, ""); } if (options.className) { element.classList.add(options.className); } if (options.styleProperty && typeof options.styleValue !== "undefined") { element.style[wysihtml5.browser.fixStyleKey(options.styleProperty)] = options.styleValue; } return element; } // Unsets element properties by options // If nodename given and matches current element, element is unwrapped or converted to default node (depending on presence of class and style attributes) function removeOptionsFromElement(element, options, composer) { var style, classes; if (options.styleProperty) { element.style[wysihtml5.browser.fixStyleKey(options.styleProperty)] = ''; } if (options.className) { element.classList.remove(options.className); } if (options.classRegExp) { element.className = element.className.replace(options.classRegExp, ""); } // Clean up blank class attribute if (element.getAttribute('class') !== null && element.getAttribute('class').trim() === "") { element.removeAttribute('class'); } if (options.nodeName && element.nodeName === options.nodeName) { style = element.getAttribute('style'); if (!style || style.trim() === '') { dom.unwrap(element); } else { element = dom.renameElement(element, defaultNodeName(composer)); } } // Clean up blank style attribute if (element.getAttribute('style') !== null && element.getAttribute('style').trim() === "") { element.removeAttribute('style'); } } // Unwraps block level elements from inside content // Useful as not all block level elements can contain other block-levels function unwrapBlocksFromContent(element) { var contentBlocks = element.querySelectorAll(BLOCK_ELEMENTS) || []; // Find unnestable block elements in extracted contents for (var i = contentBlocks.length; i--;) { if (!contentBlocks[i].nextSibling || contentBlocks[i].nextSibling.nodeType !== 1 || contentBlocks[i].nextSibling.nodeName !== 'BR') { if ((contentBlocks[i].innerHTML || contentBlocks[i].nodeValue || '').trim() !== '') { contentBlocks[i].parentNode.insertBefore(contentBlocks[i].ownerDocument.createElement('BR'), contentBlocks[i].nextSibling); } } wysihtml5.dom.unwrap(contentBlocks[i]); } } // Fix ranges that visually cover whole block element to actually cover the block function fixRangeCoverage(range, composer) { var node; if (range.startContainer && range.startContainer.nodeType === 1 && range.startContainer === range.endContainer) { if (range.startContainer.firstChild === range.startContainer.lastChild && range.endOffset === 1) { if (range.startContainer !== composer.element) { range.setStartBefore(range.startContainer); range.setEndAfter(range.endContainer); } } return; } if (range.startContainer && range.startContainer.nodeType === 1 && range.endContainer.nodeType === 3) { if (range.startContainer.firstChild === range.endContainer && range.endOffset === 1) { if (range.startContainer !== composer.element) { range.setEndAfter(range.startContainer); } } return; } if (range.endContainer && range.endContainer.nodeType === 1 && range.startContainer.nodeType === 3) { if (range.endContainer.firstChild === range.startContainer && range.endOffset === 1) { if (range.endContainer !== composer.element) { range.setStartBefore(range.endContainer); } } return; } if (range.startContainer && range.startContainer.nodeType === 3 && range.startContainer === range.endContainer && range.startContainer.parentNode) { if (range.startContainer.parentNode.firstChild === range.startContainer && range.endOffset == range.endContainer.length && range.startOffset === 0) { node = range.startContainer.parentNode; if (node !== composer.element) { range.setStartBefore(node); range.setEndAfter(node); } } return; } } // Wrap the range with a block level element // If element is one of unnestable block elements (ex: h2 inside h1), split nodes and insert between so nesting does not occur function wrapRangeWithElement(range, options, defaultName, composer) { var defaultOptions = (options) ? wysihtml5.lang.object(options).clone(true) : null; if (defaultOptions) { defaultOptions.nodeName = defaultOptions.nodeName || defaultName || defaultNodeName(composer); } fixRangeCoverage(range, composer); var r = range.cloneRange(), rangeStartContainer = r.startContainer, content = r.extractContents(), fragment = composer.doc.createDocumentFragment(), similarOptions = defaultOptions ? correctOptionsForSimilarityCheck(defaultOptions) : null, similarOuterBlock = similarOptions ? wysihtml5.dom.getParentElement(rangeStartContainer, similarOptions, null, composer.element) : null, splitAllBlocks = !defaultOptions || (defaultName === "BLOCKQUOTE" && defaultOptions.nodeName && defaultOptions.nodeName === "BLOCKQUOTE"), firstOuterBlock = similarOuterBlock || findOuterBlock(rangeStartContainer, composer.element, splitAllBlocks), // The outermost un-nestable block element parent of selection start wrapper, blocks, children; if (options && options.nodeName && options.nodeName === "BLOCKQUOTE") { var tmpEl = applyOptionsToElement(null, options, composer); tmpEl.appendChild(content); fragment.appendChild(tmpEl); blocks = [tmpEl]; } else { if (!content.firstChild) { fragment.appendChild(applyOptionsToElement(null, options, composer)); } else { while(content.firstChild) { if (content.firstChild.nodeType == 1 && content.firstChild.matches(BLOCK_ELEMENTS)) { if (options) { // Escape(split) block formatting at caret applyOptionsToElement(content.firstChild, options, composer); if (content.firstChild.matches(UNNESTABLE_BLOCK_ELEMENTS)) { unwrapBlocksFromContent(content.firstChild); } fragment.appendChild(content.firstChild); } else { // Split block formating and add new block to wrap caret unwrapBlocksFromContent(content.firstChild); children = wysihtml5.dom.unwrap(content.firstChild); for (var c = 0, cmax = children.length; c < cmax; c++) { fragment.appendChild(children[c]); } if (fragment.childNodes.length > 0) { fragment.appendChild(composer.doc.createElement('BR')); } } } else { if (options) { // Wrap subsequent non-block nodes inside new block element wrapper = applyOptionsToElement(null, defaultOptions, composer); while(content.firstChild && (content.firstChild.nodeType !== 1 || !content.firstChild.matches(BLOCK_ELEMENTS))) { if (content.firstChild.nodeType == 1 && wrapper.matches(UNNESTABLE_BLOCK_ELEMENTS)) { unwrapBlocksFromContent(content.firstChild); } wrapper.appendChild(content.firstChild); } fragment.appendChild(wrapper); } else { // Escape(split) block formatting at selection if (content.firstChild.nodeType == 1) { unwrapBlocksFromContent(content.firstChild); } fragment.appendChild(content.firstChild); } } } } blocks = wysihtml5.lang.array(fragment.childNodes).get(); } if (firstOuterBlock) { // If selection starts inside un-nestable block, split-escape the unnestable point and insert node between composer.selection.splitElementAtCaret(firstOuterBlock, fragment); } else { // Ensure node does not get inserted into an inline where it is not allowed var outerInlines = cloneOuterInlines(rangeStartContainer, composer.element); if (outerInlines.outerNode && outerInlines.innerNode && outerInlines.parent) { if (fragment.childNodes.length === 1) { while(fragment.firstChild.firstChild) { outerInlines.innerNode.appendChild(fragment.firstChild.firstChild); } fragment.firstChild.appendChild(outerInlines.outerNode); } composer.selection.splitElementAtCaret(outerInlines.parent, fragment); } else { // Otherwise just insert r.insertNode(fragment); } } return blocks; } // Find closest block level element function getParentBlockNodeName(element, composer) { var parentNode = wysihtml5.dom.getParentElement(element, { query: BLOCK_ELEMENTS }, null, composer.element); return (parentNode) ? parentNode.nodeName : null; } wysihtml5.commands.formatBlock = { exec: function(composer, command, options) { var newBlockElements = [], placeholder, ranges, range, parent, bookmark, state; // If properties is passed as a string, look for tag with that tagName/query if (typeof options === "string") { options = { nodeName: options.toUpperCase() }; } // Remove state if toggle set and state on and selection is collapsed if (options && options.toggle) { state = this.state(composer, command, options); if (state) { bookmark = rangy.saveSelection(composer.win); for (var j = 0, jmax = state.length; j < jmax; j++) { removeOptionsFromElement(state[j], options, composer); } } } // Otherwise expand selection so it will cover closest block if option caretSelectsBlock is true and selection is collapsed if (!state) { if (composer.selection.isCollapsed()) { parent = wysihtml5.dom.getParentElement(composer.selection.getOwnRanges()[0].startContainer, { query: UNNESTABLE_BLOCK_ELEMENTS + ', ' + (options && options.nodeName ? options.nodeName.toLowerCase() : 'div'), }, null, composer.element); if (parent) { bookmark = rangy.saveSelection(composer.win); range = composer.selection.createRange(); range.selectNode(parent); composer.selection.setSelection(range); } else if (!composer.isEmpty()) { bookmark = rangy.saveSelection(composer.win); composer.selection.selectLine(); } } // And get all selection ranges of current composer and iterate ranges = composer.selection.getOwnRanges(); for (var i = ranges.length; i--;) { newBlockElements = newBlockElements.concat(wrapRangeWithElement(ranges[i], options, getParentBlockNodeName(ranges[i].startContainer, composer), composer)); } } // Remove empty block elements that may be left behind cleanup(composer); // If cleanup removed some new block elements. remove them from array too for (var e = newBlockElements.length; e--;) { if (!newBlockElements[e].parentNode) { newBlockElements.splice(e, 1); } } // Restore correct selection if (bookmark) { rangy.restoreSelection(bookmark); } else { range = composer.selection.createRange(); range.setStartBefore(newBlockElements[0]); range.setEndAfter(newBlockElements[newBlockElements.length - 1]); composer.selection.setSelection(range); } wysihtml5.dom.removeInvisibleSpaces(composer.element); }, // If properties as null is passed returns status describing all block level elements state: function(composer, command, properties) { // If properties is passed as a string, look for tag with that tagName/query if (typeof properties === "string") { properties = { query: properties }; } var nodes = composer.selection.filterElements((function (element) { // Finds matching elements inside selection return wysihtml5.dom.domNode(element).test(properties || { query: BLOCK_ELEMENTS }); }).bind(this)), parentNodes = composer.selection.getSelectedOwnNodes(), parent; // Finds matching elements that are parents of selection and adds to nodes list for (var i = 0, maxi = parentNodes.length; i < maxi; i++) { parent = dom.getParentElement(parentNodes[i], properties || { query: BLOCK_ELEMENTS }, null, composer.element); if (parent && nodes.indexOf(parent) === -1) { nodes.push(parent); } } return (nodes.length === 0) ? false : nodes; } }; })(wysihtml5); ;/* Formats block for as a <pre><code class="classname"></code></pre> block * Useful in conjuction for sytax highlight utility: highlight.js * * Usage: * * editorInstance.composer.commands.exec("formatCode", "language-html"); */ (function(wysihtml5){ wysihtml5.commands.formatCode = { exec: function(composer, command, classname) { var pre = this.state(composer)[0], code, range, selectedNodes; if (pre) { // caret is already within a <pre><code>...</code></pre> composer.selection.executeAndRestore(function() { code = pre.querySelector("code"); wysihtml5.dom.replaceWithChildNodes(pre); if (code) { wysihtml5.dom.replaceWithChildNodes(code); } }); } else { // Wrap in <pre><code>...</code></pre> range = composer.selection.getRange(); selectedNodes = range.extractContents(); pre = composer.doc.createElement("pre"); code = composer.doc.createElement("code"); if (classname) { code.className = classname; } pre.appendChild(code); code.appendChild(selectedNodes); range.insertNode(pre); composer.selection.selectNode(pre); } }, state: function(composer) { var selectedNode = composer.selection.getSelectedNode(), node; if (selectedNode && selectedNode.nodeName && selectedNode.nodeName == "PRE"&& selectedNode.firstChild && selectedNode.firstChild.nodeName && selectedNode.firstChild.nodeName == "CODE") { return [selectedNode]; } else { node = wysihtml5.dom.getParentElement(selectedNode, { query: "pre code" }); return node ? [node.parentNode] : false; } } }; }(wysihtml5)); ;/** * Unifies all inline tags additions and removals * See https://github.com/Voog/wysihtml/pull/169 for specification of action */ (function(wysihtml5) { var defaultTag = "SPAN", INLINE_ELEMENTS = "b, big, i, small, tt, abbr, acronym, cite, code, dfn, em, kbd, strong, samp, var, a, bdo, br, q, span, sub, sup, button, label, textarea, input, select, u", queryAliasMap = { "b": "b, strong", "strong": "b, strong", "em": "em, i", "i": "em, i" }; function hasNoClass(element) { return (/^\s*$/).test(element.className); } function hasNoStyle(element) { return !element.getAttribute('style') || (/^\s*$/).test(element.getAttribute('style')); } // Associative arrays in javascript are really objects and do not have length defined // Thus have to check emptyness in a different way function hasNoAttributes(element) { var attr = wysihtml5.dom.getAttributes(element); return wysihtml5.lang.object(attr).isEmpty(); } // compares two nodes if they are semantically the same // Used in cleanup to find consequent semantically similar elements for merge function isSameNode(element1, element2) { var classes1, classes2, attr1, attr2; if (element1.nodeType !== 1 || element2.nodeType !== 1) { return false; } if (element1.nodeName !== element2.nodeName) { return false; } classes1 = element1.className.trim().replace(/\s+/g, ' ').split(' '); classes2 = element2.className.trim().replace(/\s+/g, ' ').split(' '); if (wysihtml5.lang.array(classes1).without(classes2).length > 0) { return false; } attr1 = wysihtml5.dom.getAttributes(element1); attr2 = wysihtml5.dom.getAttributes(element2); if (attr1.length !== attr2.length || !wysihtml5.lang.object(wysihtml5.lang.object(attr1).difference(attr2)).isEmpty()) { return false; } return true; } function createWrapNode(textNode, options) { var nodeName = options && options.nodeName || defaultTag, element = textNode.ownerDocument.createElement(nodeName); // Remove similar classes before applying className if (options.classRegExp) { element.className = element.className.replace(options.classRegExp, ""); } if (options.className) { element.classList.add(options.className); } if (options.styleProperty && typeof options.styleValue !== "undefined") { element.style[wysihtml5.browser.fixStyleKey(options.styleProperty)] = options.styleValue; } if (options.attribute) { if (typeof options.attribute === "object") { for (var a in options.attribute) { if (options.attribute.hasOwnProperty(a)) { element.setAttribute(a, options.attribute[a]); } } } else if (typeof options.attributeValue !== "undefined") { element.setAttribute(options.attribute, options.attributeValue); } } return element; } // Tests if attr2 list contains all attributes present in attr1 // Note: attr 1 can have more attributes than attr2 function containsSameAttributes(attr1, attr2) { for (var a in attr1) { if (attr1.hasOwnProperty(a)) { if (typeof attr2[a] === undefined || attr2[a] !== attr1[a]) { return false; } } } return true; } // If attrbutes and values are the same > remove // if attributes or values function updateElementAttributes(element, newAttributes, toggle) { var attr = wysihtml5.dom.getAttributes(element), fullContain = containsSameAttributes(newAttributes, attr), attrDifference = wysihtml5.lang.object(attr).difference(newAttributes), a, b; if (fullContain && toggle !== false) { for (a in newAttributes) { if (newAttributes.hasOwnProperty(a)) { element.removeAttribute(a); } } } else { /*if (!wysihtml5.lang.object(attrDifference).isEmpty()) { for (b in attrDifference) { if (attrDifference.hasOwnProperty(b)) { element.removeAttribute(b); } } }*/ for (a in newAttributes) { if (newAttributes.hasOwnProperty(a)) { element.setAttribute(a, newAttributes[a]); } } } } function updateFormatOfElement(element, options) { var attr, newNode, a, newAttributes, nodeNameQuery, nodeQueryMatch; if (options.className) { if (options.toggle !== false && element.classList.contains(options.className)) { element.classList.remove(options.className); } else { element.classList.add(options.className); } if (hasNoClass(element)) { element.removeAttribute('class'); } } // change/remove style if (options.styleProperty) { if (options.toggle !== false && element.style[wysihtml5.browser.fixStyleKey(options.styleProperty)].trim().replace(/, /g, ",") === options.styleValue) { element.style[wysihtml5.browser.fixStyleKey(options.styleProperty)] = ''; } else { element.style[wysihtml5.browser.fixStyleKey(options.styleProperty)] = options.styleValue; } } if (hasNoStyle(element)) { element.removeAttribute('style'); } if (options.attribute) { if (typeof options.attribute === "object") { newAttributes = options.attribute; } else { newAttributes = {}; newAttributes[options.attribute] = options.attributeValue || ''; } updateElementAttributes(element, newAttributes, options.toggle); } // Handle similar semantically same elements (queryAliasMap) nodeNameQuery = options.nodeName ? queryAliasMap[options.nodeName.toLowerCase()] || options.nodeName.toLowerCase() : null; nodeQueryMatch = nodeNameQuery ? wysihtml5.dom.domNode(element).test({ query: nodeNameQuery }) : false; // Unwrap element if no attributes present and node name given // or no attributes and if no nodename set but node is the default if (!options.nodeName || options.nodeName === defaultTag || nodeQueryMatch) { if ( ((options.toggle !== false && nodeQueryMatch) || (!options.nodeName && element.nodeName === defaultTag)) && hasNoClass(element) && hasNoStyle(element) && hasNoAttributes(element) ) { wysihtml5.dom.unwrap(element); } } } // Fetch all textnodes in selection // Empty textnodes are ignored except the one containing text caret function getSelectedTextNodes(selection, splitBounds) { var textNodes = []; if (!selection.isCollapsed()) { textNodes = textNodes.concat(selection.getOwnNodes([3], function(node) { // Exclude empty nodes except caret node return (!wysihtml5.dom.domNode(node).is.emptyTextNode()); }, splitBounds)); } return textNodes; } function findSimilarTextNodeWrapper(textNode, options, container, exact) { var node = textNode, similarOptions = exact ? options : correctOptionsForSimilarityCheck(options); do { if (node.nodeType === 1 && isSimilarNode(node, similarOptions)) { return node; } node = node.parentNode; } while (node && node !== container); return null; } function correctOptionsForSimilarityCheck(options) { return { nodeName: options.nodeName || null, className: (!options.classRegExp) ? options.className || null : null, classRegExp: options.classRegExp || null, styleProperty: options.styleProperty || null }; } // Finds inline node with similar nodeName/style/className // If nodeName is specified inline node with the same (or alias) nodeName is expected to prove similar regardless of attributes function isSimilarNode(node, options) { var o; if (options.nodeName) { var query = queryAliasMap[options.nodeName.toLowerCase()] || options.nodeName.toLowerCase(); return wysihtml5.dom.domNode(node).test({ query: query }); } else { o = wysihtml5.lang.object(options).clone(); o.query = INLINE_ELEMENTS; // make sure only inline elements with styles and classes are counted return wysihtml5.dom.domNode(node).test(o); } } function selectRange(composer, range) { var d = document.documentElement || document.body, oldScrollTop = d.scrollTop, oldScrollLeft = d.scrollLeft, selection = rangy.getSelection(composer.win); rangy.getSelection(composer.win).removeAllRanges(); // IE looses focus of contenteditable on removeallranges and can not set new selection unless contenteditable is focused again try { rangy.getSelection(composer.win).addRange(range); } catch (e) {} if (!composer.doc.activeElement || !wysihtml5.dom.contains(composer.element, composer.doc.activeElement)) { composer.element.focus(); d.scrollTop = oldScrollTop; d.scrollLeft = oldScrollLeft; rangy.getSelection(composer.win).addRange(range); } } function selectTextNodes(textNodes, composer) { var range = rangy.createRange(composer.doc), lastText = textNodes[textNodes.length - 1]; if (textNodes[0] && lastText) { range.setStart(textNodes[0], 0); range.setEnd(lastText, lastText.length); selectRange(composer, range); } } function selectTextNode(composer, node, start, end) { var range = rangy.createRange(composer.doc); if (node) { range.setStart(node, start); range.setEnd(node, typeof end !== 'undefined' ? end : start); selectRange(composer, range); } } function getState(composer, options, exact) { var searchNodes = getSelectedTextNodes(composer.selection), nodes = [], partial = false, node, range, caretNode; if (composer.selection.isInThisEditable()) { if (searchNodes.length === 0 && composer.selection.isCollapsed()) { caretNode = composer.selection.getSelection().anchorNode; if (!caretNode) { // selection not in editor return { nodes: [], partial: false }; } if (caretNode.nodeType === 3) { searchNodes = [caretNode]; } } // Handle collapsed selection caret if (!searchNodes.length) { range = composer.selection.getOwnRanges()[0]; if (range) { searchNodes = [range.endContainer]; } } for (var i = 0, maxi = searchNodes.length; i < maxi; i++) { node = findSimilarTextNodeWrapper(searchNodes[i], options, composer.element, exact); if (node) { nodes.push(node); } else { partial = true; } } } return { nodes: nodes, partial: partial }; } // Returns if caret is inside a word in textnode (not on boundary) // If selection anchornode is not text node, returns false function caretIsInsideWord(selection) { var anchor, offset, beforeChar, afterChar; if (selection) { anchor = selection.anchorNode; offset = selection.anchorOffset; if (anchor && anchor.nodeType === 3 && offset > 0 && offset < anchor.data.length) { beforeChar = anchor.data[offset - 1]; afterChar = anchor.data[offset]; return (/\w/).test(beforeChar) && (/\w/).test(afterChar); } } return false; } // Returns a range and textnode containing object from caret position covering a whole word // wordOffsety describes the original position of caret in the new textNode // Caret has to be inside a textNode. function getRangeForWord(selection) { var anchor, offset, doc, range, offsetStart, offsetEnd, beforeChar, afterChar, txtNodes = []; if (selection) { anchor = selection.anchorNode; offset = offsetStart = offsetEnd = selection.anchorOffset; doc = anchor.ownerDocument; range = rangy.createRange(doc); if (anchor && anchor.nodeType === 3) { while (offsetStart > 0 && (/\w/).test(anchor.data[offsetStart - 1])) { offsetStart--; } while (offsetEnd < anchor.data.length && (/\w/).test(anchor.data[offsetEnd])) { offsetEnd++; } range.setStartAndEnd(anchor, offsetStart, offsetEnd); range.splitBoundaries(); txtNodes = range.getNodes([3], function(node) { return (!wysihtml5.dom.domNode(node).is.emptyTextNode()); }); return { wordOffset: offset - offsetStart, range: range, textNode: txtNodes[0] }; } } return false; } // Contents of 2 elements are merged to fitst element. second element is removed as consequence function mergeContents(element1, element2) { while (element2.firstChild) { element1.appendChild(element2.firstChild); } element2.parentNode.removeChild(element2); } function mergeConsequentSimilarElements(elements) { for (var i = elements.length; i--;) { if (elements[i] && elements[i].parentNode) { // Test if node is not allready removed in cleanup if (elements[i].nextSibling && isSameNode(elements[i], elements[i].nextSibling)) { mergeContents(elements[i], elements[i].nextSibling); } if (elements[i].previousSibling && isSameNode(elements[i] , elements[i].previousSibling)) { mergeContents(elements[i].previousSibling, elements[i]); } } } } function cleanupAndSetSelection(composer, textNodes, options) { if (textNodes.length > 0) { selectTextNodes(textNodes, composer); } mergeConsequentSimilarElements(getState(composer, options).nodes); if (textNodes.length > 0) { selectTextNodes(textNodes, composer); } } function cleanupAndSetCaret(composer, textNode, offset, options) { selectTextNode(composer, textNode, offset); mergeConsequentSimilarElements(getState(composer, options).nodes); selectTextNode(composer, textNode, offset); } // Formats a textnode with given options function formatTextNode(textNode, options) { var wrapNode = createWrapNode(textNode, options); textNode.parentNode.insertBefore(wrapNode, textNode); wrapNode.appendChild(textNode); } // Changes/toggles format of a textnode function unformatTextNode(textNode, composer, options) { var container = composer.element, wrapNode = findSimilarTextNodeWrapper(textNode, options, container), newWrapNode; if (wrapNode) { newWrapNode = wrapNode.cloneNode(false); wysihtml5.dom.domNode(textNode).escapeParent(wrapNode, newWrapNode); updateFormatOfElement(newWrapNode, options); } } // Removes the format around textnode function removeFormatFromTextNode(textNode, composer, options) { var container = composer.element, wrapNode = findSimilarTextNodeWrapper(textNode, options, container); if (wrapNode) { wysihtml5.dom.domNode(textNode).escapeParent(wrapNode); } } // Creates node around caret formated with options function formatTextRange(range, composer, options) { var wrapNode = createWrapNode(range.endContainer, options); range.surroundContents(wrapNode); composer.selection.selectNode(wrapNode); } // Changes/toggles format of whole selection function updateFormat(composer, textNodes, state, options) { var exactState = getState(composer, options, true), selection = composer.selection.getSelection(), wordObj, textNode, newNode, i; if (!textNodes.length) { // Selection is caret if (options.toggle !== false) { if (caretIsInsideWord(selection)) { // Unformat whole word wordObj = getRangeForWord(selection); textNode = wordObj.textNode; unformatTextNode(wordObj.textNode, composer, options); cleanupAndSetCaret(composer, wordObj.textNode, wordObj.wordOffset, options); } else { // Escape caret out of format textNode = composer.doc.createTextNode(wysihtml5.INVISIBLE_SPACE); newNode = state.nodes[0].cloneNode(false); newNode.appendChild(textNode); composer.selection.splitElementAtCaret(state.nodes[0], newNode); updateFormatOfElement(newNode, options); cleanupAndSetSelection(composer, [textNode], options); var s = composer.selection.getSelection(); if (s.anchorNode && s.focusNode) { // Has an error in IE when collapsing selection. probably from rangy try { s.collapseToEnd(); } catch (e) {} } } } else { // In non-toggle mode the closest state element has to be found and the state updated differently for (i = state.nodes.length; i--;) { updateFormatOfElement(state.nodes[i], options); } } } else { if (!exactState.partial && options.toggle !== false) { // If whole selection (all textnodes) are in the applied format // remove the format from selection // Non-toggle mode never removes. Remove has to be called explicitly for (i = textNodes.length; i--;) { unformatTextNode(textNodes[i], composer, options); } } else { // Selection is partially in format // change it to new if format if textnode allreafy in similar state // else just apply for (i = textNodes.length; i--;) { if (findSimilarTextNodeWrapper(textNodes[i], options, composer.element)) { unformatTextNode(textNodes[i], composer, options); } if (!findSimilarTextNodeWrapper(textNodes[i], options, composer.element)) { formatTextNode(textNodes[i], options); } } } cleanupAndSetSelection(composer, textNodes, options); } } // Removes format from selection function removeFormat(composer, textNodes, state, options) { var textNode, textOffset, newNode, i, selection = composer.selection.getSelection(); if (!textNodes.length) { textNode = selection.anchorNode; textOffset = selection.anchorOffset; for (i = state.nodes.length; i--;) { wysihtml5.dom.unwrap(state.nodes[i]); } cleanupAndSetCaret(composer, textNode, textOffset, options); } else { for (i = textNodes.length; i--;) { removeFormatFromTextNode(textNodes[i], composer, options); } cleanupAndSetSelection(composer, textNodes, options); } } // Adds format to selection function applyFormat(composer, textNodes, options) { var wordObj, i, selection = composer.selection.getSelection(); if (!textNodes.length) { // Handle collapsed selection caret and return if (caretIsInsideWord(selection)) { wordObj = getRangeForWord(selection); formatTextNode(wordObj.textNode, options); cleanupAndSetCaret(composer, wordObj.textNode, wordObj.wordOffset, options); } else { var r = composer.selection.getOwnRanges()[0]; if (r) { formatTextRange(r, composer, options); } } } else { // Handle textnodes in selection and apply format for (i = textNodes.length; i--;) { formatTextNode(textNodes[i], options); } cleanupAndSetSelection(composer, textNodes, options); } } // If properties is passed as a string, correct options with that nodeName function fixOptions(options) { options = (typeof options === "string") ? { nodeName: options } : options; if (options.nodeName) { options.nodeName = options.nodeName.toUpperCase(); } return options; } wysihtml5.commands.formatInline = { // Basics: // In case of plain text or inline state not set wrap all non-empty textnodes with // In case a similar inline wrapper node is detected on one of textnodes, the wrapper node is changed (if fully contained) or split and changed (partially contained) // In case of changing mode every textnode is addressed separatly exec: function(composer, command, options) { options = fixOptions(options); // Join adjactent textnodes first composer.element.normalize(); var textNodes = getSelectedTextNodes(composer.selection, true), state = getState(composer, options); if (state.nodes.length > 0) { // Text allready has the format applied updateFormat(composer, textNodes, state, options); } else { // Selection is not in the applied format applyFormat(composer, textNodes, options); } composer.element.normalize(); }, remove: function(composer, command, options) { options = fixOptions(options); composer.element.normalize(); var textNodes = getSelectedTextNodes(composer.selection, true), state = getState(composer, options); if (state.nodes.length > 0) { // Text allready has the format applied removeFormat(composer, textNodes, state, options); } composer.element.normalize(); }, state: function(composer, command, options) { options = fixOptions(options); var nodes = getState(composer, options, true).nodes; return (nodes.length === 0) ? false : nodes; } }; })(wysihtml5); ;(function(wysihtml5) { var nodeOptions = { nodeName: "BLOCKQUOTE", toggle: true }; wysihtml5.commands.insertBlockQuote = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5){ wysihtml5.commands.insertHTML = { exec: function(composer, command, html) { if (composer.commands.support(command)) { composer.doc.execCommand(command, false, html); } else { composer.selection.insertHTML(html); } }, state: function() { return false; } }; }(wysihtml5)); ;(function(wysihtml5) { var NODE_NAME = "IMG"; wysihtml5.commands.insertImage = { /** * Inserts an <img> * If selection is already an image link, it removes it * * @example * // either ... * wysihtml5.commands.insertImage.exec(composer, "insertImage", "http://www.google.de/logo.jpg"); * // ... or ... * wysihtml5.commands.insertImage.exec(composer, "insertImage", { src: "http://www.google.de/logo.jpg", title: "foo" }); */ exec: function(composer, command, value) { value = typeof(value) === "object" ? value : { src: value }; var doc = composer.doc, image = this.state(composer), textNode, parent; // If image is selected and src ie empty, set the caret before it and delete the image if (image && !value.src) { composer.selection.setBefore(image); parent = image.parentNode; parent.removeChild(image); // and it's parent <a> too if it hasn't got any other relevant child nodes wysihtml5.dom.removeEmptyTextNodes(parent); if (parent.nodeName === "A" && !parent.firstChild) { composer.selection.setAfter(parent); parent.parentNode.removeChild(parent); } // firefox and ie sometimes don't remove the image handles, even though the image got removed wysihtml5.quirks.redraw(composer.element); return; } // If image selected change attributes accordingly if (image) { for (var key in value) { if (value.hasOwnProperty(key)) { image.setAttribute(key === "className" ? "class" : key, value[key]); } } return; } // Otherwise lets create the image image = doc.createElement(NODE_NAME); for (var i in value) { image.setAttribute(i === "className" ? "class" : i, value[i]); } composer.selection.insertNode(image); if (wysihtml5.browser.hasProblemsSettingCaretAfterImg()) { textNode = doc.createTextNode(wysihtml5.INVISIBLE_SPACE); composer.selection.insertNode(textNode); composer.selection.setAfter(textNode); } else { composer.selection.setAfter(image); } }, state: function(composer) { var doc = composer.doc, selectedNode, text, imagesInSelection; if (!wysihtml5.dom.hasElementWithTagName(doc, NODE_NAME)) { return false; } selectedNode = composer.selection.getSelectedNode(); if (!selectedNode) { return false; } if (selectedNode.nodeName === NODE_NAME) { // This works perfectly in IE return selectedNode; } if (selectedNode.nodeType !== wysihtml5.ELEMENT_NODE) { return false; } text = composer.selection.getText(); text = wysihtml5.lang.string(text).trim(); if (text) { return false; } imagesInSelection = composer.selection.getNodes(wysihtml5.ELEMENT_NODE, function(node) { return node.nodeName === "IMG"; }); if (imagesInSelection.length !== 1) { return false; } return imagesInSelection[0]; } }; })(wysihtml5); ;(function(wysihtml5) { var LINE_BREAK = "<br>" + (wysihtml5.browser.needsSpaceAfterLineBreak() ? " " : ""); wysihtml5.commands.insertLineBreak = { exec: function(composer, command) { if (composer.commands.support(command)) { composer.doc.execCommand(command, false, null); if (!wysihtml5.browser.autoScrollsToCaret()) { composer.selection.scrollIntoView(); } } else { composer.commands.exec("insertHTML", LINE_BREAK); } }, state: function() { return false; } }; })(wysihtml5); ;(function(wysihtml5){ wysihtml5.commands.insertOrderedList = { exec: function(composer, command) { wysihtml5.commands.insertList.exec(composer, command, "OL"); }, state: function(composer, command) { return wysihtml5.commands.insertList.state(composer, command, "OL"); } }; }(wysihtml5)); ;(function(wysihtml5){ wysihtml5.commands.insertUnorderedList = { exec: function(composer, command) { wysihtml5.commands.insertList.exec(composer, command, "UL"); }, state: function(composer, command) { return wysihtml5.commands.insertList.state(composer, command, "UL"); } }; }(wysihtml5)); ;wysihtml5.commands.insertList = (function(wysihtml5) { var isNode = function(node, name) { if (node && node.nodeName) { if (typeof name === 'string') { name = [name]; } for (var n = name.length; n--;) { if (node.nodeName === name[n]) { return true; } } } return false; }; var findListEl = function(node, nodeName, composer) { var ret = { el: null, other: false }; if (node) { var parentLi = wysihtml5.dom.getParentElement(node, { query: "li" }, false, composer.element), otherNodeName = (nodeName === "UL") ? "OL" : "UL"; if (isNode(node, nodeName)) { ret.el = node; } else if (isNode(node, otherNodeName)) { ret = { el: node, other: true }; } else if (parentLi) { if (isNode(parentLi.parentNode, nodeName)) { ret.el = parentLi.parentNode; } else if (isNode(parentLi.parentNode, otherNodeName)) { ret = { el : parentLi.parentNode, other: true }; } } } // do not count list elements outside of composer if (ret.el && !composer.element.contains(ret.el)) { ret.el = null; } return ret; }; var handleSameTypeList = function(el, nodeName, composer) { var otherNodeName = (nodeName === "UL") ? "OL" : "UL", otherLists, innerLists; // Unwrap list // <ul><li>foo</li><li>bar</li></ul> // becomes: // foo<br>bar<br> composer.selection.executeAndRestoreRangy(function() { otherLists = getListsInSelection(otherNodeName, composer); if (otherLists.length) { for (var l = otherLists.length; l--;) { wysihtml5.dom.renameElement(otherLists[l], nodeName.toLowerCase()); } } else { innerLists = getListsInSelection(['OL', 'UL'], composer); for (var i = innerLists.length; i--;) { wysihtml5.dom.resolveList(innerLists[i], composer.config.useLineBreaks); } wysihtml5.dom.resolveList(el, composer.config.useLineBreaks); } }); }; var handleOtherTypeList = function(el, nodeName, composer) { var otherNodeName = (nodeName === "UL") ? "OL" : "UL"; // Turn an ordered list into an unordered list // <ol><li>foo</li><li>bar</li></ol> // becomes: // <ul><li>foo</li><li>bar</li></ul> // Also rename other lists in selection composer.selection.executeAndRestoreRangy(function() { var renameLists = [el].concat(getListsInSelection(otherNodeName, composer)); // All selection inner lists get renamed too for (var l = renameLists.length; l--;) { wysihtml5.dom.renameElement(renameLists[l], nodeName.toLowerCase()); } }); }; var getListsInSelection = function(nodeName, composer) { var ranges = composer.selection.getOwnRanges(), renameLists = []; for (var r = ranges.length; r--;) { renameLists = renameLists.concat(ranges[r].getNodes([1], function(node) { return isNode(node, nodeName); })); } return renameLists; }; var createListFallback = function(nodeName, composer) { // Fallback for Create list composer.selection.executeAndRestoreRangy(function() { var tempClassName = "_wysihtml5-temp-" + new Date().getTime(), tempElement = composer.selection.deblockAndSurround({ "nodeName": "div", "className": tempClassName }), isEmpty, list; // This space causes new lists to never break on enter var INVISIBLE_SPACE_REG_EXP = /\uFEFF/g; tempElement.innerHTML = tempElement.innerHTML.replace(wysihtml5.INVISIBLE_SPACE_REG_EXP, ""); if (tempElement) { isEmpty = wysihtml5.lang.array(["", "<br>", wysihtml5.INVISIBLE_SPACE]).contains(tempElement.innerHTML); list = wysihtml5.dom.convertToList(tempElement, nodeName.toLowerCase(), composer.parent.config.classNames.uneditableContainer); if (isEmpty) { composer.selection.selectNode(list.querySelector("li"), true); } } }); }; return { exec: function(composer, command, nodeName) { var doc = composer.doc, cmd = (nodeName === "OL") ? "insertOrderedList" : "insertUnorderedList", selectedNode = composer.selection.getSelectedNode(), list = findListEl(selectedNode, nodeName, composer); if (!list.el) { if (composer.commands.support(cmd)) { doc.execCommand(cmd, false, null); } else { createListFallback(nodeName, composer); } } else if (list.other) { handleOtherTypeList(list.el, nodeName, composer); } else { handleSameTypeList(list.el, nodeName, composer); } }, state: function(composer, command, nodeName) { var selectedNode = composer.selection.getSelectedNode(), list = findListEl(selectedNode, nodeName, composer); return (list.el && !list.other) ? list.el : false; } }; })(wysihtml5); ;(function(wysihtml5){ var nodeOptions = { nodeName: "I", toggle: true }; wysihtml5.commands.italic = { exec: function(composer, command) { wysihtml5.commands.formatInline.exec(composer, command, nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, nodeOptions); } }; }(wysihtml5)); ;(function(wysihtml5) { var nodeOptions = { className: "wysiwyg-text-align-center", classRegExp: /wysiwyg-text-align-[0-9a-z]+/g, toggle: true }; wysihtml5.commands.justifyCenter = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5) { var nodeOptions = { className: "wysiwyg-text-align-left", classRegExp: /wysiwyg-text-align-[0-9a-z]+/g, toggle: true }; wysihtml5.commands.justifyLeft = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5) { var nodeOptions = { className: "wysiwyg-text-align-right", classRegExp: /wysiwyg-text-align-[0-9a-z]+/g, toggle: true }; wysihtml5.commands.justifyRight = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5) { var nodeOptions = { className: "wysiwyg-text-align-justify", classRegExp: /wysiwyg-text-align-[0-9a-z]+/g, toggle: true }; wysihtml5.commands.justifyFull = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5) { var nodeOptions = { styleProperty: "textAlign", styleValue: "right", toggle: true }; wysihtml5.commands.alignRightStyle = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5) { var nodeOptions = { styleProperty: "textAlign", styleValue: "left", toggle: true }; wysihtml5.commands.alignLeftStyle = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5) { var nodeOptions = { styleProperty: "textAlign", styleValue: "center", toggle: true }; wysihtml5.commands.alignCenterStyle = { exec: function(composer, command) { return wysihtml5.commands.formatBlock.exec(composer, "formatBlock", nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatBlock.state(composer, "formatBlock", nodeOptions); } }; })(wysihtml5); ;(function(wysihtml5){ wysihtml5.commands.redo = { exec: function(composer) { return composer.undoManager.redo(); }, state: function(composer) { return false; } }; }(wysihtml5)); ;(function(wysihtml5){ var nodeOptions = { nodeName: "U", toggle: true }; wysihtml5.commands.underline = { exec: function(composer, command) { wysihtml5.commands.formatInline.exec(composer, command, nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, nodeOptions); } }; }(wysihtml5)); ;(function(wysihtml5){ wysihtml5.commands.undo = { exec: function(composer) { return composer.undoManager.undo(); }, state: function(composer) { return false; } }; }(wysihtml5)); ;(function(wysihtml5){ wysihtml5.commands.createTable = { exec: function(composer, command, value) { var col, row, html; if (value && value.cols && value.rows && parseInt(value.cols, 10) > 0 && parseInt(value.rows, 10) > 0) { if (value.tableStyle) { html = "<table style=\"" + value.tableStyle + "\">"; } else { html = "<table>"; } html += "<tbody>"; for (row = 0; row < value.rows; row ++) { html += '<tr>'; for (col = 0; col < value.cols; col ++) { html += "<td><br></td>"; } html += '</tr>'; } html += "</tbody></table>"; composer.commands.exec("insertHTML", html); //composer.selection.insertHTML(html); } }, state: function(composer, command) { return false; } }; }(wysihtml5)); ;(function(wysihtml5){ wysihtml5.commands.mergeTableCells = { exec: function(composer, command) { if (composer.tableSelection && composer.tableSelection.start && composer.tableSelection.end) { if (this.state(composer, command)) { wysihtml5.dom.table.unmergeCell(composer.tableSelection.start); } else { wysihtml5.dom.table.mergeCellsBetween(composer.tableSelection.start, composer.tableSelection.end); } } }, state: function(composer, command) { if (composer.tableSelection) { var start = composer.tableSelection.start, end = composer.tableSelection.end; if (start && end && start == end && (( wysihtml5.dom.getAttribute(start, "colspan") && parseInt(wysihtml5.dom.getAttribute(start, "colspan"), 10) > 1 ) || ( wysihtml5.dom.getAttribute(start, "rowspan") && parseInt(wysihtml5.dom.getAttribute(start, "rowspan"), 10) > 1 )) ) { return [start]; } } return false; } }; }(wysihtml5)); ;(function(wysihtml5){ wysihtml5.commands.addTableCells = { exec: function(composer, command, value) { if (composer.tableSelection && composer.tableSelection.start && composer.tableSelection.end) { // switches start and end if start is bigger than end (reverse selection) var tableSelect = wysihtml5.dom.table.orderSelectionEnds(composer.tableSelection.start, composer.tableSelection.end); if (value == "before" || value == "above") { wysihtml5.dom.table.addCells(tableSelect.start, value); } else if (value == "after" || value == "below") { wysihtml5.dom.table.addCells(tableSelect.end, value); } setTimeout(function() { composer.tableSelection.select(tableSelect.start, tableSelect.end); },0); } }, state: function(composer, command) { return false; } }; }(wysihtml5)); ;(function(wysihtml5){ wysihtml5.commands.deleteTableCells = { exec: function(composer, command, value) { if (composer.tableSelection && composer.tableSelection.start && composer.tableSelection.end) { var tableSelect = wysihtml5.dom.table.orderSelectionEnds(composer.tableSelection.start, composer.tableSelection.end), idx = wysihtml5.dom.table.indexOf(tableSelect.start), selCell, table = composer.tableSelection.table; wysihtml5.dom.table.removeCells(tableSelect.start, value); setTimeout(function() { // move selection to next or previous if not present selCell = wysihtml5.dom.table.findCell(table, idx); if (!selCell){ if (value == "row") { selCell = wysihtml5.dom.table.findCell(table, { "row": idx.row - 1, "col": idx.col }); } if (value == "column") { selCell = wysihtml5.dom.table.findCell(table, { "row": idx.row, "col": idx.col - 1 }); } } if (selCell) { composer.tableSelection.select(selCell, selCell); } }, 0); } }, state: function(composer, command) { return false; } }; }(wysihtml5)); ;(function(wysihtml5){ wysihtml5.commands.indentList = { exec: function(composer, command, value) { var listEls = composer.selection.getSelectionParentsByTag('LI'); if (listEls) { return this.tryToPushLiLevel(listEls, composer.selection); } return false; }, state: function(composer, command) { return false; }, tryToPushLiLevel: function(liNodes, selection) { var listTag, list, prevLi, liNode, prevLiList, found = false; selection.executeAndRestoreRangy(function() { for (var i = liNodes.length; i--;) { liNode = liNodes[i]; listTag = (liNode.parentNode.nodeName === 'OL') ? 'OL' : 'UL'; list = liNode.ownerDocument.createElement(listTag); prevLi = wysihtml5.dom.domNode(liNode).prev({nodeTypes: [wysihtml5.ELEMENT_NODE]}); prevLiList = (prevLi) ? prevLi.querySelector('ul, ol') : null; if (prevLi) { if (prevLiList) { prevLiList.appendChild(liNode); } else { list.appendChild(liNode); prevLi.appendChild(list); } found = true; } } }); return found; } }; }(wysihtml5)); ;(function(wysihtml5){ wysihtml5.commands.outdentList = { exec: function(composer, command, value) { var listEls = composer.selection.getSelectionParentsByTag('LI'); if (listEls) { return this.tryToPullLiLevel(listEls, composer); } return false; }, state: function(composer, command) { return false; }, tryToPullLiLevel: function(liNodes, composer) { var listNode, outerListNode, outerLiNode, list, prevLi, liNode, afterList, found = false, that = this; composer.selection.executeAndRestoreRangy(function() { for (var i = liNodes.length; i--;) { liNode = liNodes[i]; if (liNode.parentNode) { listNode = liNode.parentNode; if (listNode.tagName === 'OL' || listNode.tagName === 'UL') { found = true; outerListNode = wysihtml5.dom.getParentElement(listNode.parentNode, { query: 'ol, ul' }, false, composer.element); outerLiNode = wysihtml5.dom.getParentElement(listNode.parentNode, { query: 'li' }, false, composer.element); if (outerListNode && outerLiNode) { if (liNode.nextSibling) { afterList = that.getAfterList(listNode, liNode); liNode.appendChild(afterList); } outerListNode.insertBefore(liNode, outerLiNode.nextSibling); } else { if (liNode.nextSibling) { afterList = that.getAfterList(listNode, liNode); liNode.appendChild(afterList); } for (var j = liNode.childNodes.length; j--;) { listNode.parentNode.insertBefore(liNode.childNodes[j], listNode.nextSibling); } listNode.parentNode.insertBefore(document.createElement('br'), listNode.nextSibling); liNode.parentNode.removeChild(liNode); } // cleanup if (listNode.childNodes.length === 0) { listNode.parentNode.removeChild(listNode); } } } } }); return found; }, getAfterList: function(listNode, liNode) { var nodeName = listNode.nodeName, newList = document.createElement(nodeName); while (liNode.nextSibling) { newList.appendChild(liNode.nextSibling); } return newList; } }; }(wysihtml5)); ;(function(wysihtml5){ var nodeOptions = { nodeName: "SUB", toggle: true }; wysihtml5.commands.subscript = { exec: function(composer, command) { wysihtml5.commands.formatInline.exec(composer, command, nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, nodeOptions); } }; }(wysihtml5)); ;(function(wysihtml5) { var nodeOptions = { nodeName: "SUP", toggle: true }; wysihtml5.commands.superscript = { exec: function(composer, command) { wysihtml5.commands.formatInline.exec(composer, command, nodeOptions); }, state: function(composer, command) { return wysihtml5.commands.formatInline.state(composer, command, nodeOptions); } }; }(wysihtml5)); ;/** * Undo Manager for wysihtml5 * slightly inspired by http://rniwa.com/editing/undomanager.html#the-undomanager-interface */ (function(wysihtml5) { var Z_KEY = 90, Y_KEY = 89, BACKSPACE_KEY = 8, DELETE_KEY = 46, MAX_HISTORY_ENTRIES = 25, DATA_ATTR_NODE = "data-wysihtml5-selection-node", DATA_ATTR_OFFSET = "data-wysihtml5-selection-offset", UNDO_HTML = '<span id="_wysihtml5-undo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>', REDO_HTML = '<span id="_wysihtml5-redo" class="_wysihtml5-temp">' + wysihtml5.INVISIBLE_SPACE + '</span>', dom = wysihtml5.dom; function cleanTempElements(doc) { var tempElement; while (tempElement = doc.querySelector("._wysihtml5-temp")) { tempElement.parentNode.removeChild(tempElement); } } wysihtml5.UndoManager = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.UndoManager.prototype */ { constructor: function(editor) { this.editor = editor; this.composer = editor.composer; this.element = this.composer.element; this.position = 0; this.historyStr = []; this.historyDom = []; this.transact(); this._observe(); }, _observe: function() { var that = this, doc = this.composer.sandbox.getDocument(), lastKey; // Catch CTRL+Z and CTRL+Y dom.observe(this.element, "keydown", function(event) { if (event.altKey || (!event.ctrlKey && !event.metaKey)) { return; } var keyCode = event.keyCode, isUndo = keyCode === Z_KEY && !event.shiftKey, isRedo = (keyCode === Z_KEY && event.shiftKey) || (keyCode === Y_KEY); if (isUndo) { that.undo(); event.preventDefault(); } else if (isRedo) { that.redo(); event.preventDefault(); } }); // Catch delete and backspace dom.observe(this.element, "keydown", function(event) { var keyCode = event.keyCode; if (keyCode === lastKey) { return; } lastKey = keyCode; if (keyCode === BACKSPACE_KEY || keyCode === DELETE_KEY) { that.transact(); } }); this.editor .on("newword:composer", function() { that.transact(); }) .on("beforecommand:composer", function() { that.transact(); }); }, transact: function() { var previousHtml = this.historyStr[this.position - 1], currentHtml = this.composer.getValue(false, false), composerIsVisible = this.element.offsetWidth > 0 && this.element.offsetHeight > 0, range, node, offset, element, position; if (currentHtml === previousHtml) { return; } var length = this.historyStr.length = this.historyDom.length = this.position; if (length > MAX_HISTORY_ENTRIES) { this.historyStr.shift(); this.historyDom.shift(); this.position--; } this.position++; if (composerIsVisible) { // Do not start saving selection if composer is not visible range = this.composer.selection.getRange(); node = (range && range.startContainer) ? range.startContainer : this.element; offset = (range && range.startOffset) ? range.startOffset : 0; if (node.nodeType === wysihtml5.ELEMENT_NODE) { element = node; } else { element = node.parentNode; position = this.getChildNodeIndex(element, node); } element.setAttribute(DATA_ATTR_OFFSET, offset); if (typeof(position) !== "undefined") { element.setAttribute(DATA_ATTR_NODE, position); } } var clone = this.element.cloneNode(!!currentHtml); this.historyDom.push(clone); this.historyStr.push(currentHtml); if (element) { element.removeAttribute(DATA_ATTR_OFFSET); element.removeAttribute(DATA_ATTR_NODE); } }, undo: function() { this.transact(); if (!this.undoPossible()) { return; } this.set(this.historyDom[--this.position - 1]); this.editor.fire("undo:composer"); }, redo: function() { if (!this.redoPossible()) { return; } this.set(this.historyDom[++this.position - 1]); this.editor.fire("redo:composer"); }, undoPossible: function() { return this.position > 1; }, redoPossible: function() { return this.position < this.historyStr.length; }, set: function(historyEntry) { this.element.innerHTML = ""; var i = 0, childNodes = historyEntry.childNodes, length = historyEntry.childNodes.length; for (; i<length; i++) { this.element.appendChild(childNodes[i].cloneNode(true)); } // Restore selection var offset, node, position; if (historyEntry.hasAttribute(DATA_ATTR_OFFSET)) { offset = historyEntry.getAttribute(DATA_ATTR_OFFSET); position = historyEntry.getAttribute(DATA_ATTR_NODE); node = this.element; } else { node = this.element.querySelector("[" + DATA_ATTR_OFFSET + "]") || this.element; offset = node.getAttribute(DATA_ATTR_OFFSET); position = node.getAttribute(DATA_ATTR_NODE); node.removeAttribute(DATA_ATTR_OFFSET); node.removeAttribute(DATA_ATTR_NODE); } if (position !== null) { node = this.getChildNodeByIndex(node, +position); } this.composer.selection.set(node, offset); }, getChildNodeIndex: function(parent, child) { var i = 0, childNodes = parent.childNodes, length = childNodes.length; for (; i<length; i++) { if (childNodes[i] === child) { return i; } } }, getChildNodeByIndex: function(parent, index) { return parent.childNodes[index]; } }); })(wysihtml5); ;/** * TODO: the following methods still need unit test coverage */ wysihtml5.views.View = Base.extend( /** @scope wysihtml5.views.View.prototype */ { constructor: function(parent, textareaElement, config) { this.parent = parent; this.element = textareaElement; this.config = config; if (!this.config.noTextarea) { this._observeViewChange(); } }, _observeViewChange: function() { var that = this; this.parent.on("beforeload", function() { that.parent.on("change_view", function(view) { if (view === that.name) { that.parent.currentView = that; that.show(); // Using tiny delay here to make sure that the placeholder is set before focusing setTimeout(function() { that.focus(); }, 0); } else { that.hide(); } }); }); }, focus: function() { if (this.element && this.element.ownerDocument && this.element.ownerDocument.querySelector(":focus") === this.element) { return; } try { if(this.element) { this.element.focus(); } } catch(e) {} }, hide: function() { this.element.style.display = "none"; }, show: function() { this.element.style.display = ""; }, disable: function() { this.element.setAttribute("disabled", "disabled"); }, enable: function() { this.element.removeAttribute("disabled"); } }); ;(function(wysihtml5) { var dom = wysihtml5.dom, browser = wysihtml5.browser; wysihtml5.views.Composer = wysihtml5.views.View.extend( /** @scope wysihtml5.views.Composer.prototype */ { name: "composer", // Needed for firefox in order to display a proper caret in an empty contentEditable CARET_HACK: "<br>", constructor: function(parent, editableElement, config) { this.base(parent, editableElement, config); if (!this.config.noTextarea) { this.textarea = this.parent.textarea; } else { this.editableArea = editableElement; } if (this.config.contentEditableMode) { this._initContentEditableArea(); } else { this._initSandbox(); } }, clear: function() { this.element.innerHTML = browser.displaysCaretInEmptyContentEditableCorrectly() ? "" : this.CARET_HACK; }, getValue: function(parse, clearInternals) { var value = this.isEmpty() ? "" : wysihtml5.quirks.getCorrectInnerHTML(this.element); if (parse !== false) { value = this.parent.parse(value, (clearInternals === false) ? false : true); } return value; }, setValue: function(html, parse) { if (parse) { html = this.parent.parse(html); } try { this.element.innerHTML = html; } catch (e) { this.element.innerText = html; } }, cleanUp: function() { var bookmark; if (this.selection) { bookmark = rangy.saveSelection(this.win); } this.parent.parse(this.element); if (bookmark) { rangy.restoreSelection(bookmark); } }, show: function() { this.editableArea.style.display = this._displayStyle || ""; if (!this.config.noTextarea && !this.textarea.element.disabled) { // Firefox needs this, otherwise contentEditable becomes uneditable this.disable(); this.enable(); } }, hide: function() { this._displayStyle = dom.getStyle("display").from(this.editableArea); if (this._displayStyle === "none") { this._displayStyle = null; } this.editableArea.style.display = "none"; }, disable: function() { this.parent.fire("disable:composer"); this.element.removeAttribute("contentEditable"); }, enable: function() { this.parent.fire("enable:composer"); this.element.setAttribute("contentEditable", "true"); }, focus: function(setToEnd) { // IE 8 fires the focus event after .focus() // This is needed by our simulate_placeholder.js to work // therefore we clear it ourselves this time if (wysihtml5.browser.doesAsyncFocus() && this.hasPlaceholderSet()) { this.clear(); } this.base(); var lastChild = this.element.lastChild; if (setToEnd && lastChild && this.selection) { if (lastChild.nodeName === "BR") { this.selection.setBefore(this.element.lastChild); } else { this.selection.setAfter(this.element.lastChild); } } }, getScrollPos: function() { if (this.doc && this.win) { var pos = {}; if (typeof this.win.pageYOffset !== "undefined") { pos.y = this.win.pageYOffset; } else { pos.y = (this.doc.documentElement || this.doc.body.parentNode || this.doc.body).scrollTop; } if (typeof this.win.pageXOffset !== "undefined") { pos.x = this.win.pageXOffset; } else { pos.x = (this.doc.documentElement || this.doc.body.parentNode || this.doc.body).scrollLeft; } return pos; } }, setScrollPos: function(pos) { if (pos && typeof pos.x !== "undefined" && typeof pos.y !== "undefined") { this.win.scrollTo(pos.x, pos.y); } }, getTextContent: function() { return dom.getTextContent(this.element); }, hasPlaceholderSet: function() { return this.getTextContent() == ((this.config.noTextarea) ? this.editableArea.getAttribute("data-placeholder") : this.textarea.element.getAttribute("placeholder")) && this.placeholderSet; }, isEmpty: function() { var innerHTML = this.element.innerHTML.toLowerCase(); return (/^(\s|<br>|<\/br>|<p>|<\/p>)*$/i).test(innerHTML) || innerHTML === "" || innerHTML === "<br>" || innerHTML === "<p></p>" || innerHTML === "<p><br></p>" || this.hasPlaceholderSet(); }, _initContentEditableArea: function() { var that = this; if (this.config.noTextarea) { this.sandbox = new dom.ContentEditableArea(function() { that._create(); }, { className: this.config.classNames.sandbox }, this.editableArea); } else { this.sandbox = new dom.ContentEditableArea(function() { that._create(); }, { className: this.config.classNames.sandbox }); this.editableArea = this.sandbox.getContentEditable(); dom.insert(this.editableArea).after(this.textarea.element); this._createWysiwygFormField(); } }, _initSandbox: function() { var that = this; this.sandbox = new dom.Sandbox(function() { that._create(); }, { stylesheets: this.config.stylesheets, className: this.config.classNames.sandbox }); this.editableArea = this.sandbox.getIframe(); var textareaElement = this.textarea.element; dom.insert(this.editableArea).after(textareaElement); this._createWysiwygFormField(); }, // Creates hidden field which tells the server after submit, that the user used an wysiwyg editor _createWysiwygFormField: function() { if (this.textarea.element.form) { var hiddenField = document.createElement("input"); hiddenField.type = "hidden"; hiddenField.name = "_wysihtml5_mode"; hiddenField.value = 1; dom.insert(hiddenField).after(this.textarea.element); } }, _create: function() { var that = this; this.doc = this.sandbox.getDocument(); this.win = this.sandbox.getWindow(); this.element = (this.config.contentEditableMode) ? this.sandbox.getContentEditable() : this.doc.body; if (!this.config.noTextarea) { this.textarea = this.parent.textarea; this.element.innerHTML = this.textarea.getValue(true, false); } else { this.cleanUp(); // cleans contenteditable on initiation as it may contain html } // Make sure our selection handler is ready this.selection = new wysihtml5.Selection(this.parent, this.element, this.config.classNames.uneditableContainer); // Make sure commands dispatcher is ready this.commands = new wysihtml5.Commands(this.parent); if (!this.config.noTextarea) { dom.copyAttributes([ "className", "spellcheck", "title", "lang", "dir", "accessKey" ]).from(this.textarea.element).to(this.element); } dom.addClass(this.element, this.config.classNames.composer); // // Make the editor look like the original textarea, by syncing styles if (this.config.style && !this.config.contentEditableMode) { this.style(); } this.observe(); var name = this.config.name; if (name) { dom.addClass(this.element, name); if (!this.config.contentEditableMode) { dom.addClass(this.editableArea, name); } } this.enable(); if (!this.config.noTextarea && this.textarea.element.disabled) { this.disable(); } // Simulate html5 placeholder attribute on contentEditable element var placeholderText = typeof(this.config.placeholder) === "string" ? this.config.placeholder : ((this.config.noTextarea) ? this.editableArea.getAttribute("data-placeholder") : this.textarea.element.getAttribute("placeholder")); if (placeholderText) { dom.simulatePlaceholder(this.parent, this, placeholderText, this.config.classNames.placeholder); } // Make sure that the browser avoids using inline styles whenever possible this.commands.exec("styleWithCSS", false); this._initAutoLinking(); this._initObjectResizing(); this._initUndoManager(); this._initLineBreaking(); // Simulate html5 autofocus on contentEditable element // This doesn't work on IOS (5.1.1) if (!this.config.noTextarea && (this.textarea.element.hasAttribute("autofocus") || document.querySelector(":focus") == this.textarea.element) && !browser.isIos()) { setTimeout(function() { that.focus(true); }, 100); } // IE sometimes leaves a single paragraph, which can't be removed by the user if (!browser.clearsContentEditableCorrectly()) { wysihtml5.quirks.ensureProperClearing(this); } // Set up a sync that makes sure that textarea and editor have the same content if (this.initSync && this.config.sync) { this.initSync(); } // Okay hide the textarea, we are ready to go if (!this.config.noTextarea) { this.textarea.hide(); } // Fire global (before-)load event this.parent.fire("beforeload").fire("load"); }, _initAutoLinking: function() { var that = this, supportsDisablingOfAutoLinking = browser.canDisableAutoLinking(), supportsAutoLinking = browser.doesAutoLinkingInContentEditable(); if (supportsDisablingOfAutoLinking) { this.commands.exec("autoUrlDetect", false); } if (!this.config.autoLink) { return; } // Only do the auto linking by ourselves when the browser doesn't support auto linking // OR when he supports auto linking but we were able to turn it off (IE9+) if (!supportsAutoLinking || (supportsAutoLinking && supportsDisablingOfAutoLinking)) { this.parent.on("newword:composer", function() { if (dom.getTextContent(that.element).match(dom.autoLink.URL_REG_EXP)) { var nodeWithSelection = that.selection.getSelectedNode(), uneditables = that.element.querySelectorAll("." + that.config.classNames.uneditableContainer), isInUneditable = false; for (var i = uneditables.length; i--;) { if (wysihtml5.dom.contains(uneditables[i], nodeWithSelection)) { isInUneditable = true; } } if (!isInUneditable) dom.autoLink(nodeWithSelection, [that.config.classNames.uneditableContainer]); } }); dom.observe(this.element, "blur", function() { dom.autoLink(that.element, [that.config.classNames.uneditableContainer]); }); } // Assuming we have the following: // <a href="http://www.google.de">http://www.google.de</a> // If a user now changes the url in the innerHTML we want to make sure that // it's synchronized with the href attribute (as long as the innerHTML is still a url) var // Use a live NodeList to check whether there are any links in the document links = this.sandbox.getDocument().getElementsByTagName("a"), // The autoLink helper method reveals a reg exp to detect correct urls urlRegExp = dom.autoLink.URL_REG_EXP, getTextContent = function(element) { var textContent = wysihtml5.lang.string(dom.getTextContent(element)).trim(); if (textContent.substr(0, 4) === "www.") { textContent = "http://" + textContent; } return textContent; }; dom.observe(this.element, "keydown", function(event) { if (!links.length) { return; } var selectedNode = that.selection.getSelectedNode(event.target.ownerDocument), link = dom.getParentElement(selectedNode, { query: "a" }, 4), textContent; if (!link) { return; } textContent = getTextContent(link); // keydown is fired before the actual content is changed // therefore we set a timeout to change the href setTimeout(function() { var newTextContent = getTextContent(link); if (newTextContent === textContent) { return; } // Only set href when new href looks like a valid url if (newTextContent.match(urlRegExp)) { link.setAttribute("href", newTextContent); } }, 0); }); }, _initObjectResizing: function() { this.commands.exec("enableObjectResizing", true); // IE sets inline styles after resizing objects // The following lines make sure that the width/height css properties // are copied over to the width/height attributes if (browser.supportsEvent("resizeend")) { var properties = ["width", "height"], propertiesLength = properties.length, element = this.element; dom.observe(element, "resizeend", function(event) { var target = event.target || event.srcElement, style = target.style, i = 0, property; if (target.nodeName !== "IMG") { return; } for (; i<propertiesLength; i++) { property = properties[i]; if (style[property]) { target.setAttribute(property, parseInt(style[property], 10)); style[property] = ""; } } // After resizing IE sometimes forgets to remove the old resize handles wysihtml5.quirks.redraw(element); }); } }, _initUndoManager: function() { this.undoManager = new wysihtml5.UndoManager(this.parent); }, _initLineBreaking: function() { var that = this, USE_NATIVE_LINE_BREAK_INSIDE_TAGS = "li, p, h1, h2, h3, h4, h5, h6", LIST_TAGS = "ul, ol, menu"; function adjust(selectedNode) { var parentElement = dom.getParentElement(selectedNode, { query: "p, div" }, 2); if (parentElement && dom.contains(that.element, parentElement)) { that.selection.executeAndRestore(function() { if (that.config.useLineBreaks) { dom.replaceWithChildNodes(parentElement); } else if (parentElement.nodeName !== "P") { dom.renameElement(parentElement, "p"); } }); } } if (!this.config.useLineBreaks) { dom.observe(this.element, ["focus", "keydown"], function() { if (that.isEmpty()) { var paragraph = that.doc.createElement("P"); that.element.innerHTML = ""; that.element.appendChild(paragraph); if (!browser.displaysCaretInEmptyContentEditableCorrectly()) { paragraph.innerHTML = "<br>"; that.selection.setBefore(paragraph.firstChild); } else { that.selection.selectNode(paragraph, true); } } }); } // Under certain circumstances Chrome + Safari create nested <p> or <hX> tags after paste // Inserting an invisible white space in front of it fixes the issue // This is too hacky and causes selection not to replace content on paste in chrome /* if (browser.createsNestedInvalidMarkupAfterPaste()) { dom.observe(this.element, "paste", function(event) { var invisibleSpace = that.doc.createTextNode(wysihtml5.INVISIBLE_SPACE); that.selection.insertNode(invisibleSpace); }); }*/ dom.observe(this.element, "keydown", function(event) { var keyCode = event.keyCode; if (event.shiftKey) { return; } if (keyCode !== wysihtml5.ENTER_KEY && keyCode !== wysihtml5.BACKSPACE_KEY) { return; } var blockElement = dom.getParentElement(that.selection.getSelectedNode(), { query: USE_NATIVE_LINE_BREAK_INSIDE_TAGS }, 4); if (blockElement) { setTimeout(function() { // Unwrap paragraph after leaving a list or a H1-6 var selectedNode = that.selection.getSelectedNode(), list; if (blockElement.nodeName === "LI") { if (!selectedNode) { return; } list = dom.getParentElement(selectedNode, { query: LIST_TAGS }, 2); if (!list) { adjust(selectedNode); } } if (keyCode === wysihtml5.ENTER_KEY && blockElement.nodeName.match(/^H[1-6]$/)) { adjust(selectedNode); } }, 0); return; } if (that.config.useLineBreaks && keyCode === wysihtml5.ENTER_KEY && !wysihtml5.browser.insertsLineBreaksOnReturn()) { event.preventDefault(); that.commands.exec("insertLineBreak"); } }); } }); })(wysihtml5); ;(function(wysihtml5) { var dom = wysihtml5.dom, doc = document, win = window, HOST_TEMPLATE = doc.createElement("div"), /** * Styles to copy from textarea to the composer element */ TEXT_FORMATTING = [ "background-color", "color", "cursor", "font-family", "font-size", "font-style", "font-variant", "font-weight", "line-height", "letter-spacing", "text-align", "text-decoration", "text-indent", "text-rendering", "word-break", "word-wrap", "word-spacing" ], /** * Styles to copy from textarea to the iframe */ BOX_FORMATTING = [ "background-color", "border-collapse", "border-bottom-color", "border-bottom-style", "border-bottom-width", "border-left-color", "border-left-style", "border-left-width", "border-right-color", "border-right-style", "border-right-width", "border-top-color", "border-top-style", "border-top-width", "clear", "display", "float", "margin-bottom", "margin-left", "margin-right", "margin-top", "outline-color", "outline-offset", "outline-width", "outline-style", "padding-left", "padding-right", "padding-top", "padding-bottom", "position", "top", "left", "right", "bottom", "z-index", "vertical-align", "text-align", "-webkit-box-sizing", "-moz-box-sizing", "-ms-box-sizing", "box-sizing", "-webkit-box-shadow", "-moz-box-shadow", "-ms-box-shadow","box-shadow", "-webkit-border-top-right-radius", "-moz-border-radius-topright", "border-top-right-radius", "-webkit-border-bottom-right-radius", "-moz-border-radius-bottomright", "border-bottom-right-radius", "-webkit-border-bottom-left-radius", "-moz-border-radius-bottomleft", "border-bottom-left-radius", "-webkit-border-top-left-radius", "-moz-border-radius-topleft", "border-top-left-radius", "width", "height" ], ADDITIONAL_CSS_RULES = [ "html { height: 100%; }", "body { height: 100%; padding: 1px 0 0 0; margin: -1px 0 0 0; }", "body > p:first-child { margin-top: 0; }", "._wysihtml5-temp { display: none; }", wysihtml5.browser.isGecko ? "body.placeholder { color: graytext !important; }" : "body.placeholder { color: #a9a9a9 !important; }", // Ensure that user see's broken images and can delete them "img:-moz-broken { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }" ]; /** * With "setActive" IE offers a smart way of focusing elements without scrolling them into view: * http://msdn.microsoft.com/en-us/library/ms536738(v=vs.85).aspx * * Other browsers need a more hacky way: (pssst don't tell my mama) * In order to prevent the element being scrolled into view when focusing it, we simply * move it out of the scrollable area, focus it, and reset it's position */ var focusWithoutScrolling = function(element) { if (element.setActive) { // Following line could cause a js error when the textarea is invisible // See https://github.com/xing/wysihtml5/issues/9 try { element.setActive(); } catch(e) {} } else { var elementStyle = element.style, originalScrollTop = doc.documentElement.scrollTop || doc.body.scrollTop, originalScrollLeft = doc.documentElement.scrollLeft || doc.body.scrollLeft, originalStyles = { position: elementStyle.position, top: elementStyle.top, left: elementStyle.left, WebkitUserSelect: elementStyle.WebkitUserSelect }; dom.setStyles({ position: "absolute", top: "-99999px", left: "-99999px", // Don't ask why but temporarily setting -webkit-user-select to none makes the whole thing performing smoother WebkitUserSelect: "none" }).on(element); element.focus(); dom.setStyles(originalStyles).on(element); if (win.scrollTo) { // Some browser extensions unset this method to prevent annoyances // "Better PopUp Blocker" for Chrome http://code.google.com/p/betterpopupblocker/source/browse/trunk/blockStart.js#100 // Issue: http://code.google.com/p/betterpopupblocker/issues/detail?id=1 win.scrollTo(originalScrollLeft, originalScrollTop); } } }; wysihtml5.views.Composer.prototype.style = function() { var that = this, originalActiveElement = doc.querySelector(":focus"), textareaElement = this.textarea.element, hasPlaceholder = textareaElement.hasAttribute("placeholder"), originalPlaceholder = hasPlaceholder && textareaElement.getAttribute("placeholder"), originalDisplayValue = textareaElement.style.display, originalDisabled = textareaElement.disabled, displayValueForCopying; this.focusStylesHost = HOST_TEMPLATE.cloneNode(false); this.blurStylesHost = HOST_TEMPLATE.cloneNode(false); this.disabledStylesHost = HOST_TEMPLATE.cloneNode(false); // Remove placeholder before copying (as the placeholder has an affect on the computed style) if (hasPlaceholder) { textareaElement.removeAttribute("placeholder"); } if (textareaElement === originalActiveElement) { textareaElement.blur(); } // enable for copying styles textareaElement.disabled = false; // set textarea to display="none" to get cascaded styles via getComputedStyle textareaElement.style.display = displayValueForCopying = "none"; if ((textareaElement.getAttribute("rows") && dom.getStyle("height").from(textareaElement) === "auto") || (textareaElement.getAttribute("cols") && dom.getStyle("width").from(textareaElement) === "auto")) { textareaElement.style.display = displayValueForCopying = originalDisplayValue; } // --------- iframe styles (has to be set before editor styles, otherwise IE9 sets wrong fontFamily on blurStylesHost) --------- dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.editableArea).andTo(this.blurStylesHost); // --------- editor styles --------- dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.element).andTo(this.blurStylesHost); // --------- apply standard rules --------- dom.insertCSS(ADDITIONAL_CSS_RULES).into(this.element.ownerDocument); // --------- :disabled styles --------- textareaElement.disabled = true; dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.disabledStylesHost); dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.disabledStylesHost); textareaElement.disabled = originalDisabled; // --------- :focus styles --------- textareaElement.style.display = originalDisplayValue; focusWithoutScrolling(textareaElement); textareaElement.style.display = displayValueForCopying; dom.copyStyles(BOX_FORMATTING).from(textareaElement).to(this.focusStylesHost); dom.copyStyles(TEXT_FORMATTING).from(textareaElement).to(this.focusStylesHost); // reset textarea textareaElement.style.display = originalDisplayValue; dom.copyStyles(["display"]).from(textareaElement).to(this.editableArea); // Make sure that we don't change the display style of the iframe when copying styles oblur/onfocus // this is needed for when the change_view event is fired where the iframe is hidden and then // the blur event fires and re-displays it var boxFormattingStyles = wysihtml5.lang.array(BOX_FORMATTING).without(["display"]); // --------- restore focus --------- if (originalActiveElement) { originalActiveElement.focus(); } else { textareaElement.blur(); } // --------- restore placeholder --------- if (hasPlaceholder) { textareaElement.setAttribute("placeholder", originalPlaceholder); } // --------- Sync focus/blur styles --------- this.parent.on("focus:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.focusStylesHost).to(that.editableArea); dom.copyStyles(TEXT_FORMATTING) .from(that.focusStylesHost).to(that.element); }); this.parent.on("blur:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.blurStylesHost).to(that.editableArea); dom.copyStyles(TEXT_FORMATTING) .from(that.blurStylesHost).to(that.element); }); this.parent.observe("disable:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.disabledStylesHost).to(that.editableArea); dom.copyStyles(TEXT_FORMATTING) .from(that.disabledStylesHost).to(that.element); }); this.parent.observe("enable:composer", function() { dom.copyStyles(boxFormattingStyles) .from(that.blurStylesHost).to(that.editableArea); dom.copyStyles(TEXT_FORMATTING) .from(that.blurStylesHost).to(that.element); }); return this; }; })(wysihtml5); ;/** * Taking care of events * - Simulating 'change' event on contentEditable element * - Handling drag & drop logic * - Catch paste events * - Dispatch proprietary newword:composer event * - Keyboard shortcuts */ (function(wysihtml5) { var dom = wysihtml5.dom, browser = wysihtml5.browser, /** * Map keyCodes to query commands */ shortcuts = { "66": "bold", // B "73": "italic", // I "85": "underline" // U }; // Adds multiple eventlisteners to target, bound to one callback // TODO: If needed elsewhere make it part of wysihtml5.dom or sth var addListeners = function (target, events, callback) { for(var i = 0, max = events.length; i < max; i++) { target.addEventListener(events[i], callback, false); } }; // Removes multiple eventlisteners from target, bound to one callback // TODO: If needed elsewhere make it part of wysihtml5.dom or sth var removeListeners = function (target, events, callback) { for(var i = 0, max = events.length; i < max; i++) { target.removeEventListener(events[i], callback, false); } }; // Override for giving user ability to delete last line break in table cell var fixLastBrDeletionInTable = function(composer, force) { if (composer.selection.caretIsLastInSelection()) { var sel = composer.selection.getSelection(), aNode = sel.anchorNode; if (aNode && aNode.nodeType === 1 && (wysihtml5.dom.getParentElement(aNode, {query: 'td, th'}, false, composer.element) || force)) { var nextNode = aNode.childNodes[sel.anchorOffset]; if (nextNode && nextNode.nodeType === 1 & nextNode.nodeName === "BR") { nextNode.parentNode.removeChild(nextNode); return true; } } } return false; }; // If found an uneditable before caret then notify it before deletion var handleUneditableDeletion = function(composer) { var before = composer.selection.getBeforeSelection(true); if (before && (before.type === "element" || before.type === "leafnode") && before.node.nodeType === 1 && before.node.classList.contains(composer.config.classNames.uneditableContainer)) { if (fixLastBrDeletionInTable(composer, true)) { return true; } try { var ev = new CustomEvent("wysihtml5:uneditable:delete"); before.node.dispatchEvent(ev); } catch (err) {} before.node.parentNode.removeChild(before.node); return true; } return false; }; // Deletion with caret in the beginning of headings needs special attention // Heading does not concate text to previous block node correctly (browsers do unexpected miracles here especially webkit) var fixDeleteInTheBeginnigOfHeading = function(composer) { var selection = composer.selection, prevNode = selection.getPreviousNode(); if (selection.caretIsFirstInSelection() && prevNode && prevNode.nodeType === 1 && (/block/).test(composer.win.getComputedStyle(prevNode).display) ) { if ((/^\s*$/).test(prevNode.textContent || prevNode.innerText)) { // If heading is empty remove the heading node prevNode.parentNode.removeChild(prevNode); return true; } else { if (prevNode.lastChild) { var selNode = prevNode.lastChild, selectedNode = selection.getSelectedNode(), commonAncestorNode = wysihtml5.dom.domNode(prevNode).commonAncestor(selectedNode, composer.element); curNode = commonAncestorNode ? wysihtml5.dom.getParentElement(selectedNode, { query: "h1, h2, h3, h4, h5, h6, p, pre, div, blockquote" }, false, commonAncestorNode) : null; if (curNode) { while (curNode.firstChild) { prevNode.appendChild(curNode.firstChild); } selection.setAfter(selNode); return true; } else if (selectedNode.nodeType === 3) { prevNode.appendChild(selectedNode); selection.setAfter(selNode); return true; } } } } return false; }; var handleDeleteKeyPress = function(event, composer) { var selection = composer.selection, element = composer.element; if (selection.isCollapsed()) { if (fixDeleteInTheBeginnigOfHeading(composer)) { event.preventDefault(); return; } if (fixLastBrDeletionInTable(composer)) { event.preventDefault(); return; } if (handleUneditableDeletion(composer)) { event.preventDefault(); return; } } else { if (selection.containsUneditable()) { event.preventDefault(); selection.deleteContents(); } } }; var handleTabKeyDown = function(composer, element, shiftKey) { if (!composer.selection.isCollapsed()) { composer.selection.deleteContents(); } else if (composer.selection.caretIsInTheBeginnig('li')) { if (shiftKey) { if (composer.commands.exec('outdentList')) return; } else { if (composer.commands.exec('indentList')) return; } } // Is &emsp; close enough to tab. Could not find enough counter arguments for now. composer.commands.exec("insertHTML", "&emsp;"); }; var handleDomNodeRemoved = function(event) { if (this.domNodeRemovedInterval) { clearInterval(domNodeRemovedInterval); } this.parent.fire("destroy:composer"); }; // Listens to "drop", "paste", "mouseup", "focus", "keyup" events and fires var handleUserInteraction = function (event) { this.parent.fire("beforeinteraction", event).fire("beforeinteraction:composer", event); setTimeout((function() { this.parent.fire("interaction", event).fire("interaction:composer", event); }).bind(this), 0); }; var handleFocus = function(event) { this.parent.fire("focus", event).fire("focus:composer", event); // Delay storing of state until all focus handler are fired // especially the one which resets the placeholder setTimeout((function() { this.focusState = this.getValue(false, false); }).bind(this), 0); }; var handleBlur = function(event) { if (this.focusState !== this.getValue(false, false)) { //create change event if supported (all except IE8) var changeevent = event; if(typeof Object.create == 'function') { changeevent = Object.create(event, { type: { value: 'change' } }); } this.parent.fire("change", changeevent).fire("change:composer", changeevent); } this.parent.fire("blur", event).fire("blur:composer", event); }; var handlePaste = function(event) { this.parent.fire(event.type, event).fire(event.type + ":composer", event); if (event.type === "paste") { setTimeout((function() { this.parent.fire("newword:composer"); }).bind(this), 0); } }; var handleCopy = function(event) { if (this.config.copyedFromMarking) { // If supported the copied source can be based directly on selection // Very useful for webkit based browsers where copy will otherwise contain a lot of code and styles based on whatever and not actually in selection. if (event.clipboardData) { event.clipboardData.setData("text/html", this.config.copyedFromMarking + this.selection.getHtml()); event.clipboardData.setData("text/plain", this.selection.getPlainText()); event.preventDefault(); } this.parent.fire(event.type, event).fire(event.type + ":composer", event); } }; var handleKeyUp = function(event) { var keyCode = event.keyCode; if (keyCode === wysihtml5.SPACE_KEY || keyCode === wysihtml5.ENTER_KEY) { this.parent.fire("newword:composer"); } }; var handleMouseDown = function(event) { if (!browser.canSelectImagesInContentEditable()) { // Make sure that images are selected when clicking on them var target = event.target, allImages = this.element.querySelectorAll('img'), notMyImages = this.element.querySelectorAll('.' + this.config.classNames.uneditableContainer + ' img'), myImages = wysihtml5.lang.array(allImages).without(notMyImages); if (target.nodeName === "IMG" && wysihtml5.lang.array(myImages).contains(target)) { this.selection.selectNode(target); } } }; // TODO: mouseover is not actually a foolproof and obvious place for this, must be changed as it modifies dom on random basis // Shows url in tooltip when hovering links or images var handleMouseOver = function(event) { var titlePrefixes = { IMG: "Image: ", A: "Link: " }, target = event.target, nodeName = target.nodeName, title; if (nodeName !== "A" && nodeName !== "IMG") { return; } if(!target.hasAttribute("title")){ title = titlePrefixes[nodeName] + (target.getAttribute("href") || target.getAttribute("src")); target.setAttribute("title", title); } }; var handleClick = function(event) { if (this.config.classNames.uneditableContainer) { // If uneditables is configured, makes clicking on uneditable move caret after clicked element (so it can be deleted like text) // If uneditable needs text selection itself event.stopPropagation can be used to prevent this behaviour var uneditable = wysihtml5.dom.getParentElement(event.target, { query: "." + this.config.classNames.uneditableContainer }, false, this.element); if (uneditable) { this.selection.setAfter(uneditable); } } }; var handleDrop = function(event) { if (!browser.canSelectImagesInContentEditable()) { // TODO: if I knew how to get dropped elements list from event I could limit it to only IMG element case setTimeout((function() { this.selection.getSelection().removeAllRanges(); }).bind(this), 0); } }; var handleKeyDown = function(event) { var keyCode = event.keyCode, command = shortcuts[keyCode], target, parent; // Select all (meta/ctrl + a) if ((event.ctrlKey || event.metaKey) && keyCode === 65) { this.selection.selectAll(); event.preventDefault(); return; } // Shortcut logic if ((event.ctrlKey || event.metaKey) && !event.altKey && command) { this.commands.exec(command); event.preventDefault(); } if (keyCode === wysihtml5.BACKSPACE_KEY) { // Delete key override for special cases handleDeleteKeyPress(event, this); } // Make sure that when pressing backspace/delete on selected images deletes the image and it's anchor if (keyCode === wysihtml5.BACKSPACE_KEY || keyCode === wysihtml5.DELETE_KEY) { target = this.selection.getSelectedNode(true); if (target && target.nodeName === "IMG") { event.preventDefault(); parent = target.parentNode; parent.removeChild(target);// delete the <img> // And it's parent <a> too if it hasn't got any other child nodes if (parent.nodeName === "A" && !parent.firstChild) { parent.parentNode.removeChild(parent); } setTimeout((function() { wysihtml5.quirks.redraw(this.element); }).bind(this), 0); } } if (this.config.handleTabKey && keyCode === wysihtml5.TAB_KEY) { // TAB key handling event.preventDefault(); handleTabKeyDown(this, this.element, event.shiftKey); } }; var handleIframeFocus = function(event) { setTimeout((function() { if (this.doc.querySelector(":focus") !== this.element) { this.focus(); } }).bind(this), 0); }; var handleIframeBlur = function(event) { setTimeout((function() { this.selection.getSelection().removeAllRanges(); }).bind(this), 0); }; // Table management // If present enableObjectResizing and enableInlineTableEditing command should be called with false to prevent native table handlers var initTableHandling = function () { var hideHandlers = function () { this.doc.execCommand("enableObjectResizing", false, "false"); this.doc.execCommand("enableInlineTableEditing", false, "false"); }, iframeInitiator = (function() { hideHandlers.call(this); removeListeners(this.sandbox.getIframe(), ["focus", "mouseup", "mouseover"], iframeInitiator); }).bind(this); if( this.doc.execCommand && wysihtml5.browser.supportsCommand(this.doc, "enableObjectResizing") && wysihtml5.browser.supportsCommand(this.doc, "enableInlineTableEditing")) { if (this.sandbox.getIframe) { addListeners(this.sandbox.getIframe(), ["focus", "mouseup", "mouseover"], iframeInitiator); } else { setTimeout((function() { hideHandlers.call(this); }).bind(this), 0); } } this.tableSelection = wysihtml5.quirks.tableCellsSelection(this.element, this.parent); }; wysihtml5.views.Composer.prototype.observe = function() { var that = this, container = (this.sandbox.getIframe) ? this.sandbox.getIframe() : this.sandbox.getContentEditable(), element = this.element, focusBlurElement = (browser.supportsEventsInIframeCorrectly() || this.sandbox.getContentEditable) ? this.element : this.sandbox.getWindow(); this.focusState = this.getValue(false, false); // --------- destroy:composer event --------- container.addEventListener(["DOMNodeRemoved"], handleDomNodeRemoved.bind(this), false); // DOMNodeRemoved event is not supported in IE 8 // TODO: try to figure out a polyfill style fix, so it could be transferred to polyfills and removed if ie8 is not needed if (!browser.supportsMutationEvents()) { this.domNodeRemovedInterval = setInterval(function() { if (!dom.contains(document.documentElement, container)) { handleDomNodeRemoved.call(this); } }, 250); } // --------- User interactions -- if (this.config.handleTables) { // If handleTables option is true, table handling functions are bound initTableHandling.call(this); } addListeners(focusBlurElement, ["drop", "paste", "mouseup", "focus", "keyup"], handleUserInteraction.bind(this)); focusBlurElement.addEventListener("focus", handleFocus.bind(this), false); focusBlurElement.addEventListener("blur", handleBlur.bind(this), false); addListeners(this.element, ["drop", "paste", "beforepaste"], handlePaste.bind(this), false); this.element.addEventListener("copy", handleCopy.bind(this), false); this.element.addEventListener("mousedown", handleMouseDown.bind(this), false); this.element.addEventListener("mouseover", handleMouseOver.bind(this), false); this.element.addEventListener("click", handleClick.bind(this), false); this.element.addEventListener("drop", handleDrop.bind(this), false); this.element.addEventListener("keyup", handleKeyUp.bind(this), false); this.element.addEventListener("keydown", handleKeyDown.bind(this), false); this.element.addEventListener("dragenter", (function() { this.parent.fire("unset_placeholder"); }).bind(this), false); }; })(wysihtml5); ;/** * Class that takes care that the value of the composer and the textarea is always in sync */ (function(wysihtml5) { var INTERVAL = 400; wysihtml5.views.Synchronizer = Base.extend( /** @scope wysihtml5.views.Synchronizer.prototype */ { constructor: function(editor, textarea, composer) { this.editor = editor; this.textarea = textarea; this.composer = composer; this._observe(); }, /** * Sync html from composer to textarea * Takes care of placeholders * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the textarea */ fromComposerToTextarea: function(shouldParseHtml) { this.textarea.setValue(wysihtml5.lang.string(this.composer.getValue(false, false)).trim(), shouldParseHtml); }, /** * Sync value of textarea to composer * Takes care of placeholders * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer */ fromTextareaToComposer: function(shouldParseHtml) { var textareaValue = this.textarea.getValue(false, false); if (textareaValue) { this.composer.setValue(textareaValue, shouldParseHtml); } else { this.composer.clear(); this.editor.fire("set_placeholder"); } }, /** * Invoke syncing based on view state * @param {Boolean} shouldParseHtml Whether the html should be sanitized before inserting it into the composer/textarea */ sync: function(shouldParseHtml) { if (this.editor.currentView.name === "textarea") { this.fromTextareaToComposer(shouldParseHtml); } else { this.fromComposerToTextarea(shouldParseHtml); } }, /** * Initializes interval-based syncing * also makes sure that on-submit the composer's content is synced with the textarea * immediately when the form gets submitted */ _observe: function() { var interval, that = this, form = this.textarea.element.form, startInterval = function() { interval = setInterval(function() { that.fromComposerToTextarea(); }, INTERVAL); }, stopInterval = function() { clearInterval(interval); interval = null; }; startInterval(); if (form) { // If the textarea is in a form make sure that after onreset and onsubmit the composer // has the correct state wysihtml5.dom.observe(form, "submit", function() { that.sync(true); }); wysihtml5.dom.observe(form, "reset", function() { setTimeout(function() { that.fromTextareaToComposer(); }, 0); }); } this.editor.on("change_view", function(view) { if (view === "composer" && !interval) { that.fromTextareaToComposer(true); startInterval(); } else if (view === "textarea") { that.fromComposerToTextarea(true); stopInterval(); } }); this.editor.on("destroy:composer", stopInterval); } }); })(wysihtml5); ;(function(wysihtml5) { wysihtml5.views.SourceView = Base.extend( /** @scope wysihtml5.views.SourceView.prototype */ { constructor: function(editor, composer) { this.editor = editor; this.composer = composer; this._observe(); }, switchToTextarea: function(shouldParseHtml) { var composerStyles = this.composer.win.getComputedStyle(this.composer.element), width = parseFloat(composerStyles.width), height = Math.max(parseFloat(composerStyles.height), 100); if (!this.textarea) { this.textarea = this.composer.doc.createElement('textarea'); this.textarea.className = "wysihtml5-source-view"; } this.textarea.style.width = width + 'px'; this.textarea.style.height = height + 'px'; this.textarea.value = this.editor.getValue(shouldParseHtml, true); this.composer.element.parentNode.insertBefore(this.textarea, this.composer.element); this.editor.currentView = "source"; this.composer.element.style.display = 'none'; }, switchToComposer: function(shouldParseHtml) { var textareaValue = this.textarea.value; if (textareaValue) { this.composer.setValue(textareaValue, shouldParseHtml); } else { this.composer.clear(); this.editor.fire("set_placeholder"); } this.textarea.parentNode.removeChild(this.textarea); this.editor.currentView = this.composer; this.composer.element.style.display = ''; }, _observe: function() { this.editor.on("change_view", function(view) { if (view === "composer") { this.switchToComposer(true); } else if (view === "textarea") { this.switchToTextarea(true); } }.bind(this)); } }); })(wysihtml5); ;wysihtml5.views.Textarea = wysihtml5.views.View.extend( /** @scope wysihtml5.views.Textarea.prototype */ { name: "textarea", constructor: function(parent, textareaElement, config) { this.base(parent, textareaElement, config); this._observe(); }, clear: function() { this.element.value = ""; }, getValue: function(parse) { var value = this.isEmpty() ? "" : this.element.value; if (parse !== false) { value = this.parent.parse(value); } return value; }, setValue: function(html, parse) { if (parse) { html = this.parent.parse(html); } this.element.value = html; }, cleanUp: function() { var html = this.parent.parse(this.element.value); this.element.value = html; }, hasPlaceholderSet: function() { var supportsPlaceholder = wysihtml5.browser.supportsPlaceholderAttributeOn(this.element), placeholderText = this.element.getAttribute("placeholder") || null, value = this.element.value, isEmpty = !value; return (supportsPlaceholder && isEmpty) || (value === placeholderText); }, isEmpty: function() { return !wysihtml5.lang.string(this.element.value).trim() || this.hasPlaceholderSet(); }, _observe: function() { var element = this.element, parent = this.parent, eventMapping = { focusin: "focus", focusout: "blur" }, /** * Calling focus() or blur() on an element doesn't synchronously trigger the attached focus/blur events * This is the case for focusin and focusout, so let's use them whenever possible, kkthxbai */ events = wysihtml5.browser.supportsEvent("focusin") ? ["focusin", "focusout", "change"] : ["focus", "blur", "change"]; parent.on("beforeload", function() { wysihtml5.dom.observe(element, events, function(event) { var eventName = eventMapping[event.type] || event.type; parent.fire(eventName).fire(eventName + ":textarea"); }); wysihtml5.dom.observe(element, ["paste", "drop"], function() { setTimeout(function() { parent.fire("paste").fire("paste:textarea"); }, 0); }); }); } }); ;/** * WYSIHTML5 Editor * * @param {Element} editableElement Reference to the textarea which should be turned into a rich text interface * @param {Object} [config] See defaultConfig object below for explanation of each individual config option * * @events * load * beforeload (for internal use only) * focus * focus:composer * focus:textarea * blur * blur:composer * blur:textarea * change * change:composer * change:textarea * paste * paste:composer * paste:textarea * newword:composer * destroy:composer * undo:composer * redo:composer * beforecommand:composer * aftercommand:composer * enable:composer * disable:composer * change_view */ (function(wysihtml5) { var undef; var defaultConfig = { // Give the editor a name, the name will also be set as class name on the iframe and on the iframe's body name: undef, // Whether the editor should look like the textarea (by adopting styles) style: true, // Id of the toolbar element, pass falsey value if you don't want any toolbar logic toolbar: undef, // Whether toolbar is displayed after init by script automatically. // Can be set to false if toolobar is set to display only on editable area focus showToolbarAfterInit: true, // With default toolbar it shows dialogs in toolbar when their related text format state becomes active (click on link in text opens link dialogue) showToolbarDialogsOnSelection: true, // Whether urls, entered by the user should automatically become clickable-links autoLink: true, // Includes table editing events and cell selection tracking handleTables: true, // Tab key inserts tab into text as default behaviour. It can be disabled to regain keyboard navigation handleTabKey: true, // Object which includes parser rules to apply when html gets cleaned // See parser_rules/*.js for examples parserRules: { tags: { br: {}, span: {}, div: {}, p: {} }, classes: {} }, // Object which includes parser when the user inserts content via copy & paste. If null parserRules will be used instead pasteParserRulesets: null, // Parser method to use when the user inserts content parser: wysihtml5.dom.parse, // By default wysihtml5 will insert a <br> for line breaks, set this to false to use <p> useLineBreaks: true, // Array (or single string) of stylesheet urls to be loaded in the editor's iframe stylesheets: [], // Placeholder text to use, defaults to the placeholder attribute on the textarea element placeholderText: undef, // Whether the rich text editor should be rendered on touch devices (wysihtml5 >= 0.3.0 comes with basic support for iOS 5) supportTouchDevices: true, // Whether senseless <span> elements (empty or without attributes) should be removed/replaced with their content cleanUp: true, // Whether to use div instead of secure iframe contentEditableMode: false, classNames: { // Class name which should be set on the contentEditable element in the created sandbox iframe, can be styled via the 'stylesheets' option composer: "wysihtml5-editor", // Class name to add to the body when the wysihtml5 editor is supported body: "wysihtml5-supported", // classname added to editable area element (iframe/div) on creation sandbox: "wysihtml5-sandbox", // class on editable area with placeholder placeholder: "wysihtml5-placeholder", // Classname of container that editor should not touch and pass through uneditableContainer: "wysihtml5-uneditable-container" }, // Browsers that support copied source handling will get a marking of the origin of the copied source (for determinig code cleanup rules on paste) // Also copied source is based directly on selection - // (very useful for webkit based browsers where copy will otherwise contain a lot of code and styles based on whatever and not actually in selection). // If falsy value is passed source override is also disabled copyedFromMarking: '<meta name="copied-from" content="wysihtml5">' }; wysihtml5.Editor = wysihtml5.lang.Dispatcher.extend( /** @scope wysihtml5.Editor.prototype */ { constructor: function(editableElement, config) { this.editableElement = typeof(editableElement) === "string" ? document.getElementById(editableElement) : editableElement; this.config = wysihtml5.lang.object({}).merge(defaultConfig).merge(config).get(); this._isCompatible = wysihtml5.browser.supported(); // merge classNames if (config && config.classNames) { wysihtml5.lang.object(this.config.classNames).merge(config.classNames); } if (this.editableElement.nodeName.toLowerCase() != "textarea") { this.config.contentEditableMode = true; this.config.noTextarea = true; } if (!this.config.noTextarea) { this.textarea = new wysihtml5.views.Textarea(this, this.editableElement, this.config); this.currentView = this.textarea; } // Sort out unsupported/unwanted browsers here if (!this._isCompatible || (!this.config.supportTouchDevices && wysihtml5.browser.isTouchDevice())) { var that = this; setTimeout(function() { that.fire("beforeload").fire("load"); }, 0); return; } // Add class name to body, to indicate that the editor is supported wysihtml5.dom.addClass(document.body, this.config.classNames.body); this.composer = new wysihtml5.views.Composer(this, this.editableElement, this.config); this.currentView = this.composer; if (typeof(this.config.parser) === "function") { this._initParser(); } this.on("beforeload", this.handleBeforeLoad); }, handleBeforeLoad: function() { if (!this.config.noTextarea) { this.synchronizer = new wysihtml5.views.Synchronizer(this, this.textarea, this.composer); } else { this.sourceView = new wysihtml5.views.SourceView(this, this.composer); } if (this.config.toolbar) { this.toolbar = new wysihtml5.toolbar.Toolbar(this, this.config.toolbar, this.config.showToolbarAfterInit); } }, isCompatible: function() { return this._isCompatible; }, clear: function() { this.currentView.clear(); return this; }, getValue: function(parse, clearInternals) { return this.currentView.getValue(parse, clearInternals); }, setValue: function(html, parse) { this.fire("unset_placeholder"); if (!html) { return this.clear(); } this.currentView.setValue(html, parse); return this; }, cleanUp: function() { this.currentView.cleanUp(); }, focus: function(setToEnd) { this.currentView.focus(setToEnd); return this; }, /** * Deactivate editor (make it readonly) */ disable: function() { this.currentView.disable(); return this; }, /** * Activate editor */ enable: function() { this.currentView.enable(); return this; }, isEmpty: function() { return this.currentView.isEmpty(); }, hasPlaceholderSet: function() { return this.currentView.hasPlaceholderSet(); }, parse: function(htmlOrElement, clearInternals) { var parseContext = (this.config.contentEditableMode) ? document : ((this.composer) ? this.composer.sandbox.getDocument() : null); var returnValue = this.config.parser(htmlOrElement, { "rules": this.config.parserRules, "cleanUp": this.config.cleanUp, "context": parseContext, "uneditableClass": this.config.classNames.uneditableContainer, "clearInternals" : clearInternals }); if (typeof(htmlOrElement) === "object") { wysihtml5.quirks.redraw(htmlOrElement); } return returnValue; }, /** * Prepare html parser logic * - Observes for paste and drop */ _initParser: function() { var oldHtml; if (wysihtml5.browser.supportsModernPaste()) { this.on("paste:composer", function(event) { event.preventDefault(); oldHtml = wysihtml5.dom.getPastedHtml(event); if (oldHtml) { this._cleanAndPaste(oldHtml); } }.bind(this)); } else { this.on("beforepaste:composer", function(event) { event.preventDefault(); var scrollPos = this.composer.getScrollPos(); wysihtml5.dom.getPastedHtmlWithDiv(this.composer, function(pastedHTML) { if (pastedHTML) { this._cleanAndPaste(pastedHTML); } this.composer.setScrollPos(scrollPos); }.bind(this)); }.bind(this)); } }, _cleanAndPaste: function (oldHtml) { var cleanHtml = wysihtml5.quirks.cleanPastedHTML(oldHtml, { "referenceNode": this.composer.element, "rules": this.config.pasteParserRulesets || [{"set": this.config.parserRules}], "uneditableClass": this.config.classNames.uneditableContainer }); this.composer.selection.deleteContents(); this.composer.selection.insertHTML(cleanHtml); } }); })(wysihtml5);
define("axios", [], 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__) { module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var defaults = __webpack_require__(2); var utils = __webpack_require__(3); var deprecatedMethod = __webpack_require__(4); var dispatchRequest = __webpack_require__(5); var InterceptorManager = __webpack_require__(6); // Polyfill ES6 Promise if needed (function () { // webpack is being used to set es6-promise to the native Promise // for the standalone build. It's necessary to make sure polyfill exists. var P = __webpack_require__(9); if (P && typeof P.polyfill === 'function') { P.polyfill(); } })(); var axios = module.exports = function axios(config) { config = utils.merge({ method: 'get', headers: {}, transformRequest: defaults.transformRequest, transformResponse: defaults.transformResponse }, config); // Don't allow overriding defaults.withCredentials config.withCredentials = config.withCredentials || defaults.withCredentials; // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); axios.interceptors.request.forEach(function (interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); axios.interceptors.response.forEach(function (interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } // Provide alias for success promise.success = function success(fn) { deprecatedMethod('success', 'then', 'https://github.com/mzabriskie/axios/blob/master/README.md#response-api'); promise.then(function(response) { fn(response.data, response.status, response.headers, response.config); }); return promise; }; // Provide alias for error promise.error = function error(fn) { deprecatedMethod('error', 'catch', 'https://github.com/mzabriskie/axios/blob/master/README.md#response-api'); promise.then(null, function(response) { fn(response.data, response.status, response.headers, response.config); }); return promise; }; return promise; }; // Expose defaults axios.defaults = defaults; // Expose all/spread axios.all = function (promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(7); // Expose interceptors axios.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; // Provide aliases for supported request methods (function () { function createShortMethods() { utils.forEach(arguments, function (method) { axios[method] = function (url, config) { return axios(utils.merge(config || {}, { method: method, url: url })); }; }); } function createShortMethodsWithData() { utils.forEach(arguments, function (method) { axios[method] = function (url, data, config) { return axios(utils.merge(config || {}, { method: method, url: url, data: data })); }; }); } createShortMethods('delete', 'get', 'head'); createShortMethodsWithData('post', 'put', 'patch'); })(); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); var PROTECTION_PREFIX = /^\)\]\}',?\n/; var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; module.exports = { transformRequest: [function (data, headers) { if (utils.isArrayBuffer(data)) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isObject(data) && !utils.isFile(data) && !utils.isBlob(data)) { // Set application/json if no Content-Type has been specified if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = 'application/json;charset=utf-8'; } return JSON.stringify(data); } return data; }], transformResponse: [function (data) { if (typeof data === 'string') { data = data.replace(PROTECTION_PREFIX, ''); try { data = JSON.parse(data); } catch (e) {} } return data; }], headers: { common: { 'Accept': 'application/json, text/plain, */*' }, patch: utils.merge(DEFAULT_CONTENT_TYPE), post: utils.merge(DEFAULT_CONTENT_TYPE), put: utils.merge(DEFAULT_CONTENT_TYPE) }, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN' }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /*global toString:true*/ // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return toString.call(val) === '[object FormData]'; } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { return ArrayBuffer.isView(val); } else { return (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array or arguments callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Check if obj is array-like var isArrayLike = isArray(obj) || (typeof obj === 'object' && !isNaN(obj.length)); // Force an array if not already something iterable if (typeof obj !== 'object' && !isArrayLike) { obj = [obj]; } // Iterate over array values if (isArrayLike) { for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } // Iterate over object keys else { for (var key in obj) { if (obj.hasOwnProperty(key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/*obj1, obj2, obj3, ...*/) { var result = {}; forEach(arguments, function (obj) { forEach(obj, function (val, key) { result[key] = val; }); }); return result; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, forEach: forEach, merge: merge, trim: trim }; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Supply a warning to the developer that a method they are using * has been deprecated. * * @param {string} method The name of the deprecated method * @param {string} [instead] The alternate method to use if applicable * @param {string} [docs] The documentation URL to get further details */ module.exports = function deprecatedMethod(method, instead, docs) { try { console.warn( 'DEPRECATED method `' + method + '`.' + (instead ? ' Use `' + instead + '` instead.' : '') + ' This method will be removed in a future release.'); if (docs) { console.warn('For more information about usage see ' + docs); } } catch (e) {} }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Dispatch a request to the server using whichever adapter * is supported by the current environment. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { return new Promise(function (resolve, reject) { try { // For browsers use XHR adapter if (typeof window !== 'undefined') { __webpack_require__(8)(resolve, reject, config); } // For node use HTTP adapter else if (typeof process !== 'undefined') { __webpack_require__(8)(resolve, reject, config); } } catch (e) { reject(e); } }); }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function (fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function (id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `remove`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function (fn) { utils.forEach(this.handlers, function (h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function (arr) { callback.apply(null, arr); }; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /*global ActiveXObject:true*/ var defaults = __webpack_require__(2); var utils = __webpack_require__(3); var buildUrl = __webpack_require__(11); var cookies = __webpack_require__(12); var parseHeaders = __webpack_require__(13); var transformData = __webpack_require__(14); var urlIsSameOrigin = __webpack_require__(15); module.exports = function xhrAdapter(resolve, reject, config) { // Transform request data var data = transformData( config.data, config.headers, config.transformRequest ); // Merge headers var requestHeaders = utils.merge( defaults.headers.common, defaults.headers[config.method] || {}, config.headers || {} ); if (utils.isFormData(data)) { delete requestHeaders['Content-Type']; // Let the browser set it } // Create the request var request = new (XMLHttpRequest || ActiveXObject)('Microsoft.XMLHTTP'); request.open(config.method.toUpperCase(), buildUrl(config.url, config.params), true); // Listen for ready state request.onreadystatechange = function () { if (request && request.readyState === 4) { // Prepare the response var responseHeaders = parseHeaders(request.getAllResponseHeaders()); var responseData = ['text', ''].indexOf(config.responseType || '') !== -1 ? request.responseText : request.response; var response = { data: transformData( responseData, responseHeaders, config.transformResponse ), status: request.status, statusText: request.statusText, headers: responseHeaders, config: config }; // Resolve or reject the Promise based on the status (request.status >= 200 && request.status < 300 ? resolve : reject)(response); // Clean up request request = null; } }; // Add xsrf header var xsrfValue = urlIsSameOrigin(config.url) ? cookies.read(config.xsrfCookieName || defaults.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName || defaults.xsrfHeaderName] = xsrfValue; } // Add headers to the request utils.forEach(requestHeaders, function (val, key) { // Remove Content-Type if data is undefined if (!data && key.toLowerCase() === 'content-type') { delete requestHeaders[key]; } // Otherwise add header to the request else { request.setRequestHeader(key, val); } }); // Add withCredentials to request if needed if (config.withCredentials) { request.withCredentials = true; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { if (request.responseType !== 'json') { throw e; } } } if (utils.isArrayBuffer(data)) { data = new DataView(data); } // Send the request request.send(data); }; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/* WEBPACK VAR INJECTION */(function(process, global, module) {/*! * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE * @version 2.0.1 */ (function() { "use strict"; function $$utils$$objectOrFunction(x) { return typeof x === 'function' || (typeof x === 'object' && x !== null); } function $$utils$$isFunction(x) { return typeof x === 'function'; } function $$utils$$isMaybeThenable(x) { return typeof x === 'object' && x !== null; } var $$utils$$_isArray; if (!Array.isArray) { $$utils$$_isArray = function (x) { return Object.prototype.toString.call(x) === '[object Array]'; }; } else { $$utils$$_isArray = Array.isArray; } var $$utils$$isArray = $$utils$$_isArray; var $$utils$$now = Date.now || function() { return new Date().getTime(); }; function $$utils$$F() { } var $$utils$$o_create = (Object.create || function (o) { if (arguments.length > 1) { throw new Error('Second argument not supported'); } if (typeof o !== 'object') { throw new TypeError('Argument must be an object'); } $$utils$$F.prototype = o; return new $$utils$$F(); }); var $$asap$$len = 0; var $$asap$$default = function asap(callback, arg) { $$asap$$queue[$$asap$$len] = callback; $$asap$$queue[$$asap$$len + 1] = arg; $$asap$$len += 2; if ($$asap$$len === 2) { // If len is 1, that means that we need to schedule an async flush. // If additional callbacks are queued before the queue is flushed, they // will be processed by this flush that we are scheduling. $$asap$$scheduleFlush(); } }; var $$asap$$browserGlobal = (typeof window !== 'undefined') ? window : {}; var $$asap$$BrowserMutationObserver = $$asap$$browserGlobal.MutationObserver || $$asap$$browserGlobal.WebKitMutationObserver; // test for web worker but not in IE10 var $$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; // node function $$asap$$useNextTick() { return function() { process.nextTick($$asap$$flush); }; } function $$asap$$useMutationObserver() { var iterations = 0; var observer = new $$asap$$BrowserMutationObserver($$asap$$flush); var node = document.createTextNode(''); observer.observe(node, { characterData: true }); return function() { node.data = (iterations = ++iterations % 2); }; } // web worker function $$asap$$useMessageChannel() { var channel = new MessageChannel(); channel.port1.onmessage = $$asap$$flush; return function () { channel.port2.postMessage(0); }; } function $$asap$$useSetTimeout() { return function() { setTimeout($$asap$$flush, 1); }; } var $$asap$$queue = new Array(1000); function $$asap$$flush() { for (var i = 0; i < $$asap$$len; i+=2) { var callback = $$asap$$queue[i]; var arg = $$asap$$queue[i+1]; callback(arg); $$asap$$queue[i] = undefined; $$asap$$queue[i+1] = undefined; } $$asap$$len = 0; } var $$asap$$scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { $$asap$$scheduleFlush = $$asap$$useNextTick(); } else if ($$asap$$BrowserMutationObserver) { $$asap$$scheduleFlush = $$asap$$useMutationObserver(); } else if ($$asap$$isWorker) { $$asap$$scheduleFlush = $$asap$$useMessageChannel(); } else { $$asap$$scheduleFlush = $$asap$$useSetTimeout(); } function $$$internal$$noop() {} var $$$internal$$PENDING = void 0; var $$$internal$$FULFILLED = 1; var $$$internal$$REJECTED = 2; var $$$internal$$GET_THEN_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$selfFullfillment() { return new TypeError("You cannot resolve a promise with itself"); } function $$$internal$$cannotReturnOwn() { return new TypeError('A promises callback cannot return that same promise.') } function $$$internal$$getThen(promise) { try { return promise.then; } catch(error) { $$$internal$$GET_THEN_ERROR.error = error; return $$$internal$$GET_THEN_ERROR; } } function $$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) { try { then.call(value, fulfillmentHandler, rejectionHandler); } catch(e) { return e; } } function $$$internal$$handleForeignThenable(promise, thenable, then) { $$asap$$default(function(promise) { var sealed = false; var error = $$$internal$$tryThen(then, thenable, function(value) { if (sealed) { return; } sealed = true; if (thenable !== value) { $$$internal$$resolve(promise, value); } else { $$$internal$$fulfill(promise, value); } }, function(reason) { if (sealed) { return; } sealed = true; $$$internal$$reject(promise, reason); }, 'Settle: ' + (promise._label || ' unknown promise')); if (!sealed && error) { sealed = true; $$$internal$$reject(promise, error); } }, promise); } function $$$internal$$handleOwnThenable(promise, thenable) { if (thenable._state === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, thenable._result); } else if (promise._state === $$$internal$$REJECTED) { $$$internal$$reject(promise, thenable._result); } else { $$$internal$$subscribe(thenable, undefined, function(value) { $$$internal$$resolve(promise, value); }, function(reason) { $$$internal$$reject(promise, reason); }); } } function $$$internal$$handleMaybeThenable(promise, maybeThenable) { if (maybeThenable.constructor === promise.constructor) { $$$internal$$handleOwnThenable(promise, maybeThenable); } else { var then = $$$internal$$getThen(maybeThenable); if (then === $$$internal$$GET_THEN_ERROR) { $$$internal$$reject(promise, $$$internal$$GET_THEN_ERROR.error); } else if (then === undefined) { $$$internal$$fulfill(promise, maybeThenable); } else if ($$utils$$isFunction(then)) { $$$internal$$handleForeignThenable(promise, maybeThenable, then); } else { $$$internal$$fulfill(promise, maybeThenable); } } } function $$$internal$$resolve(promise, value) { if (promise === value) { $$$internal$$reject(promise, $$$internal$$selfFullfillment()); } else if ($$utils$$objectOrFunction(value)) { $$$internal$$handleMaybeThenable(promise, value); } else { $$$internal$$fulfill(promise, value); } } function $$$internal$$publishRejection(promise) { if (promise._onerror) { promise._onerror(promise._result); } $$$internal$$publish(promise); } function $$$internal$$fulfill(promise, value) { if (promise._state !== $$$internal$$PENDING) { return; } promise._result = value; promise._state = $$$internal$$FULFILLED; if (promise._subscribers.length === 0) { } else { $$asap$$default($$$internal$$publish, promise); } } function $$$internal$$reject(promise, reason) { if (promise._state !== $$$internal$$PENDING) { return; } promise._state = $$$internal$$REJECTED; promise._result = reason; $$asap$$default($$$internal$$publishRejection, promise); } function $$$internal$$subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; parent._onerror = null; subscribers[length] = child; subscribers[length + $$$internal$$FULFILLED] = onFulfillment; subscribers[length + $$$internal$$REJECTED] = onRejection; if (length === 0 && parent._state) { $$asap$$default($$$internal$$publish, parent); } } function $$$internal$$publish(promise) { var subscribers = promise._subscribers; var settled = promise._state; if (subscribers.length === 0) { return; } var child, callback, detail = promise._result; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; if (child) { $$$internal$$invokeCallback(settled, child, callback, detail); } else { callback(detail); } } promise._subscribers.length = 0; } function $$$internal$$ErrorObject() { this.error = null; } var $$$internal$$TRY_CATCH_ERROR = new $$$internal$$ErrorObject(); function $$$internal$$tryCatch(callback, detail) { try { return callback(detail); } catch(e) { $$$internal$$TRY_CATCH_ERROR.error = e; return $$$internal$$TRY_CATCH_ERROR; } } function $$$internal$$invokeCallback(settled, promise, callback, detail) { var hasCallback = $$utils$$isFunction(callback), value, error, succeeded, failed; if (hasCallback) { value = $$$internal$$tryCatch(callback, detail); if (value === $$$internal$$TRY_CATCH_ERROR) { failed = true; error = value.error; value = null; } else { succeeded = true; } if (promise === value) { $$$internal$$reject(promise, $$$internal$$cannotReturnOwn()); return; } } else { value = detail; succeeded = true; } if (promise._state !== $$$internal$$PENDING) { // noop } else if (hasCallback && succeeded) { $$$internal$$resolve(promise, value); } else if (failed) { $$$internal$$reject(promise, error); } else if (settled === $$$internal$$FULFILLED) { $$$internal$$fulfill(promise, value); } else if (settled === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } } function $$$internal$$initializePromise(promise, resolver) { try { resolver(function resolvePromise(value){ $$$internal$$resolve(promise, value); }, function rejectPromise(reason) { $$$internal$$reject(promise, reason); }); } catch(e) { $$$internal$$reject(promise, e); } } function $$$enumerator$$makeSettledResult(state, position, value) { if (state === $$$internal$$FULFILLED) { return { state: 'fulfilled', value: value }; } else { return { state: 'rejected', reason: value }; } } function $$$enumerator$$Enumerator(Constructor, input, abortOnReject, label) { this._instanceConstructor = Constructor; this.promise = new Constructor($$$internal$$noop, label); this._abortOnReject = abortOnReject; if (this._validateInput(input)) { this._input = input; this.length = input.length; this._remaining = input.length; this._init(); if (this.length === 0) { $$$internal$$fulfill(this.promise, this._result); } else { this.length = this.length || 0; this._enumerate(); if (this._remaining === 0) { $$$internal$$fulfill(this.promise, this._result); } } } else { $$$internal$$reject(this.promise, this._validationError()); } } $$$enumerator$$Enumerator.prototype._validateInput = function(input) { return $$utils$$isArray(input); }; $$$enumerator$$Enumerator.prototype._validationError = function() { return new Error('Array Methods must be provided an Array'); }; $$$enumerator$$Enumerator.prototype._init = function() { this._result = new Array(this.length); }; var $$$enumerator$$default = $$$enumerator$$Enumerator; $$$enumerator$$Enumerator.prototype._enumerate = function() { var length = this.length; var promise = this.promise; var input = this._input; for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { this._eachEntry(input[i], i); } }; $$$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) { var c = this._instanceConstructor; if ($$utils$$isMaybeThenable(entry)) { if (entry.constructor === c && entry._state !== $$$internal$$PENDING) { entry._onerror = null; this._settledAt(entry._state, i, entry._result); } else { this._willSettleAt(c.resolve(entry), i); } } else { this._remaining--; this._result[i] = this._makeResult($$$internal$$FULFILLED, i, entry); } }; $$$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) { var promise = this.promise; if (promise._state === $$$internal$$PENDING) { this._remaining--; if (this._abortOnReject && state === $$$internal$$REJECTED) { $$$internal$$reject(promise, value); } else { this._result[i] = this._makeResult(state, i, value); } } if (this._remaining === 0) { $$$internal$$fulfill(promise, this._result); } }; $$$enumerator$$Enumerator.prototype._makeResult = function(state, i, value) { return value; }; $$$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) { var enumerator = this; $$$internal$$subscribe(promise, undefined, function(value) { enumerator._settledAt($$$internal$$FULFILLED, i, value); }, function(reason) { enumerator._settledAt($$$internal$$REJECTED, i, reason); }); }; var $$promise$all$$default = function all(entries, label) { return new $$$enumerator$$default(this, entries, true /* abort on reject */, label).promise; }; var $$promise$race$$default = function race(entries, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); if (!$$utils$$isArray(entries)) { $$$internal$$reject(promise, new TypeError('You must pass an array to race.')); return promise; } var length = entries.length; function onFulfillment(value) { $$$internal$$resolve(promise, value); } function onRejection(reason) { $$$internal$$reject(promise, reason); } for (var i = 0; promise._state === $$$internal$$PENDING && i < length; i++) { $$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); } return promise; }; var $$promise$resolve$$default = function resolve(object, label) { /*jshint validthis:true */ var Constructor = this; if (object && typeof object === 'object' && object.constructor === Constructor) { return object; } var promise = new Constructor($$$internal$$noop, label); $$$internal$$resolve(promise, object); return promise; }; var $$promise$reject$$default = function reject(reason, label) { /*jshint validthis:true */ var Constructor = this; var promise = new Constructor($$$internal$$noop, label); $$$internal$$reject(promise, reason); return promise; }; var $$es6$promise$promise$$counter = 0; function $$es6$promise$promise$$needsResolver() { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } function $$es6$promise$promise$$needsNew() { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } var $$es6$promise$promise$$default = $$es6$promise$promise$$Promise; /** Promise objects represent the eventual result of an asynchronous operation. The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled. Terminology ----------- - `promise` is an object or function with a `then` method whose behavior conforms to this specification. - `thenable` is an object or function that defines a `then` method. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). - `exception` is a value that is thrown using the throw statement. - `reason` is a value that indicates why a promise was rejected. - `settled` the final resting state of a promise, fulfilled or rejected. A promise can be in one of three states: pending, fulfilled, or rejected. Promises that are fulfilled have a fulfillment value and are in the fulfilled state. Promises that are rejected have a rejection reason and are in the rejected state. A fulfillment value is never a thenable. Promises can also be said to *resolve* a value. If this value is also a promise, then the original promise's settled state will match the value's settled state. So a promise that *resolves* a promise that rejects will itself reject, and a promise that *resolves* a promise that fulfills will itself fulfill. Basic Usage: ------------ ```js var promise = new Promise(function(resolve, reject) { // on success resolve(value); // on failure reject(reason); }); promise.then(function(value) { // on fulfillment }, function(reason) { // on rejection }); ``` Advanced Usage: --------------- Promises shine when abstracting away asynchronous interactions such as `XMLHttpRequest`s. ```js function getJSON(url) { return new Promise(function(resolve, reject){ var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onreadystatechange = handler; xhr.responseType = 'json'; xhr.setRequestHeader('Accept', 'application/json'); xhr.send(); function handler() { if (this.readyState === this.DONE) { if (this.status === 200) { resolve(this.response); } else { reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); } } }; }); } getJSON('/posts.json').then(function(json) { // on fulfillment }, function(reason) { // on rejection }); ``` Unlike callbacks, promises are great composable primitives. ```js Promise.all([ getJSON('/posts'), getJSON('/comments') ]).then(function(values){ values[0] // => postsJSON values[1] // => commentsJSON return values; }); ``` @class Promise @param {function} resolver Useful for tooling. @constructor */ function $$es6$promise$promise$$Promise(resolver) { this._id = $$es6$promise$promise$$counter++; this._state = undefined; this._result = undefined; this._subscribers = []; if ($$$internal$$noop !== resolver) { if (!$$utils$$isFunction(resolver)) { $$es6$promise$promise$$needsResolver(); } if (!(this instanceof $$es6$promise$promise$$Promise)) { $$es6$promise$promise$$needsNew(); } $$$internal$$initializePromise(this, resolver); } } $$es6$promise$promise$$Promise.all = $$promise$all$$default; $$es6$promise$promise$$Promise.race = $$promise$race$$default; $$es6$promise$promise$$Promise.resolve = $$promise$resolve$$default; $$es6$promise$promise$$Promise.reject = $$promise$reject$$default; $$es6$promise$promise$$Promise.prototype = { constructor: $$es6$promise$promise$$Promise, /** The primary way of interacting with a promise is through its `then` method, which registers callbacks to receive either a promise's eventual value or the reason why the promise cannot be fulfilled. ```js findUser().then(function(user){ // user is available }, function(reason){ // user is unavailable, and you are given the reason why }); ``` Chaining -------- The return value of `then` is itself a promise. This second, 'downstream' promise is resolved with the return value of the first promise's fulfillment or rejection handler, or rejected if the handler throws an exception. ```js findUser().then(function (user) { return user.name; }, function (reason) { return 'default name'; }).then(function (userName) { // If `findUser` fulfilled, `userName` will be the user's name, otherwise it // will be `'default name'` }); findUser().then(function (user) { throw new Error('Found user, but still unhappy'); }, function (reason) { throw new Error('`findUser` rejected and we're unhappy'); }).then(function (value) { // never reached }, function (reason) { // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. }); ``` If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. ```js findUser().then(function (user) { throw new PedagogicalException('Upstream error'); }).then(function (value) { // never reached }).then(function (value) { // never reached }, function (reason) { // The `PedgagocialException` is propagated all the way down to here }); ``` Assimilation ------------ Sometimes the value you want to propagate to a downstream promise can only be retrieved asynchronously. This can be achieved by returning a promise in the fulfillment or rejection handler. The downstream promise will then be pending until the returned promise is settled. This is called *assimilation*. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // The user's comments are now available }); ``` If the assimliated promise rejects, then the downstream promise will also reject. ```js findUser().then(function (user) { return findCommentsByAuthor(user); }).then(function (comments) { // If `findCommentsByAuthor` fulfills, we'll have the value here }, function (reason) { // If `findCommentsByAuthor` rejects, we'll have the reason here }); ``` Simple Example -------------- Synchronous Example ```javascript var result; try { result = findResult(); // success } catch(reason) { // failure } ``` Errback Example ```js findResult(function(result, err){ if (err) { // failure } else { // success } }); ``` Promise Example; ```javascript findResult().then(function(result){ // success }, function(reason){ // failure }); ``` Advanced Example -------------- Synchronous Example ```javascript var author, books; try { author = findAuthor(); books = findBooksByAuthor(author); // success } catch(reason) { // failure } ``` Errback Example ```js function foundBooks(books) { } function failure(reason) { } findAuthor(function(author, err){ if (err) { failure(err); // failure } else { try { findBoooksByAuthor(author, function(books, err) { if (err) { failure(err); } else { try { foundBooks(books); } catch(reason) { failure(reason); } } }); } catch(error) { failure(err); } // success } }); ``` Promise Example; ```javascript findAuthor(). then(findBooksByAuthor). then(function(books){ // found books }).catch(function(reason){ // something went wrong }); ``` @method then @param {Function} onFulfilled @param {Function} onRejected Useful for tooling. @return {Promise} */ then: function(onFulfillment, onRejection) { var parent = this; var state = parent._state; if (state === $$$internal$$FULFILLED && !onFulfillment || state === $$$internal$$REJECTED && !onRejection) { return this; } var child = new this.constructor($$$internal$$noop); var result = parent._result; if (state) { var callback = arguments[state - 1]; $$asap$$default(function(){ $$$internal$$invokeCallback(state, child, callback, result); }); } else { $$$internal$$subscribe(parent, child, onFulfillment, onRejection); } return child; }, /** `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same as the catch block of a try/catch statement. ```js function findAuthor(){ throw new Error('couldn't find that author'); } // synchronous try { findAuthor(); } catch(reason) { // something went wrong } // async with promises findAuthor().catch(function(reason){ // something went wrong }); ``` @method catch @param {Function} onRejection Useful for tooling. @return {Promise} */ 'catch': function(onRejection) { return this.then(null, onRejection); } }; var $$es6$promise$polyfill$$default = function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return $$utils$$isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = $$es6$promise$promise$$default; } }; var es6$promise$umd$$ES6Promise = { 'Promise': $$es6$promise$promise$$default, 'polyfill': $$es6$promise$polyfill$$default }; /* global define:true module:true window: true */ if ("function" === 'function' && __webpack_require__(16)['amd']) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return es6$promise$umd$$ES6Promise; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = es6$promise$umd$$ES6Promise; } else if (typeof this !== 'undefined') { this['ES6Promise'] = es6$promise$umd$$ES6Promise; } }).call(this); /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10), (function() { return this; }()), __webpack_require__(17)(module))) /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // 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'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); function encode(val) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildUrl(url, params) { if (!params) { return url; } var parts = []; utils.forEach(params, function (val, key) { if (val === null || typeof val === 'undefined') { return; } if (!utils.isArray(val)) { val = [val]; } utils.forEach(val, function (v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); if (parts.length > 0) { url += (url.indexOf('?') === -1 ? '?' : '&') + parts.join('&'); } return url; }; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); module.exports = { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } }); return parsed; }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { utils.forEach(fns, function (fn) { data = fn(data, headers); }); return data; }; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var utils = __webpack_require__(3); var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originUrl; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function urlResolve(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originUrl = urlResolve(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestUrl The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ module.exports = function urlIsSameOrigin(requestUrl) { var parsed = (utils.isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl; return (parsed.protocol === originUrl.protocol && parsed.host === originUrl.host); }; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { module.exports = function() { throw new Error("define cannot be used indirect"); }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ } /******/ ])});; //# sourceMappingURL=axios.amd.map
topojson = (function() { function merge(topology, arcs) { var fragmentByStart = {}, fragmentByEnd = {}; 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 if (g = fragmentByEnd[end]) { delete fragmentByStart[g.start]; delete fragmentByEnd[g.end]; var fg = f.concat(g.map(function(i) { return ~i; }).reverse()); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = 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 if (g = fragmentByStart[start]) { delete fragmentByStart[g.start]; delete fragmentByEnd[g.end]; var gf = g.map(function(i) { return ~i; }).reverse().concat(f); fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else if (f = fragmentByStart[start]) { delete fragmentByStart[f.start]; f.unshift(~i); f.start = end; if (g = fragmentByEnd[end]) { delete fragmentByEnd[g.end]; var gf = g === f ? f : g.concat(f); fragmentByStart[gf.start = g.start] = fragmentByEnd[gf.end = f.end] = gf; } else if (g = fragmentByStart[end]) { delete fragmentByStart[g.start]; delete fragmentByEnd[g.end]; var gf = g.map(function(i) { return ~i; }).reverse().concat(f); fragmentByStart[gf.start = g.end] = fragmentByEnd[gf.end = f.end] = gf; } else { fragmentByStart[f.start] = fragmentByEnd[f.end] = f; } } else if (f = fragmentByEnd[end]) { delete fragmentByEnd[f.end]; f.push(~i); f.end = start; if (g = fragmentByEnd[start]) { delete fragmentByStart[g.start]; var fg = g === f ? f : f.concat(g); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.end] = fg; } else if (g = fragmentByStart[start]) { delete fragmentByStart[g.start]; delete fragmentByEnd[g.end]; var fg = f.concat(g.map(function(i) { return ~i; }).reverse()); fragmentByStart[fg.start = f.start] = fragmentByEnd[fg.end = g.start] = fg; } 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], p0 = arc[0], p1 = [0, 0]; arc.forEach(function(dp) { p1[0] += dp[0], p1[1] += dp[1]; }); return [p0, p1]; } var fragments = []; for (var k in fragmentByEnd) fragments.push(fragmentByEnd[k]); return fragments; } function mesh(topology, o, filter) { var arcs = []; if (arguments.length > 1) { var geomsByArc = [], geom; function arc(i) { if (i < 0) i = ~i; (geomsByArc[i] || (geomsByArc[i] = [])).push(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); } } var geometryType = { LineString: line, MultiLineString: polygon, Polygon: polygon, MultiPolygon: function(arcs) { arcs.forEach(polygon); } }; geometry(o); geomsByArc.forEach(arguments.length < 3 ? function(geoms, i) { arcs.push(i); } : function(geoms, i) { if (filter(geoms[0], geoms[geoms.length - 1])) arcs.push(i); }); } else { for (var i = 0, n = topology.arcs.length; i < n; ++i) arcs.push(i); } return object(topology, {type: "MultiLineString", arcs: merge(topology, arcs)}); } function featureOrCollection(topology, o) { return o.type === "GeometryCollection" ? { type: "FeatureCollection", features: o.geometries.map(function(o) { return feature(topology, o); }) } : feature(topology, o); } function feature(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 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 bisect(a, x) { var lo = 0, hi = a.length; while (lo < hi) { var mid = lo + hi >>> 1; if (a[mid] < x) lo = mid + 1; else hi = mid; } return lo; } function neighbors(objects) { var indexesByArc = {}, // arc index -> array of object indexes neighbors = objects.map(function() { return []; }); function line(arcs, i) { arcs.forEach(function(a) { if (a < 0) a = ~a; var o = indexesByArc[a]; if (o) o.push(i); else indexesByArc[a] = [i]; }); } function polygon(arcs, i) { arcs.forEach(function(arc) { line(arc, i); }); } function geometry(o, i) { if (o.type === "GeometryCollection") o.geometries.forEach(function(o) { geometry(o, i); }); else if (o.type in geometryType) geometryType[o.type](o.arcs, i); } var geometryType = { LineString: line, MultiLineString: polygon, Polygon: polygon, MultiPolygon: function(arcs, i) { arcs.forEach(function(arc) { polygon(arc, i); }); } }; objects.forEach(geometry); for (var i in indexesByArc) { for (var indexes = indexesByArc[i], m = indexes.length, j = 0; j < m; ++j) { for (var k = j + 1; k < m; ++k) { var ij = indexes[j], ik = indexes[k], n; if ((n = neighbors[ij])[i = bisect(n, ik)] !== ik) n.splice(i, 0, ik); if ((n = neighbors[ik])[i = bisect(n, ij)] !== ij) n.splice(i, 0, ij); } } } return neighbors; } function presimplify(topology, triangleArea) { var absolute = transformAbsolute(topology.transform), relative = transformRelative(topology.transform), heap = minHeap(compareArea), maxArea = 0, triangle; if (!triangleArea) triangleArea = cartesianArea; topology.arcs.forEach(function(arc) { var triangles = []; arc.forEach(absolute); for (var i = 1, n = arc.length - 1; i < n; ++i) { triangle = arc.slice(i - 1, i + 2); triangle[1][2] = triangleArea(triangle); triangles.push(triangle); heap.push(triangle); } // Always keep the arc endpoints! arc[0][2] = arc[n][2] = Infinity; for (var i = 0, n = triangles.length; i < n; ++i) { triangle = triangles[i]; triangle.previous = triangles[i - 1]; triangle.next = triangles[i + 1]; } }); while (triangle = heap.pop()) { var previous = triangle.previous, next = triangle.next; // If the area of the current point is less than that of the previous point // to be eliminated, use the latter's area instead. This ensures that the // current point cannot be eliminated without eliminating previously- // eliminated points. if (triangle[1][2] < maxArea) triangle[1][2] = maxArea; else maxArea = triangle[1][2]; if (previous) { previous.next = next; previous[2] = triangle[2]; update(previous); } if (next) { next.previous = previous; next[0] = triangle[0]; update(next); } } topology.arcs.forEach(function(arc) { arc.forEach(relative); }); function update(triangle) { heap.remove(triangle); triangle[1][2] = triangleArea(triangle); heap.push(triangle); } return topology; }; function cartesianArea(triangle) { return Math.abs( (triangle[0][0] - triangle[2][0]) * (triangle[1][1] - triangle[0][1]) - (triangle[0][0] - triangle[1][0]) * (triangle[2][1] - triangle[0][1]) ); } function compareArea(a, b) { return a[1][2] - b[1][2]; } function minHeap(compare) { var heap = {}, array = []; heap.push = function() { for (var i = 0, n = arguments.length; i < n; ++i) { var object = arguments[i]; up(object.index = array.push(object) - 1); } return array.length; }; heap.pop = function() { var removed = array[0], object = array.pop(); if (array.length) { array[object.index = 0] = object; down(0); } return removed; }; heap.remove = function(removed) { var i = removed.index, object = array.pop(); if (i !== array.length) { array[object.index = i] = object; (compare(object, removed) < 0 ? up : down)(i); } return i; }; function up(i) { var object = array[i]; while (i > 0) { var up = ((i + 1) >> 1) - 1, parent = array[up]; if (compare(object, parent) >= 0) break; array[parent.index = i] = parent; array[object.index = i = up] = object; } } function down(i) { var object = array[i]; while (true) { var right = (i + 1) << 1, left = right - 1, down = i, child = array[down]; if (left < array.length && compare(array[left], child) < 0) child = array[down = left]; if (right < array.length && compare(array[right], child) < 0) child = array[down = right]; if (down === i) break; array[child.index = i] = child; array[object.index = i = down] = object; } } return heap; } function transformAbsolute(transform) { if (!transform) return noop; 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 transformRelative(transform) { if (!transform) return noop; 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; var x1 = (point[0] - dx) / kx | 0, y1 = (point[1] - dy) / ky | 0; point[0] = x1 - x0; point[1] = y1 - y0; x0 = x1; y0 = y1; }; } function noop() {} return { version: "1.4.2", mesh: mesh, feature: featureOrCollection, neighbors: neighbors, presimplify: presimplify }; })();
// Copyright 2005 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview Implements the disposable interface. The dispose method is used * to clean up references and resources. * @author arv@google.com (Erik Arvidsson) */ goog.provide('goog.Disposable'); /** @suppress {extraProvide} */ goog.provide('goog.dispose'); /** @suppress {extraProvide} */ goog.provide('goog.disposeAll'); goog.require('goog.disposable.IDisposable'); /** * Class that provides the basic implementation for disposable objects. If your * class holds one or more references to COM objects, DOM nodes, or other * disposable objects, it should extend this class or implement the disposable * interface (defined in goog.disposable.IDisposable). * @constructor * @implements {goog.disposable.IDisposable} */ goog.Disposable = function() { if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) { if (goog.Disposable.INCLUDE_STACK_ON_CREATION) { this.creationStack = new Error().stack; } goog.Disposable.instances_[goog.getUid(this)] = this; } }; /** * @enum {number} Different monitoring modes for Disposable. */ goog.Disposable.MonitoringMode = { /** * No monitoring. */ OFF: 0, /** * Creating and disposing the goog.Disposable instances is monitored. All * disposable objects need to call the {@code goog.Disposable} base * constructor. The PERMANENT mode must be switched on before creating any * goog.Disposable instances. */ PERMANENT: 1, /** * INTERACTIVE mode can be switched on and off on the fly without producing * errors. It also doesn't warn if the disposable objects don't call the * {@code goog.Disposable} base constructor. */ INTERACTIVE: 2 }; /** * @define {number} The monitoring mode of the goog.Disposable * instances. Default is OFF. Switching on the monitoring is only * recommended for debugging because it has a significant impact on * performance and memory usage. If switched off, the monitoring code * compiles down to 0 bytes. */ goog.define('goog.Disposable.MONITORING_MODE', 0); /** * @define {boolean} Whether to attach creation stack to each created disposable * instance; This is only relevant for when MonitoringMode != OFF. */ goog.define('goog.Disposable.INCLUDE_STACK_ON_CREATION', true); /** * Maps the unique ID of every undisposed {@code goog.Disposable} object to * the object itself. * @type {!Object.<number, !goog.Disposable>} * @private */ goog.Disposable.instances_ = {}; /** * @return {!Array.<!goog.Disposable>} All {@code goog.Disposable} objects that * haven't been disposed of. */ goog.Disposable.getUndisposedObjects = function() { var ret = []; for (var id in goog.Disposable.instances_) { if (goog.Disposable.instances_.hasOwnProperty(id)) { ret.push(goog.Disposable.instances_[Number(id)]); } } return ret; }; /** * Clears the registry of undisposed objects but doesn't dispose of them. */ goog.Disposable.clearUndisposedObjects = function() { goog.Disposable.instances_ = {}; }; /** * Whether the object has been disposed of. * @type {boolean} * @private */ goog.Disposable.prototype.disposed_ = false; /** * Callbacks to invoke when this object is disposed. * @type {Array.<!Function>} * @private */ goog.Disposable.prototype.onDisposeCallbacks_; /** * If monitoring the goog.Disposable instances is enabled, stores the creation * stack trace of the Disposable instance. * @type {string} */ goog.Disposable.prototype.creationStack; /** * @return {boolean} Whether the object has been disposed of. * @override */ goog.Disposable.prototype.isDisposed = function() { return this.disposed_; }; /** * @return {boolean} Whether the object has been disposed of. * @deprecated Use {@link #isDisposed} instead. */ goog.Disposable.prototype.getDisposed = goog.Disposable.prototype.isDisposed; /** * Disposes of the object. If the object hasn't already been disposed of, calls * {@link #disposeInternal}. Classes that extend {@code goog.Disposable} should * override {@link #disposeInternal} in order to delete references to COM * objects, DOM nodes, and other disposable objects. Reentrant. * * @return {void} Nothing. * @override */ goog.Disposable.prototype.dispose = function() { if (!this.disposed_) { // Set disposed_ to true first, in case during the chain of disposal this // gets disposed recursively. this.disposed_ = true; this.disposeInternal(); if (goog.Disposable.MONITORING_MODE != goog.Disposable.MonitoringMode.OFF) { var uid = goog.getUid(this); if (goog.Disposable.MONITORING_MODE == goog.Disposable.MonitoringMode.PERMANENT && !goog.Disposable.instances_.hasOwnProperty(uid)) { throw Error(this + ' did not call the goog.Disposable base ' + 'constructor or was disposed of after a clearUndisposedObjects ' + 'call'); } delete goog.Disposable.instances_[uid]; } } }; /** * Associates a disposable object with this object so that they will be disposed * together. * @param {goog.disposable.IDisposable} disposable that will be disposed when * this object is disposed. */ goog.Disposable.prototype.registerDisposable = function(disposable) { this.addOnDisposeCallback(goog.partial(goog.dispose, disposable)); }; /** * Invokes a callback function when this object is disposed. Callbacks are * invoked in the order in which they were added. * @param {function(this:T):?} callback The callback function. * @param {T=} opt_scope An optional scope to call the callback in. * @template T */ goog.Disposable.prototype.addOnDisposeCallback = function(callback, opt_scope) { if (!this.onDisposeCallbacks_) { this.onDisposeCallbacks_ = []; } this.onDisposeCallbacks_.push( goog.isDef(opt_scope) ? goog.bind(callback, opt_scope) : callback); }; /** * Deletes or nulls out any references to COM objects, DOM nodes, or other * disposable objects. Classes that extend {@code goog.Disposable} should * override this method. * Not reentrant. To avoid calling it twice, it must only be called from the * subclass' {@code disposeInternal} method. Everywhere else the public * {@code dispose} method must be used. * For example: * <pre> * mypackage.MyClass = function() { * mypackage.MyClass.base(this, 'constructor'); * // Constructor logic specific to MyClass. * ... * }; * goog.inherits(mypackage.MyClass, goog.Disposable); * * mypackage.MyClass.prototype.disposeInternal = function() { * // Dispose logic specific to MyClass. * ... * // Call superclass's disposeInternal at the end of the subclass's, like * // in C++, to avoid hard-to-catch issues. * mypackage.MyClass.base(this, 'disposeInternal'); * }; * </pre> * @protected */ goog.Disposable.prototype.disposeInternal = function() { if (this.onDisposeCallbacks_) { while (this.onDisposeCallbacks_.length) { this.onDisposeCallbacks_.shift()(); } } }; /** * Returns True if we can verify the object is disposed. * Calls {@code isDisposed} on the argument if it supports it. If obj * is not an object with an isDisposed() method, return false. * @param {*} obj The object to investigate. * @return {boolean} True if we can verify the object is disposed. */ goog.Disposable.isDisposed = function(obj) { if (obj && typeof obj.isDisposed == 'function') { return obj.isDisposed(); } return false; }; /** * Calls {@code dispose} on the argument if it supports it. If obj is not an * object with a dispose() method, this is a no-op. * @param {*} obj The object to dispose of. */ goog.dispose = function(obj) { if (obj && typeof obj.dispose == 'function') { obj.dispose(); } }; /** * Calls {@code dispose} on each member of the list that supports it. (If the * member is an ArrayLike, then {@code goog.disposeAll()} will be called * recursively on each of its members.) If the member is not an object with a * {@code dispose()} method, then it is ignored. * @param {...*} var_args The list. */ goog.disposeAll = function(var_args) { for (var i = 0, len = arguments.length; i < len; ++i) { var disposable = arguments[i]; if (goog.isArrayLike(disposable)) { goog.disposeAll.apply(null, disposable); } else { goog.dispose(disposable); } } };
var fs = require('fs'); var path = require('path'); var dynamicallyCreatedFilename = path.join('/files/', 'somefile'); var stuff = fs.readFileSync(__dirname + dynamicallyCreatedFilename + __dirname, 'utf8');
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'image2', 'lt', { alt: 'Alternatyvus Tekstas', btnUpload: 'Siųsti į serverį', captioned: 'Captioned image', // MISSING captionPlaceholder: 'Caption', // MISSING infoTab: 'Vaizdo informacija', lockRatio: 'Išlaikyti proporciją', menu: 'Vaizdo savybės', pathName: 'image', // MISSING pathNameCaption: 'caption', // MISSING resetSize: 'Atstatyti dydį', resizer: 'Click and drag to resize', // MISSING title: 'Vaizdo savybės', uploadTab: 'Siųsti', urlMissing: 'Paveiksliuko nuorodos nėra.' } );
YUI.add('event-tap', function (Y, NAME) { /** The tap module provides a gesture events, "tap", which normalizes user interactions across touch and mouse or pointer based input devices. This can be used by application developers to build input device agnostic components which behave the same in response to either touch or mouse based interaction. 'tap' is like a touchscreen 'click', only it requires much less finger-down time since it listens to touch events, but reverts to mouse events if touch is not supported. @example YUI().use('event-tap', function (Y) { Y.one('#my-button').on('tap', function (e) { Y.log('Button was tapped on'); }); }); @module event @submodule event-tap @author Andres Garza, matuzak and tilo mitra @since 3.7.0 */ var doc = Y.config.doc, GESTURE_MAP = Y.Event._GESTURE_MAP, SUPPORTS_TOUCHES = !!(doc && doc.createTouch), EVT_START = GESTURE_MAP.start, EVT_MOVE = GESTURE_MAP.move, EVT_END = GESTURE_MAP.end, EVT_CANCEL = GESTURE_MAP.cancel, EVT_TAP = 'tap', HANDLES = { START: 'Y_TAP_ON_START_HANDLE', MOVE: 'Y_TAP_ON_MOVE_HANDLE', END: 'Y_TAP_ON_END_HANDLE', CANCEL: 'Y_TAP_ON_CANCEL_HANDLE' }; function detachHelper(subscription, handles, subset, context) { handles = subset ? handles : [ handles.START, handles.MOVE, handles.END, handles.CANCEL ]; Y.Array.each(handles, function (item, index, array) { var handle = subscription[item]; if (handle) { handle.detach(); subscription[item] = null; } }); } /** Sets up a "tap" event, that is fired on touch devices in response to a tap event (finger down, finder up). This event can be used instead of listening for click events which have a 500ms delay on most touch devices. This event can also be listened for using node.delegate(). @event tap @param type {string} "tap" @param fn {function} The method the event invokes. It receives the event facade of the underlying DOM event. @for Event @return {EventHandle} the detach handle */ Y.Event.define(EVT_TAP, { /** This function should set up the node that will eventually fire the event. Usage: node.on('tap', function (e) { Y.log('the node was tapped on'); }); @method on @param {Y.Node} node @param {Array} subscription @param {Boolean} notifier @public @static **/ on: function (node, subscription, notifier) { subscription[HANDLES.START] = node.on(EVT_START, this.touchStart, this, node, subscription, notifier); }, /** Detaches all event subscriptions set up by the event-tap module @method detach @param {Y.Node} node @param {Array} subscription @param {Boolean} notifier @public @static **/ detach: function (node, subscription, notifier) { detachHelper(subscription, HANDLES); }, /** Event delegation for the 'tap' event. 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. Usage: node.delegate('tap', function (e) { Y.log('li a inside node was tapped.'); }, 'li a'); @method delegate @param {Y.Node} node @param {Array} subscription @param {Boolean} notifier @param {String | Function} filter @public @static **/ delegate: function (node, subscription, notifier, filter) { subscription[HANDLES.START] = node.delegate(EVT_START, function (e) { this.touchStart(e, node, subscription, notifier, true); }, filter, this); }, /** Detaches the delegated event subscriptions set up by the event-tap module. Only used if you use node.delegate(...) instead of node.on(...); @method detachDelegate @param {Y.Node} node @param {Array} subscription @param {Boolean} notifier @public @static **/ detachDelegate: function (node, subscription, notifier) { detachHelper(subscription, HANDLES); }, /** Called when the monitor(s) are tapped on, either through touchstart or mousedown. @method touchStart @param {DOMEventFacade} event @param {Y.Node} node @param {Array} subscription @param {Boolean} notifier @param {Boolean} delegate @protected @static **/ touchStart: function (event, node, subscription, notifier, delegate) { var context = { canceled: false }; //move ways to quit early to the top. // no right clicks if (event.button && event.button === 3) { return; } // for now just support a 1 finger count (later enhance via config) if (event.touches && event.touches.length !== 1) { return; } context.node = delegate ? event.currentTarget : node; //There is a double check in here to support event simulation tests, in which //event.touches can be undefined when simulating 'touchstart' on touch devices. if (SUPPORTS_TOUCHES && event.touches) { context.startXY = [ event.touches[0].pageX, event.touches[0].pageY ]; } else { context.startXY = [ event.pageX, event.pageY ]; } //Possibly outdated issue: something is off with the move that it attaches it but never triggers the handler subscription[HANDLES.MOVE] = node.once(EVT_MOVE, this.touchMove, this, node, subscription, notifier, delegate, context); subscription[HANDLES.END] = node.once(EVT_END, this.touchEnd, this, node, subscription, notifier, delegate, context); subscription[HANDLES.CANCEL] = node.once(EVT_CANCEL, this.touchMove, this, node, subscription, notifier, delegate, context); }, /** Called when the monitor(s) fires a touchmove or touchcancel event (or the mouse equivalent). This method detaches event handlers so that 'tap' is not fired. @method touchMove @param {DOMEventFacade} event @param {Y.Node} node @param {Array} subscription @param {Boolean} notifier @param {Boolean} delegate @param {Object} context @protected @static **/ touchMove: function (event, node, subscription, notifier, delegate, context) { detachHelper(subscription, [ HANDLES.MOVE, HANDLES.END, HANDLES.CANCEL ], true, context); context.cancelled = true; }, /** Called when the monitor(s) fires a touchend event (or the mouse equivalent). This method fires the 'tap' event if certain requirements are met. @method touchEnd @param {DOMEventFacade} event @param {Y.Node} node @param {Array} subscription @param {Boolean} notifier @param {Boolean} delegate @param {Object} context @protected @static **/ touchEnd: function (event, node, subscription, notifier, delegate, context) { var startXY = context.startXY, endXY, clientXY; //There is a double check in here to support event simulation tests, in which //event.touches can be undefined when simulating 'touchstart' on touch devices. if (SUPPORTS_TOUCHES && event.changedTouches) { endXY = [ event.changedTouches[0].pageX, event.changedTouches[0].pageY ]; clientXY = [event.changedTouches[0].clientX, event.changedTouches[0].clientY]; } else { endXY = [ event.pageX, event.pageY ]; clientXY = [event.clientX, event.clientY]; } detachHelper(subscription, [ HANDLES.MOVE, HANDLES.END, HANDLES.CANCEL ], true, context); // make sure mouse didn't move if (Math.abs(endXY[0] - startXY[0]) === 0 && Math.abs(endXY[1] - startXY[1]) === 0) { event.type = EVT_TAP; event.pageX = endXY[0]; event.pageY = endXY[1]; event.clientX = clientXY[0]; event.clientY = clientXY[1]; event.currentTarget = context.node; notifier.fire(event); } } }); }, '@VERSION@', {"requires": ["node-base", "event-base", "event-touch", "event-synthetic"]});
(function(a){var b={set:{colors:1,values:1,backgroundColor:1,scaleColors:1,normalizeFunction:1,focus:1},get:{selectedRegions:1,selectedMarkers:1,mapObject:1,regionName:1}};a.fn.vectorMap=function(d){var f,c,e;if(d==="addMap"){jvm.WorldMap.maps[arguments[1]]=arguments[2]}else{if((d==="set"||d==="get")&&b[d][arguments[1]]){c=arguments[1].charAt(0).toUpperCase()+arguments[1].substr(1);return this.data("mapObject")[d+c].apply(this.data("mapObject"),Array.prototype.slice.call(arguments,2))}else{d=d||{};d.container=this;f=new jvm.WorldMap(d);this.data("mapObject",f)}}}})(jQuery);
/* eslint-env mocha */ /* eslint no-template-curly-in-string: 0 */ import assert from 'assert'; import { extractProp } from '../helper'; import getPropValue from '../../src/getPropValue'; describe('getPropValue', () => { it('should export a function', () => { const expected = 'function'; const actual = typeof getPropValue; assert.equal(expected, actual); }); it('should return undefined when not provided with a JSXAttribute', () => { const expected = undefined; const actual = getPropValue(1); assert.equal(expected, actual); }); it('should throw error when trying to get value from unknown node type', () => { const prop = { type: 'JSXAttribute', value: { type: 'JSXExpressionContainer', }, }; assert.throws(() => { getPropValue(prop); }, Error); }); describe('Null', () => { it('should return true when no value is given', () => { const prop = extractProp('<div foo />'); const expected = true; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Literal', () => { it('should return correct string if value is a string', () => { const prop = extractProp('<div foo="bar" />'); const expected = 'bar'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return correct string if value is a string expression', () => { const prop = extractProp('<div foo={"bar"} />'); const expected = 'bar'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return correct integer if value is a integer expression', () => { const prop = extractProp('<div foo={1} />'); const expected = 1; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should convert "true" to boolean type', () => { const prop = extractProp('<div foo="true" />'); const expected = true; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should convert "false" to boolean type', () => { const prop = extractProp('<div foo="false" />'); const expected = false; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('JSXElement', () => { it('should return correct representation of JSX element as a string', () => { const prop = extractProp('<div foo=<bar /> />'); const expected = '<bar />'; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Identifier', () => { it('should return string representation of variable identifier', () => { const prop = extractProp('<div foo={bar} />'); const expected = 'bar'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return undefined when identifier is literally `undefined`', () => { const prop = extractProp('<div foo={undefined} />'); const expected = undefined; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return String object when using a reserved JavaScript object', () => { const prop = extractProp('<div foo={String} />'); const expected = String; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return Array object when using a reserved JavaScript object', () => { const prop = extractProp('<div foo={Array} />'); const expected = Array; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return Date object when using a reserved JavaScript object', () => { const prop = extractProp('<div foo={Date} />'); const expected = Date; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return Infinity object when using a reserved JavaScript object', () => { const prop = extractProp('<div foo={Infinity} />'); const expected = Infinity; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return Math object when using a reserved JavaScript object', () => { const prop = extractProp('<div foo={Math} />'); const expected = Math; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return Number object when using a reserved JavaScript object', () => { const prop = extractProp('<div foo={Number} />'); const expected = Number; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return Object object when using a reserved JavaScript object', () => { const prop = extractProp('<div foo={Object} />'); const expected = Object; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Template literal', () => { it('should return template literal with vars wrapped in curly braces', () => { const prop = extractProp('<div foo={`bar ${baz}`} />'); const expected = 'bar {baz}'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should drop variables in template literals that are literally undefined', () => { const prop = extractProp('<div foo={`bar ${undefined}`} />'); const expected = 'bar '; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return template literal with expression type wrapped in curly braces', () => { const prop = extractProp('<div foo={`bar ${baz()}`} />'); const expected = 'bar {CallExpression}'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should ignore non-expressions in the template literal', () => { const prop = extractProp('<div foo={`bar ${<baz />}`} />'); const expected = 'bar '; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Tagged Template literal', () => { it('should return template literal with vars wrapped in curly braces', () => { const prop = extractProp('<div foo={noop`bar ${baz}`} />'); const expected = 'bar {baz}'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should drop variables in template literals that are literally undefined', () => { const prop = extractProp('<div foo={noop`bar ${undefined}`} />'); const expected = 'bar '; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return template literal with expression type wrapped in curly braces', () => { const prop = extractProp('<div foo={noop`bar ${baz()}`} />'); const expected = 'bar {CallExpression}'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should ignore non-expressions in the template literal', () => { const prop = extractProp('<div foo={noop`bar ${<baz />}`} />'); const expected = 'bar '; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Arrow function expression', () => { it('should return a function', () => { const prop = extractProp('<div foo={ () => { return "bar"; }} />'); const expected = 'function'; const actual = getPropValue(prop); assert.equal(expected, typeof actual); // For code coverage ¯\_(ツ)_/¯ actual(); }); it('should handle ArrowFunctionExpression as conditional consequent', () => { const prop = extractProp('<div foo={ (true) ? () => null : () => ({})} />'); const expected = 'function'; const actual = getPropValue(prop); assert.equal(expected, typeof actual); // For code coverage ¯\_(ツ)_/¯ actual(); }); }); describe('Function expression', () => { it('should return a function', () => { const prop = extractProp('<div foo={ function() { return "bar"; } } />'); const expected = 'function'; const actual = getPropValue(prop); assert.equal(expected, typeof actual); // For code coverage ¯\_(ツ)_/¯ actual(); }); }); describe('Logical expression', () => { it('should correctly infer result of && logical expression based on derived values', () => { const prop = extractProp('<div foo={bar && baz} />'); const expected = 'baz'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return undefined when evaluating `undefined && undefined` ', () => { const prop = extractProp('<div foo={undefined && undefined} />'); const expected = undefined; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should correctly infer result of || logical expression based on derived values', () => { const prop = extractProp('<div foo={bar || baz} />'); const expected = 'bar'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should correctly infer result of || logical expression based on derived values', () => { const prop = extractProp('<div foo={undefined || baz} />'); const expected = 'baz'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return undefined when evaluating `undefined || undefined` ', () => { const prop = extractProp('<div foo={undefined || undefined} />'); const expected = undefined; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Member expression', () => { it('should return string representation of form `object.property`', () => { const prop = extractProp('<div foo={bar.baz} />'); const expected = 'bar.baz'; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Call expression', () => { it('should return string representation of callee', () => { const prop = extractProp('<div foo={bar()} />'); const expected = 'bar'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return string representation of callee', () => { const prop = extractProp('<div foo={bar.call()} />'); const expected = 'bar.call'; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Unary expression', () => { it('should correctly evaluate an expression that prefixes with -', () => { const prop = extractProp('<div foo={-bar} />'); // -"bar" => NaN const expected = true; const actual = isNaN(getPropValue(prop)); assert.equal(expected, actual); }); it('should correctly evaluate an expression that prefixes with -', () => { const prop = extractProp('<div foo={-42} />'); const expected = -42; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should correctly evaluate an expression that prefixes with +', () => { const prop = extractProp('<div foo={+bar} />'); // +"bar" => NaN const expected = true; const actual = isNaN(getPropValue(prop)); assert.equal(expected, actual); }); it('should correctly evaluate an expression that prefixes with +', () => { const prop = extractProp('<div foo={+42} />'); const expected = 42; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should correctly evaluate an expression that prefixes with !', () => { const prop = extractProp('<div foo={!bar} />'); const expected = false; // !"bar" === false const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should correctly evaluate an expression that prefixes with ~', () => { const prop = extractProp('<div foo={~bar} />'); const expected = -1; // ~"bar" === -1 const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return true when evaluating `delete foo`', () => { const prop = extractProp('<div foo={delete x} />'); const expected = true; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should return undefined when evaluating `void foo`', () => { const prop = extractProp('<div foo={void x} />'); const expected = undefined; const actual = getPropValue(prop); assert.equal(expected, actual); }); // TODO: We should fix this to check to see if we can evaluate it. it('should return undefined when evaluating `typeof foo`', () => { const prop = extractProp('<div foo={typeof x} />'); const expected = undefined; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Update expression', () => { it('should correctly evaluate an expression that prefixes with ++', () => { const prop = extractProp('<div foo={++bar} />'); // ++"bar" => NaN const expected = true; const actual = isNaN(getPropValue(prop)); assert.equal(expected, actual); }); it('should correctly evaluate an expression that prefixes with --', () => { const prop = extractProp('<div foo={--bar} />'); const expected = true; const actual = isNaN(getPropValue(prop)); assert.equal(expected, actual); }); it('should correctly evaluate an expression that suffixes with ++', () => { const prop = extractProp('<div foo={bar++} />'); // "bar"++ => NaN const expected = true; const actual = isNaN(getPropValue(prop)); assert.equal(expected, actual); }); it('should correctly evaluate an expression that suffixes with --', () => { const prop = extractProp('<div foo={bar--} />'); const expected = true; const actual = isNaN(getPropValue(prop)); assert.equal(expected, actual); }); }); describe('This expression', () => { it('should return string value `this`', () => { const prop = extractProp('<div foo={this} />'); const expected = 'this'; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Conditional expression', () => { it('should evaluate the conditional based on the derived values correctly', () => { const prop = extractProp('<div foo={bar ? baz : bam} />'); const expected = 'baz'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the conditional based on the derived values correctly', () => { const prop = extractProp('<div foo={undefined ? baz : bam} />'); const expected = 'bam'; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the conditional based on the derived values correctly', () => { const prop = extractProp('<div foo={(1 > 2) ? baz : bam} />'); const expected = 'bam'; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Binary expression', () => { it('should evaluate the `==` operator correctly', () => { const trueProp = extractProp('<div foo={1 == "1"} />'); const falseProp = extractProp('<div foo={1 == bar} />'); const trueVal = getPropValue(trueProp); const falseVal = getPropValue(falseProp); assert.equal(true, trueVal); assert.equal(false, falseVal); }); it('should evaluate the `!=` operator correctly', () => { const trueProp = extractProp('<div foo={1 != "2"} />'); const falseProp = extractProp('<div foo={1 != "1"} />'); const trueVal = getPropValue(trueProp); const falseVal = getPropValue(falseProp); assert.equal(true, trueVal); assert.equal(false, falseVal); }); it('should evaluate the `===` operator correctly', () => { const trueProp = extractProp('<div foo={1 === 1} />'); const falseProp = extractProp('<div foo={1 === "1"} />'); const trueVal = getPropValue(trueProp); const falseVal = getPropValue(falseProp); assert.equal(true, trueVal); assert.equal(false, falseVal); }); it('should evaluate the `!==` operator correctly', () => { const trueProp = extractProp('<div foo={1 !== "1"} />'); const falseProp = extractProp('<div foo={1 !== 1} />'); const trueVal = getPropValue(trueProp); const falseVal = getPropValue(falseProp); assert.equal(true, trueVal); assert.equal(false, falseVal); }); it('should evaluate the `<` operator correctly', () => { const trueProp = extractProp('<div foo={1 < 2} />'); const falseProp = extractProp('<div foo={1 < 0} />'); const trueVal = getPropValue(trueProp); const falseVal = getPropValue(falseProp); assert.equal(true, trueVal); assert.equal(false, falseVal); }); it('should evaluate the `>` operator correctly', () => { const trueProp = extractProp('<div foo={1 > 0} />'); const falseProp = extractProp('<div foo={1 > 2} />'); const trueVal = getPropValue(trueProp); const falseVal = getPropValue(falseProp); assert.equal(true, trueVal); assert.equal(false, falseVal); }); it('should evaluate the `<=` operator correctly', () => { const trueProp = extractProp('<div foo={1 <= 1} />'); const falseProp = extractProp('<div foo={1 <= 0} />'); const trueVal = getPropValue(trueProp); const falseVal = getPropValue(falseProp); assert.equal(true, trueVal); assert.equal(false, falseVal); }); it('should evaluate the `>=` operator correctly', () => { const trueProp = extractProp('<div foo={1 >= 1} />'); const falseProp = extractProp('<div foo={1 >= 2} />'); const trueVal = getPropValue(trueProp); const falseVal = getPropValue(falseProp); assert.equal(true, trueVal); assert.equal(false, falseVal); }); it('should evaluate the `<<` operator correctly', () => { const prop = extractProp('<div foo={1 << 2} />'); const expected = 4; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `>>` operator correctly', () => { const prop = extractProp('<div foo={1 >> 2} />'); const expected = 0; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `>>>` operator correctly', () => { const prop = extractProp('<div foo={2 >>> 1} />'); const expected = 1; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `+` operator correctly', () => { const prop = extractProp('<div foo={1 + 1} />'); const expected = 2; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `-` operator correctly', () => { const prop = extractProp('<div foo={1 - 1} />'); const expected = 0; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `*` operator correctly', () => { const prop = extractProp('<div foo={10 * 10} />'); const expected = 100; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `/` operator correctly', () => { const prop = extractProp('<div foo={10 / 2} />'); const expected = 5; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `%` operator correctly', () => { const prop = extractProp('<div foo={10 % 3} />'); const expected = 1; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `|` operator correctly', () => { const prop = extractProp('<div foo={10 | 1} />'); const expected = 11; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `^` operator correctly', () => { const prop = extractProp('<div foo={10 ^ 1} />'); const expected = 11; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `&` operator correctly', () => { const prop = extractProp('<div foo={10 & 1} />'); const expected = 0; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `in` operator correctly', () => { const prop = extractProp('<div foo={foo in bar} />'); const expected = false; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `instanceof` operator correctly', () => { const prop = extractProp('<div foo={{} instanceof Object} />'); const expected = true; const actual = getPropValue(prop); assert.equal(expected, actual); }); it('should evaluate the `instanceof` operator when right side is not a function', () => { const prop = extractProp('<div foo={"bar" instanceof Baz} />'); const expected = false; const actual = getPropValue(prop); assert.equal(expected, actual); }); }); describe('Object expression', () => { it('should evaluate to a correct representation of the object in props', () => { const prop = extractProp('<div foo={ { bar: "baz" } } />'); const expected = { bar: 'baz' }; const actual = getPropValue(prop); assert.deepEqual(expected, actual); }); }); describe('New expression', () => { it('should return a new empty object', () => { const prop = extractProp('<div foo={new Bar()} />'); const expected = {}; const actual = getPropValue(prop); assert.deepEqual(expected, actual); }); }); describe('Array expression', () => { it('should evaluate to correct representation of the the array in props', () => { const prop = extractProp('<div foo={["bar", 42, null]} />'); const expected = ['bar', 42, null]; const actual = getPropValue(prop); assert.deepEqual(expected, actual); }); }); it('should return an empty array provided an empty array in props', () => { const prop = extractProp('<div foo={[]} />'); const expected = []; const actual = getPropValue(prop); assert.deepEqual(expected, actual); }); });
/* Highcharts JS v6.0.0 (2017-10-04) Highcharts variwide module (c) 2010-2017 Torstein Honsi License: www.highcharts.com/license */ (function(d){"object"===typeof module&&module.exports?module.exports=d:d(Highcharts)})(function(d){(function(b){var d=b.seriesType,l=b.seriesTypes,k=b.each,m=b.pick;d("variwide","column",{pointPadding:0,groupPadding:0},{pointArrayMap:["y","z"],parallelArrays:["x","y","z"],processData:function(){var a=this;this.totalZ=0;this.relZ=[];l.column.prototype.processData.call(this);k(this.zData,function(g,c){a.relZ[c]=a.totalZ;a.totalZ+=g});this.xAxis.categories&&(this.xAxis.variwide=!0)},postTranslate:function(a, g){var c=this.relZ,h=this.xAxis.len,e=this.totalZ,f=a/c.length*h,b=(a+1)/c.length*h,d=m(c[a],e)/e*h;a=m(c[a+1],e)/e*h;return d+(g-f)*(a-d)/(b-f)},translate:function(){var a=this.options.crisp;this.options.crisp=!1;l.column.prototype.translate.call(this);this.options.crisp=a;var b=this.chart.inverted,c=this.borderWidth%2/2;k(this.points,function(a,e){var f=this.postTranslate(e,a.shapeArgs.x),d=this.postTranslate(e,a.shapeArgs.x+a.shapeArgs.width);this.options.crisp&&(f=Math.round(f)-c,d=Math.round(d)- c);a.shapeArgs.x=f;a.shapeArgs.width=d-f;a.tooltipPos[b?1:0]=this.postTranslate(e,a.tooltipPos[b?1:0])},this)}},{isValid:function(){return b.isNumber(this.y,!0)&&b.isNumber(this.z,!0)}});b.Tick.prototype.postTranslate=function(a,b,c){a[b]=this.axis.pos+this.axis.series[0].postTranslate(c,a[b]-this.axis.pos)};b.wrap(b.Tick.prototype,"getPosition",function(a,b,c){var d=this.axis,e=a.apply(this,Array.prototype.slice.call(arguments,1)),f=b?"x":"y";d.categories&&d.variwide&&(this[f+"Orig"]=e[f],this.postTranslate(e, f,c));return e});b.wrap(b.Tick.prototype,"getLabelPosition",function(a,b,d,h,e,f,l,k){var c=Array.prototype.slice.call(arguments,1),g=e?"x":"y";this.axis.variwide&&"number"===typeof this[g+"Orig"]&&(c[e?0:1]=this[g+"Orig"]);c=a.apply(this,c);this.axis.variwide&&this.axis.categories&&this.postTranslate(c,g,k);return c})})(d)});
define( [ "../var/pnum" ], function( pnum ) { return new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); } );
/*! * autocomplete.js 0.8.0 * https://github.com/algolia/autocomplete.js * Copyright 2015 Algolia, Inc. and other contributors; Licensed MIT */ (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; window.autocomplete = require('./src/standalone/index.js'); },{"./src/standalone/index.js":14}],2:[function(require,module,exports){ /* Zepto 1.1.6 - zepto event ajax form ie - zeptojs.com/license */ var Zepto = (function() { var undefined, key, $, classList, emptyArray = [], slice = emptyArray.slice, filter = emptyArray.filter, document = window.document, elementDisplay = {}, classCache = {}, cssNumber = { 'column-count': 1, 'columns': 1, 'font-weight': 1, 'line-height': 1,'opacity': 1, 'z-index': 1, 'zoom': 1 }, fragmentRE = /^\s*<(\w+|!)[^>]*>/, singleTagRE = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, tagExpanderRE = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig, rootNodeRE = /^(?:body|html)$/i, capitalRE = /([A-Z])/g, // special attributes that should be get/set via method calls methodAttributes = ['val', 'css', 'html', 'text', 'data', 'width', 'height', 'offset'], adjacencyOperators = [ 'after', 'prepend', 'before', 'append' ], table = document.createElement('table'), tableRow = document.createElement('tr'), containers = { 'tr': document.createElement('tbody'), 'tbody': table, 'thead': table, 'tfoot': table, 'td': tableRow, 'th': tableRow, '*': document.createElement('div') }, readyRE = /complete|loaded|interactive/, simpleSelectorRE = /^[\w-]*$/, class2type = {}, toString = class2type.toString, zepto = {}, camelize, uniq, tempParent = document.createElement('div'), propMap = { 'tabindex': 'tabIndex', 'readonly': 'readOnly', 'for': 'htmlFor', 'class': 'className', 'maxlength': 'maxLength', 'cellspacing': 'cellSpacing', 'cellpadding': 'cellPadding', 'rowspan': 'rowSpan', 'colspan': 'colSpan', 'usemap': 'useMap', 'frameborder': 'frameBorder', 'contenteditable': 'contentEditable' }, isArray = Array.isArray || function(object){ return object instanceof Array } zepto.matches = function(element, selector) { if (!selector || !element || element.nodeType !== 1) return false var matchesSelector = element.webkitMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.matchesSelector if (matchesSelector) return matchesSelector.call(element, selector) // fall back to performing a selector: var match, parent = element.parentNode, temp = !parent if (temp) (parent = tempParent).appendChild(element) match = ~zepto.qsa(parent, selector).indexOf(element) temp && tempParent.removeChild(element) return match } function type(obj) { return obj == null ? String(obj) : class2type[toString.call(obj)] || "object" } function isFunction(value) { return type(value) == "function" } function isWindow(obj) { return obj != null && obj == obj.window } function isDocument(obj) { return obj != null && obj.nodeType == obj.DOCUMENT_NODE } function isObject(obj) { return type(obj) == "object" } function isPlainObject(obj) { return isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype } function likeArray(obj) { return typeof obj.length == 'number' } function compact(array) { return filter.call(array, function(item){ return item != null }) } function flatten(array) { return array.length > 0 ? $.fn.concat.apply([], array) : array } camelize = function(str){ return str.replace(/-+(.)?/g, function(match, chr){ return chr ? chr.toUpperCase() : '' }) } function dasherize(str) { return str.replace(/::/g, '/') .replace(/([A-Z]+)([A-Z][a-z])/g, '$1_$2') .replace(/([a-z\d])([A-Z])/g, '$1_$2') .replace(/_/g, '-') .toLowerCase() } uniq = function(array){ return filter.call(array, function(item, idx){ return array.indexOf(item) == idx }) } function classRE(name) { return name in classCache ? classCache[name] : (classCache[name] = new RegExp('(^|\\s)' + name + '(\\s|$)')) } function maybeAddPx(name, value) { return (typeof value == "number" && !cssNumber[dasherize(name)]) ? value + "px" : value } function defaultDisplay(nodeName) { var element, display if (!elementDisplay[nodeName]) { element = document.createElement(nodeName) document.body.appendChild(element) display = getComputedStyle(element, '').getPropertyValue("display") element.parentNode.removeChild(element) display == "none" && (display = "block") elementDisplay[nodeName] = display } return elementDisplay[nodeName] } function children(element) { return 'children' in element ? slice.call(element.children) : $.map(element.childNodes, function(node){ if (node.nodeType == 1) return node }) } // `$.zepto.fragment` takes a html string and an optional tag name // to generate DOM nodes nodes from the given html string. // The generated DOM nodes are returned as an array. // This function can be overriden in plugins for example to make // it compatible with browsers that don't support the DOM fully. zepto.fragment = function(html, name, properties) { var dom, nodes, container // A special case optimization for a single tag if (singleTagRE.test(html)) dom = $(document.createElement(RegExp.$1)) if (!dom) { if (html.replace) html = html.replace(tagExpanderRE, "<$1></$2>") if (name === undefined) name = fragmentRE.test(html) && RegExp.$1 if (!(name in containers)) name = '*' container = containers[name] container.innerHTML = '' + html dom = $.each(slice.call(container.childNodes), function(){ container.removeChild(this) }) } if (isPlainObject(properties)) { nodes = $(dom) $.each(properties, function(key, value) { if (methodAttributes.indexOf(key) > -1) nodes[key](value) else nodes.attr(key, value) }) } return dom } // `$.zepto.Z` swaps out the prototype of the given `dom` array // of nodes with `$.fn` and thus supplying all the Zepto functions // to the array. Note that `__proto__` is not supported on Internet // Explorer. This method can be overriden in plugins. zepto.Z = function(dom, selector) { dom = dom || [] dom.__proto__ = $.fn dom.selector = selector || '' return dom } // `$.zepto.isZ` should return `true` if the given object is a Zepto // collection. This method can be overriden in plugins. zepto.isZ = function(object) { return object instanceof zepto.Z } // `$.zepto.init` is Zepto's counterpart to jQuery's `$.fn.init` and // takes a CSS selector and an optional context (and handles various // special cases). // This method can be overriden in plugins. zepto.init = function(selector, context) { var dom // If nothing given, return an empty Zepto collection if (!selector) return zepto.Z() // Optimize for string selectors else if (typeof selector == 'string') { selector = selector.trim() // If it's a html fragment, create nodes from it // Note: In both Chrome 21 and Firefox 15, DOM error 12 // is thrown if the fragment doesn't begin with < if (selector[0] == '<' && fragmentRE.test(selector)) dom = zepto.fragment(selector, RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // If it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // If a function is given, call it when the DOM is ready else if (isFunction(selector)) return $(document).ready(selector) // If a Zepto collection is given, just return it else if (zepto.isZ(selector)) return selector else { // normalize array if an array of nodes is given if (isArray(selector)) dom = compact(selector) // Wrap DOM nodes. else if (isObject(selector)) dom = [selector], selector = null // If it's a html fragment, create nodes from it else if (fragmentRE.test(selector)) dom = zepto.fragment(selector.trim(), RegExp.$1, context), selector = null // If there's a context, create a collection on that context first, and select // nodes from there else if (context !== undefined) return $(context).find(selector) // And last but no least, if it's a CSS selector, use it to select nodes. else dom = zepto.qsa(document, selector) } // create a new Zepto collection from the nodes found return zepto.Z(dom, selector) } // `$` will be the base `Zepto` object. When calling this // function just call `$.zepto.init, which makes the implementation // details of selecting nodes and creating Zepto collections // patchable in plugins. $ = function(selector, context){ return zepto.init(selector, context) } function extend(target, source, deep) { for (key in source) if (deep && (isPlainObject(source[key]) || isArray(source[key]))) { if (isPlainObject(source[key]) && !isPlainObject(target[key])) target[key] = {} if (isArray(source[key]) && !isArray(target[key])) target[key] = [] extend(target[key], source[key], deep) } else if (source[key] !== undefined) target[key] = source[key] } // Copy all but undefined properties from one or more // objects to the `target` object. $.extend = function(target){ var deep, args = slice.call(arguments, 1) if (typeof target == 'boolean') { deep = target target = args.shift() } args.forEach(function(arg){ extend(target, arg, deep) }) return target } // `$.zepto.qsa` is Zepto's CSS selector implementation which // uses `document.querySelectorAll` and optimizes for some special cases, like `#id`. // This method can be overriden in plugins. zepto.qsa = function(element, selector){ var found, maybeID = selector[0] == '#', maybeClass = !maybeID && selector[0] == '.', nameOnly = maybeID || maybeClass ? selector.slice(1) : selector, // Ensure that a 1 char tag name still gets checked isSimple = simpleSelectorRE.test(nameOnly) return (isDocument(element) && isSimple && maybeID) ? ( (found = element.getElementById(nameOnly)) ? [found] : [] ) : (element.nodeType !== 1 && element.nodeType !== 9) ? [] : slice.call( isSimple && !maybeID ? maybeClass ? element.getElementsByClassName(nameOnly) : // If it's simple, it could be a class element.getElementsByTagName(selector) : // Or a tag element.querySelectorAll(selector) // Or it's not simple, and we need to query all ) } function filtered(nodes, selector) { return selector == null ? $(nodes) : $(nodes).filter(selector) } $.contains = document.documentElement.contains ? function(parent, node) { return parent !== node && parent.contains(node) } : function(parent, node) { while (node && (node = node.parentNode)) if (node === parent) return true return false } function funcArg(context, arg, idx, payload) { return isFunction(arg) ? arg.call(context, idx, payload) : arg } function setAttribute(node, name, value) { value == null ? node.removeAttribute(name) : node.setAttribute(name, value) } // access className property while respecting SVGAnimatedString function className(node, value){ var klass = node.className || '', svg = klass && klass.baseVal !== undefined if (value === undefined) return svg ? klass.baseVal : klass svg ? (klass.baseVal = value) : (node.className = value) } // "true" => true // "false" => false // "null" => null // "42" => 42 // "42.5" => 42.5 // "08" => "08" // JSON => parse if valid // String => self function deserializeValue(value) { try { return value ? value == "true" || ( value == "false" ? false : value == "null" ? null : +value + "" == value ? +value : /^[\[\{]/.test(value) ? $.parseJSON(value) : value ) : value } catch(e) { return value } } $.type = type $.isFunction = isFunction $.isWindow = isWindow $.isArray = isArray $.isPlainObject = isPlainObject $.isEmptyObject = function(obj) { var name for (name in obj) return false return true } $.inArray = function(elem, array, i){ return emptyArray.indexOf.call(array, elem, i) } $.camelCase = camelize $.trim = function(str) { return str == null ? "" : String.prototype.trim.call(str) } // plugin compatibility $.uuid = 0 $.support = { } $.expr = { } $.map = function(elements, callback){ var value, values = [], i, key if (likeArray(elements)) for (i = 0; i < elements.length; i++) { value = callback(elements[i], i) if (value != null) values.push(value) } else for (key in elements) { value = callback(elements[key], key) if (value != null) values.push(value) } return flatten(values) } $.each = function(elements, callback){ var i, key if (likeArray(elements)) { for (i = 0; i < elements.length; i++) if (callback.call(elements[i], i, elements[i]) === false) return elements } else { for (key in elements) if (callback.call(elements[key], key, elements[key]) === false) return elements } return elements } $.grep = function(elements, callback){ return filter.call(elements, callback) } if (window.JSON) $.parseJSON = JSON.parse // Populate the class2type map $.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase() }) // Define methods that will be available on all // Zepto collections $.fn = { // Because a collection acts like an array // copy over these useful array functions. forEach: emptyArray.forEach, reduce: emptyArray.reduce, push: emptyArray.push, sort: emptyArray.sort, indexOf: emptyArray.indexOf, concat: emptyArray.concat, // `map` and `slice` in the jQuery API work differently // from their array counterparts map: function(fn){ return $($.map(this, function(el, i){ return fn.call(el, i, el) })) }, slice: function(){ return $(slice.apply(this, arguments)) }, ready: function(callback){ // need to check if document.body exists for IE as that browser reports // document ready when it hasn't yet created the body element if (readyRE.test(document.readyState) && document.body) callback($) else document.addEventListener('DOMContentLoaded', function(){ callback($) }, false) return this }, get: function(idx){ return idx === undefined ? slice.call(this) : this[idx >= 0 ? idx : idx + this.length] }, toArray: function(){ return this.get() }, size: function(){ return this.length }, remove: function(){ return this.each(function(){ if (this.parentNode != null) this.parentNode.removeChild(this) }) }, each: function(callback){ emptyArray.every.call(this, function(el, idx){ return callback.call(el, idx, el) !== false }) return this }, filter: function(selector){ if (isFunction(selector)) return this.not(this.not(selector)) return $(filter.call(this, function(element){ return zepto.matches(element, selector) })) }, add: function(selector,context){ return $(uniq(this.concat($(selector,context)))) }, is: function(selector){ return this.length > 0 && zepto.matches(this[0], selector) }, not: function(selector){ var nodes=[] if (isFunction(selector) && selector.call !== undefined) this.each(function(idx){ if (!selector.call(this,idx)) nodes.push(this) }) else { var excludes = typeof selector == 'string' ? this.filter(selector) : (likeArray(selector) && isFunction(selector.item)) ? slice.call(selector) : $(selector) this.forEach(function(el){ if (excludes.indexOf(el) < 0) nodes.push(el) }) } return $(nodes) }, has: function(selector){ return this.filter(function(){ return isObject(selector) ? $.contains(this, selector) : $(this).find(selector).size() }) }, eq: function(idx){ return idx === -1 ? this.slice(idx) : this.slice(idx, + idx + 1) }, first: function(){ var el = this[0] return el && !isObject(el) ? el : $(el) }, last: function(){ var el = this[this.length - 1] return el && !isObject(el) ? el : $(el) }, find: function(selector){ var result, $this = this if (!selector) result = $() else if (typeof selector == 'object') result = $(selector).filter(function(){ var node = this return emptyArray.some.call($this, function(parent){ return $.contains(parent, node) }) }) else if (this.length == 1) result = $(zepto.qsa(this[0], selector)) else result = this.map(function(){ return zepto.qsa(this, selector) }) return result }, closest: function(selector, context){ var node = this[0], collection = false if (typeof selector == 'object') collection = $(selector) while (node && !(collection ? collection.indexOf(node) >= 0 : zepto.matches(node, selector))) node = node !== context && !isDocument(node) && node.parentNode return $(node) }, parents: function(selector){ var ancestors = [], nodes = this while (nodes.length > 0) nodes = $.map(nodes, function(node){ if ((node = node.parentNode) && !isDocument(node) && ancestors.indexOf(node) < 0) { ancestors.push(node) return node } }) return filtered(ancestors, selector) }, parent: function(selector){ return filtered(uniq(this.pluck('parentNode')), selector) }, children: function(selector){ return filtered(this.map(function(){ return children(this) }), selector) }, contents: function() { return this.map(function() { return slice.call(this.childNodes) }) }, siblings: function(selector){ return filtered(this.map(function(i, el){ return filter.call(children(el.parentNode), function(child){ return child!==el }) }), selector) }, empty: function(){ return this.each(function(){ this.innerHTML = '' }) }, // `pluck` is borrowed from Prototype.js pluck: function(property){ return $.map(this, function(el){ return el[property] }) }, show: function(){ return this.each(function(){ this.style.display == "none" && (this.style.display = '') if (getComputedStyle(this, '').getPropertyValue("display") == "none") this.style.display = defaultDisplay(this.nodeName) }) }, replaceWith: function(newContent){ return this.before(newContent).remove() }, wrap: function(structure){ var func = isFunction(structure) if (this[0] && !func) var dom = $(structure).get(0), clone = dom.parentNode || this.length > 1 return this.each(function(index){ $(this).wrapAll( func ? structure.call(this, index) : clone ? dom.cloneNode(true) : dom ) }) }, wrapAll: function(structure){ if (this[0]) { $(this[0]).before(structure = $(structure)) var children // drill down to the inmost element while ((children = structure.children()).length) structure = children.first() $(structure).append(this) } return this }, wrapInner: function(structure){ var func = isFunction(structure) return this.each(function(index){ var self = $(this), contents = self.contents(), dom = func ? structure.call(this, index) : structure contents.length ? contents.wrapAll(dom) : self.append(dom) }) }, unwrap: function(){ this.parent().each(function(){ $(this).replaceWith($(this).children()) }) return this }, clone: function(){ return this.map(function(){ return this.cloneNode(true) }) }, hide: function(){ return this.css("display", "none") }, toggle: function(setting){ return this.each(function(){ var el = $(this) ;(setting === undefined ? el.css("display") == "none" : setting) ? el.show() : el.hide() }) }, prev: function(selector){ return $(this.pluck('previousElementSibling')).filter(selector || '*') }, next: function(selector){ return $(this.pluck('nextElementSibling')).filter(selector || '*') }, html: function(html){ return 0 in arguments ? this.each(function(idx){ var originHtml = this.innerHTML $(this).empty().append( funcArg(this, html, idx, originHtml) ) }) : (0 in this ? this[0].innerHTML : null) }, text: function(text){ return 0 in arguments ? this.each(function(idx){ var newText = funcArg(this, text, idx, this.textContent) this.textContent = newText == null ? '' : ''+newText }) : (0 in this ? this[0].textContent : null) }, attr: function(name, value){ var result return (typeof name == 'string' && !(1 in arguments)) ? (!this.length || this[0].nodeType !== 1 ? undefined : (!(result = this[0].getAttribute(name)) && name in this[0]) ? this[0][name] : result ) : this.each(function(idx){ if (this.nodeType !== 1) return if (isObject(name)) for (key in name) setAttribute(this, key, name[key]) else setAttribute(this, name, funcArg(this, value, idx, this.getAttribute(name))) }) }, removeAttr: function(name){ return this.each(function(){ this.nodeType === 1 && name.split(' ').forEach(function(attribute){ setAttribute(this, attribute) }, this)}) }, prop: function(name, value){ name = propMap[name] || name return (1 in arguments) ? this.each(function(idx){ this[name] = funcArg(this, value, idx, this[name]) }) : (this[0] && this[0][name]) }, data: function(name, value){ var attrName = 'data-' + name.replace(capitalRE, '-$1').toLowerCase() var data = (1 in arguments) ? this.attr(attrName, value) : this.attr(attrName) return data !== null ? deserializeValue(data) : undefined }, val: function(value){ return 0 in arguments ? this.each(function(idx){ this.value = funcArg(this, value, idx, this.value) }) : (this[0] && (this[0].multiple ? $(this[0]).find('option').filter(function(){ return this.selected }).pluck('value') : this[0].value) ) }, offset: function(coordinates){ if (coordinates) return this.each(function(index){ var $this = $(this), coords = funcArg(this, coordinates, index, $this.offset()), parentOffset = $this.offsetParent().offset(), props = { top: coords.top - parentOffset.top, left: coords.left - parentOffset.left } if ($this.css('position') == 'static') props['position'] = 'relative' $this.css(props) }) if (!this.length) return null var obj = this[0].getBoundingClientRect() return { left: obj.left + window.pageXOffset, top: obj.top + window.pageYOffset, width: Math.round(obj.width), height: Math.round(obj.height) } }, css: function(property, value){ if (arguments.length < 2) { var computedStyle, element = this[0] if(!element) return computedStyle = getComputedStyle(element, '') if (typeof property == 'string') return element.style[camelize(property)] || computedStyle.getPropertyValue(property) else if (isArray(property)) { var props = {} $.each(property, function(_, prop){ props[prop] = (element.style[camelize(prop)] || computedStyle.getPropertyValue(prop)) }) return props } } var css = '' if (type(property) == 'string') { if (!value && value !== 0) this.each(function(){ this.style.removeProperty(dasherize(property)) }) else css = dasherize(property) + ":" + maybeAddPx(property, value) } else { for (key in property) if (!property[key] && property[key] !== 0) this.each(function(){ this.style.removeProperty(dasherize(key)) }) else css += dasherize(key) + ':' + maybeAddPx(key, property[key]) + ';' } return this.each(function(){ this.style.cssText += ';' + css }) }, index: function(element){ return element ? this.indexOf($(element)[0]) : this.parent().children().indexOf(this[0]) }, hasClass: function(name){ if (!name) return false return emptyArray.some.call(this, function(el){ return this.test(className(el)) }, classRE(name)) }, addClass: function(name){ if (!name) return this return this.each(function(idx){ if (!('className' in this)) return classList = [] var cls = className(this), newName = funcArg(this, name, idx, cls) newName.split(/\s+/g).forEach(function(klass){ if (!$(this).hasClass(klass)) classList.push(klass) }, this) classList.length && className(this, cls + (cls ? " " : "") + classList.join(" ")) }) }, removeClass: function(name){ return this.each(function(idx){ if (!('className' in this)) return if (name === undefined) return className(this, '') classList = className(this) funcArg(this, name, idx, classList).split(/\s+/g).forEach(function(klass){ classList = classList.replace(classRE(klass), " ") }) className(this, classList.trim()) }) }, toggleClass: function(name, when){ if (!name) return this return this.each(function(idx){ var $this = $(this), names = funcArg(this, name, idx, className(this)) names.split(/\s+/g).forEach(function(klass){ (when === undefined ? !$this.hasClass(klass) : when) ? $this.addClass(klass) : $this.removeClass(klass) }) }) }, scrollTop: function(value){ if (!this.length) return var hasScrollTop = 'scrollTop' in this[0] if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset return this.each(hasScrollTop ? function(){ this.scrollTop = value } : function(){ this.scrollTo(this.scrollX, value) }) }, scrollLeft: function(value){ if (!this.length) return var hasScrollLeft = 'scrollLeft' in this[0] if (value === undefined) return hasScrollLeft ? this[0].scrollLeft : this[0].pageXOffset return this.each(hasScrollLeft ? function(){ this.scrollLeft = value } : function(){ this.scrollTo(value, this.scrollY) }) }, position: function() { if (!this.length) return var elem = this[0], // Get *real* offsetParent offsetParent = this.offsetParent(), // Get correct offsets offset = this.offset(), parentOffset = rootNodeRE.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset() // Subtract element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 offset.top -= parseFloat( $(elem).css('margin-top') ) || 0 offset.left -= parseFloat( $(elem).css('margin-left') ) || 0 // Add offsetParent borders parentOffset.top += parseFloat( $(offsetParent[0]).css('border-top-width') ) || 0 parentOffset.left += parseFloat( $(offsetParent[0]).css('border-left-width') ) || 0 // Subtract the two offsets return { top: offset.top - parentOffset.top, left: offset.left - parentOffset.left } }, offsetParent: function() { return this.map(function(){ var parent = this.offsetParent || document.body while (parent && !rootNodeRE.test(parent.nodeName) && $(parent).css("position") == "static") parent = parent.offsetParent return parent }) } } // for now $.fn.detach = $.fn.remove // Generate the `width` and `height` functions ;['width', 'height'].forEach(function(dimension){ var dimensionProperty = dimension.replace(/./, function(m){ return m[0].toUpperCase() }) $.fn[dimension] = function(value){ var offset, el = this[0] if (value === undefined) return isWindow(el) ? el['inner' + dimensionProperty] : isDocument(el) ? el.documentElement['scroll' + dimensionProperty] : (offset = this.offset()) && offset[dimension] else return this.each(function(idx){ el = $(this) el.css(dimension, funcArg(this, value, idx, el[dimension]())) }) } }) function traverseNode(node, fun) { fun(node) for (var i = 0, len = node.childNodes.length; i < len; i++) traverseNode(node.childNodes[i], fun) } // Generate the `after`, `prepend`, `before`, `append`, // `insertAfter`, `insertBefore`, `appendTo`, and `prependTo` methods. adjacencyOperators.forEach(function(operator, operatorIndex) { var inside = operatorIndex % 2 //=> prepend, append $.fn[operator] = function(){ // arguments can be nodes, arrays of nodes, Zepto objects and HTML strings var argType, nodes = $.map(arguments, function(arg) { argType = type(arg) return argType == "object" || argType == "array" || arg == null ? arg : zepto.fragment(arg) }), parent, copyByClone = this.length > 1 if (nodes.length < 1) return this return this.each(function(_, target){ parent = inside ? target : target.parentNode // convert all methods to a "before" operation target = operatorIndex == 0 ? target.nextSibling : operatorIndex == 1 ? target.firstChild : operatorIndex == 2 ? target : null var parentInDocument = $.contains(document.documentElement, parent) nodes.forEach(function(node){ if (copyByClone) node = node.cloneNode(true) else if (!parent) return $(node).remove() parent.insertBefore(node, target) if (parentInDocument) traverseNode(node, function(el){ if (el.nodeName != null && el.nodeName.toUpperCase() === 'SCRIPT' && (!el.type || el.type === 'text/javascript') && !el.src) window['eval'].call(window, el.innerHTML) }) }) }) } // after => insertAfter // prepend => prependTo // before => insertBefore // append => appendTo $.fn[inside ? operator+'To' : 'insert'+(operatorIndex ? 'Before' : 'After')] = function(html){ $(html)[operator](this) return this } }) zepto.Z.prototype = $.fn // Export internal API functions in the `$.zepto` namespace zepto.uniq = uniq zepto.deserializeValue = deserializeValue $.zepto = zepto return $ })() window.Zepto = Zepto window.$ === undefined && (window.$ = Zepto) ;(function($){ var _zid = 1, undefined, slice = Array.prototype.slice, isFunction = $.isFunction, isString = function(obj){ return typeof obj == 'string' }, handlers = {}, specialEvents={}, focusinSupported = 'onfocusin' in window, focus = { focus: 'focusin', blur: 'focusout' }, hover = { mouseenter: 'mouseover', mouseleave: 'mouseout' } specialEvents.click = specialEvents.mousedown = specialEvents.mouseup = specialEvents.mousemove = 'MouseEvents' function zid(element) { return element._zid || (element._zid = _zid++) } function findHandlers(element, event, fn, selector) { event = parse(event) if (event.ns) var matcher = matcherFor(event.ns) return (handlers[zid(element)] || []).filter(function(handler) { return handler && (!event.e || handler.e == event.e) && (!event.ns || matcher.test(handler.ns)) && (!fn || zid(handler.fn) === zid(fn)) && (!selector || handler.sel == selector) }) } function parse(event) { var parts = ('' + event).split('.') return {e: parts[0], ns: parts.slice(1).sort().join(' ')} } function matcherFor(ns) { return new RegExp('(?:^| )' + ns.replace(' ', ' .* ?') + '(?: |$)') } function eventCapture(handler, captureSetting) { return handler.del && (!focusinSupported && (handler.e in focus)) || !!captureSetting } function realEvent(type) { return hover[type] || (focusinSupported && focus[type]) || type } function add(element, events, fn, data, selector, delegator, capture){ var id = zid(element), set = (handlers[id] || (handlers[id] = [])) events.split(/\s/).forEach(function(event){ if (event == 'ready') return $(document).ready(fn) var handler = parse(event) handler.fn = fn handler.sel = selector // emulate mouseenter, mouseleave if (handler.e in hover) fn = function(e){ var related = e.relatedTarget if (!related || (related !== this && !$.contains(this, related))) return handler.fn.apply(this, arguments) } handler.del = delegator var callback = delegator || fn handler.proxy = function(e){ e = compatible(e) if (e.isImmediatePropagationStopped()) return e.data = data var result = callback.apply(element, e._args == undefined ? [e] : [e].concat(e._args)) if (result === false) e.preventDefault(), e.stopPropagation() return result } handler.i = set.length set.push(handler) if ('addEventListener' in element) element.addEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) } function remove(element, events, fn, selector, capture){ var id = zid(element) ;(events || '').split(/\s/).forEach(function(event){ findHandlers(element, event, fn, selector).forEach(function(handler){ delete handlers[id][handler.i] if ('removeEventListener' in element) element.removeEventListener(realEvent(handler.e), handler.proxy, eventCapture(handler, capture)) }) }) } $.event = { add: add, remove: remove } $.proxy = function(fn, context) { var args = (2 in arguments) && slice.call(arguments, 2) if (isFunction(fn)) { var proxyFn = function(){ return fn.apply(context, args ? args.concat(slice.call(arguments)) : arguments) } proxyFn._zid = zid(fn) return proxyFn } else if (isString(context)) { if (args) { args.unshift(fn[context], fn) return $.proxy.apply(null, args) } else { return $.proxy(fn[context], fn) } } else { throw new TypeError("expected function") } } $.fn.bind = function(event, data, callback){ return this.on(event, data, callback) } $.fn.unbind = function(event, callback){ return this.off(event, callback) } $.fn.one = function(event, selector, data, callback){ return this.on(event, selector, data, callback, 1) } var returnTrue = function(){return true}, returnFalse = function(){return false}, ignoreProperties = /^([A-Z]|returnValue$|layer[XY]$)/, eventMethods = { preventDefault: 'isDefaultPrevented', stopImmediatePropagation: 'isImmediatePropagationStopped', stopPropagation: 'isPropagationStopped' } function compatible(event, source) { if (source || !event.isDefaultPrevented) { source || (source = event) $.each(eventMethods, function(name, predicate) { var sourceMethod = source[name] event[name] = function(){ this[predicate] = returnTrue return sourceMethod && sourceMethod.apply(source, arguments) } event[predicate] = returnFalse }) if (source.defaultPrevented !== undefined ? source.defaultPrevented : 'returnValue' in source ? source.returnValue === false : source.getPreventDefault && source.getPreventDefault()) event.isDefaultPrevented = returnTrue } return event } function createProxy(event) { var key, proxy = { originalEvent: event } for (key in event) if (!ignoreProperties.test(key) && event[key] !== undefined) proxy[key] = event[key] return compatible(proxy, event) } $.fn.delegate = function(selector, event, callback){ return this.on(event, selector, callback) } $.fn.undelegate = function(selector, event, callback){ return this.off(event, selector, callback) } $.fn.live = function(event, callback){ $(document.body).delegate(this.selector, event, callback) return this } $.fn.die = function(event, callback){ $(document.body).undelegate(this.selector, event, callback) return this } $.fn.on = function(event, selector, data, callback, one){ var autoRemove, delegator, $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.on(type, selector, data, fn, one) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = data, data = selector, selector = undefined if (isFunction(data) || data === false) callback = data, data = undefined if (callback === false) callback = returnFalse return $this.each(function(_, element){ if (one) autoRemove = function(e){ remove(element, e.type, callback) return callback.apply(this, arguments) } if (selector) delegator = function(e){ var evt, match = $(e.target).closest(selector, element).get(0) if (match && match !== element) { evt = $.extend(createProxy(e), {currentTarget: match, liveFired: element}) return (autoRemove || callback).apply(match, [evt].concat(slice.call(arguments, 1))) } } add(element, event, callback, data, selector, delegator || autoRemove) }) } $.fn.off = function(event, selector, callback){ var $this = this if (event && !isString(event)) { $.each(event, function(type, fn){ $this.off(type, selector, fn) }) return $this } if (!isString(selector) && !isFunction(callback) && callback !== false) callback = selector, selector = undefined if (callback === false) callback = returnFalse return $this.each(function(){ remove(this, event, callback, selector) }) } $.fn.trigger = function(event, args){ event = (isString(event) || $.isPlainObject(event)) ? $.Event(event) : compatible(event) event._args = args return this.each(function(){ // handle focus(), blur() by calling them directly if (event.type in focus && typeof this[event.type] == "function") this[event.type]() // items in the collection might not be DOM elements else if ('dispatchEvent' in this) this.dispatchEvent(event) else $(this).triggerHandler(event, args) }) } // triggers event handlers on current element just as if an event occurred, // doesn't trigger an actual event, doesn't bubble $.fn.triggerHandler = function(event, args){ var e, result this.each(function(i, element){ e = createProxy(isString(event) ? $.Event(event) : event) e._args = args e.target = element $.each(findHandlers(element, event.type || event), function(i, handler){ result = handler.proxy(e) if (e.isImmediatePropagationStopped()) return false }) }) return result } // shortcut methods for `.bind(event, fn)` for each event type ;('focusin focusout focus blur load resize scroll unload click dblclick '+ 'mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave '+ 'change select keydown keypress keyup error').split(' ').forEach(function(event) { $.fn[event] = function(callback) { return (0 in arguments) ? this.bind(event, callback) : this.trigger(event) } }) $.Event = function(type, props) { if (!isString(type)) props = type, type = props.type var event = document.createEvent(specialEvents[type] || 'Events'), bubbles = true if (props) for (var name in props) (name == 'bubbles') ? (bubbles = !!props[name]) : (event[name] = props[name]) event.initEvent(type, bubbles, true) return compatible(event) } })(Zepto) ;(function($){ var jsonpID = 0, document = window.document, key, name, rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, scriptTypeRE = /^(?:text|application)\/javascript/i, xmlTypeRE = /^(?:text|application)\/xml/i, jsonType = 'application/json', htmlType = 'text/html', blankRE = /^\s*$/, originAnchor = document.createElement('a') originAnchor.href = window.location.href // trigger a custom event and return false if it was cancelled function triggerAndReturn(context, eventName, data) { var event = $.Event(eventName) $(context).trigger(event, data) return !event.isDefaultPrevented() } // trigger an Ajax "global" event function triggerGlobal(settings, context, eventName, data) { if (settings.global) return triggerAndReturn(context || document, eventName, data) } // Number of active Ajax requests $.active = 0 function ajaxStart(settings) { if (settings.global && $.active++ === 0) triggerGlobal(settings, null, 'ajaxStart') } function ajaxStop(settings) { if (settings.global && !(--$.active)) triggerGlobal(settings, null, 'ajaxStop') } // triggers an extra global event "ajaxBeforeSend" that's like "ajaxSend" but cancelable function ajaxBeforeSend(xhr, settings) { var context = settings.context if (settings.beforeSend.call(context, xhr, settings) === false || triggerGlobal(settings, context, 'ajaxBeforeSend', [xhr, settings]) === false) return false triggerGlobal(settings, context, 'ajaxSend', [xhr, settings]) } function ajaxSuccess(data, xhr, settings, deferred) { var context = settings.context, status = 'success' settings.success.call(context, data, status, xhr) if (deferred) deferred.resolveWith(context, [data, status, xhr]) triggerGlobal(settings, context, 'ajaxSuccess', [xhr, settings, data]) ajaxComplete(status, xhr, settings) } // type: "timeout", "error", "abort", "parsererror" function ajaxError(error, type, xhr, settings, deferred) { var context = settings.context settings.error.call(context, xhr, type, error) if (deferred) deferred.rejectWith(context, [xhr, type, error]) triggerGlobal(settings, context, 'ajaxError', [xhr, settings, error || type]) ajaxComplete(type, xhr, settings) } // status: "success", "notmodified", "error", "timeout", "abort", "parsererror" function ajaxComplete(status, xhr, settings) { var context = settings.context settings.complete.call(context, xhr, status) triggerGlobal(settings, context, 'ajaxComplete', [xhr, settings]) ajaxStop(settings) } // Empty function, used as default callback function empty() {} $.ajaxJSONP = function(options, deferred){ if (!('type' in options)) return $.ajax(options) var _callbackName = options.jsonpCallback, callbackName = ($.isFunction(_callbackName) ? _callbackName() : _callbackName) || ('jsonp' + (++jsonpID)), script = document.createElement('script'), originalCallback = window[callbackName], responseData, abort = function(errorType) { $(script).triggerHandler('error', errorType || 'abort') }, xhr = { abort: abort }, abortTimeout if (deferred) deferred.promise(xhr) $(script).on('load error', function(e, errorType){ clearTimeout(abortTimeout) $(script).off().remove() if (e.type == 'error' || !responseData) { ajaxError(null, errorType || 'error', xhr, options, deferred) } else { ajaxSuccess(responseData[0], xhr, options, deferred) } window[callbackName] = originalCallback if (responseData && $.isFunction(originalCallback)) originalCallback(responseData[0]) originalCallback = responseData = undefined }) if (ajaxBeforeSend(xhr, options) === false) { abort('abort') return xhr } window[callbackName] = function(){ responseData = arguments } script.src = options.url.replace(/\?(.+)=\?/, '?$1=' + callbackName) document.head.appendChild(script) if (options.timeout > 0) abortTimeout = setTimeout(function(){ abort('timeout') }, options.timeout) return xhr } $.ajaxSettings = { // Default type of request type: 'GET', // Callback that is executed before request beforeSend: empty, // Callback that is executed if the request succeeds success: empty, // Callback that is executed the the server drops error error: empty, // Callback that is executed on request complete (both: error and success) complete: empty, // The context for the callbacks context: null, // Whether to trigger "global" Ajax events global: true, // Transport xhr: function () { return new window.XMLHttpRequest() }, // MIME types mapping // IIS returns Javascript as "application/x-javascript" accepts: { script: 'text/javascript, application/javascript, application/x-javascript', json: jsonType, xml: 'application/xml, text/xml', html: htmlType, text: 'text/plain' }, // Whether the request is to another domain crossDomain: false, // Default timeout timeout: 0, // Whether data should be serialized to string processData: true, // Whether the browser should be allowed to cache GET responses cache: true } function mimeToDataType(mime) { if (mime) mime = mime.split(';', 2)[0] return mime && ( mime == htmlType ? 'html' : mime == jsonType ? 'json' : scriptTypeRE.test(mime) ? 'script' : xmlTypeRE.test(mime) && 'xml' ) || 'text' } function appendQuery(url, query) { if (query == '') return url return (url + '&' + query).replace(/[&?]{1,2}/, '?') } // serialize payload and append it to the URL for GET requests function serializeData(options) { if (options.processData && options.data && $.type(options.data) != "string") options.data = $.param(options.data, options.traditional) if (options.data && (!options.type || options.type.toUpperCase() == 'GET')) options.url = appendQuery(options.url, options.data), options.data = undefined } $.ajax = function(options){ var settings = $.extend({}, options || {}), deferred = $.Deferred && $.Deferred(), urlAnchor for (key in $.ajaxSettings) if (settings[key] === undefined) settings[key] = $.ajaxSettings[key] ajaxStart(settings) if (!settings.crossDomain) { urlAnchor = document.createElement('a') urlAnchor.href = settings.url urlAnchor.href = urlAnchor.href settings.crossDomain = (originAnchor.protocol + '//' + originAnchor.host) !== (urlAnchor.protocol + '//' + urlAnchor.host) } if (!settings.url) settings.url = window.location.toString() serializeData(settings) var dataType = settings.dataType, hasPlaceholder = /\?.+=\?/.test(settings.url) if (hasPlaceholder) dataType = 'jsonp' if (settings.cache === false || ( (!options || options.cache !== true) && ('script' == dataType || 'jsonp' == dataType) )) settings.url = appendQuery(settings.url, '_=' + Date.now()) if ('jsonp' == dataType) { if (!hasPlaceholder) settings.url = appendQuery(settings.url, settings.jsonp ? (settings.jsonp + '=?') : settings.jsonp === false ? '' : 'callback=?') return $.ajaxJSONP(settings, deferred) } var mime = settings.accepts[dataType], headers = { }, setHeader = function(name, value) { headers[name.toLowerCase()] = [name, value] }, protocol = /^([\w-]+:)\/\//.test(settings.url) ? RegExp.$1 : window.location.protocol, xhr = settings.xhr(), nativeSetHeader = xhr.setRequestHeader, abortTimeout if (deferred) deferred.promise(xhr) if (!settings.crossDomain) setHeader('X-Requested-With', 'XMLHttpRequest') setHeader('Accept', mime || '*/*') if (mime = settings.mimeType || mime) { if (mime.indexOf(',') > -1) mime = mime.split(',', 2)[0] xhr.overrideMimeType && xhr.overrideMimeType(mime) } if (settings.contentType || (settings.contentType !== false && settings.data && settings.type.toUpperCase() != 'GET')) setHeader('Content-Type', settings.contentType || 'application/x-www-form-urlencoded') if (settings.headers) for (name in settings.headers) setHeader(name, settings.headers[name]) xhr.setRequestHeader = setHeader xhr.onreadystatechange = function(){ if (xhr.readyState == 4) { xhr.onreadystatechange = empty clearTimeout(abortTimeout) var result, error = false if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304 || (xhr.status == 0 && protocol == 'file:')) { dataType = dataType || mimeToDataType(settings.mimeType || xhr.getResponseHeader('content-type')) result = xhr.responseText try { // http://perfectionkills.com/global-eval-what-are-the-options/ if (dataType == 'script') (1,eval)(result) else if (dataType == 'xml') result = xhr.responseXML else if (dataType == 'json') result = blankRE.test(result) ? null : $.parseJSON(result) } catch (e) { error = e } if (error) ajaxError(error, 'parsererror', xhr, settings, deferred) else ajaxSuccess(result, xhr, settings, deferred) } else { ajaxError(xhr.statusText || null, xhr.status ? 'error' : 'abort', xhr, settings, deferred) } } } if (ajaxBeforeSend(xhr, settings) === false) { xhr.abort() ajaxError(null, 'abort', xhr, settings, deferred) return xhr } if (settings.xhrFields) for (name in settings.xhrFields) xhr[name] = settings.xhrFields[name] var async = 'async' in settings ? settings.async : true xhr.open(settings.type, settings.url, async, settings.username, settings.password) for (name in headers) nativeSetHeader.apply(xhr, headers[name]) if (settings.timeout > 0) abortTimeout = setTimeout(function(){ xhr.onreadystatechange = empty xhr.abort() ajaxError(null, 'timeout', xhr, settings, deferred) }, settings.timeout) // avoid sending empty string (#319) xhr.send(settings.data ? settings.data : null) return xhr } // handle optional data/success arguments function parseArguments(url, data, success, dataType) { if ($.isFunction(data)) dataType = success, success = data, data = undefined if (!$.isFunction(success)) dataType = success, success = undefined return { url: url , data: data , success: success , dataType: dataType } } $.get = function(/* url, data, success, dataType */){ return $.ajax(parseArguments.apply(null, arguments)) } $.post = function(/* url, data, success, dataType */){ var options = parseArguments.apply(null, arguments) options.type = 'POST' return $.ajax(options) } $.getJSON = function(/* url, data, success */){ var options = parseArguments.apply(null, arguments) options.dataType = 'json' return $.ajax(options) } $.fn.load = function(url, data, success){ if (!this.length) return this var self = this, parts = url.split(/\s/), selector, options = parseArguments(url, data, success), callback = options.success if (parts.length > 1) options.url = parts[0], selector = parts[1] options.success = function(response){ self.html(selector ? $('<div>').html(response.replace(rscript, "")).find(selector) : response) callback && callback.apply(self, arguments) } $.ajax(options) return this } var escape = encodeURIComponent function serialize(params, obj, traditional, scope){ var type, array = $.isArray(obj), hash = $.isPlainObject(obj) $.each(obj, function(key, value) { type = $.type(value) if (scope) key = traditional ? scope : scope + '[' + (hash || type == 'object' || type == 'array' ? key : '') + ']' // handle data in serializeArray() format if (!scope && array) params.add(value.name, value.value) // recurse into nested objects else if (type == "array" || (!traditional && type == "object")) serialize(params, value, traditional, key) else params.add(key, value) }) } $.param = function(obj, traditional){ var params = [] params.add = function(key, value) { if ($.isFunction(value)) value = value() if (value == null) value = "" this.push(escape(key) + '=' + escape(value)) } serialize(params, obj, traditional) return params.join('&').replace(/%20/g, '+') } })(Zepto) ;(function($){ $.fn.serializeArray = function() { var name, type, result = [], add = function(value) { if (value.forEach) return value.forEach(add) result.push({ name: name, value: value }) } if (this[0]) $.each(this[0].elements, function(_, field){ type = field.type, name = field.name if (name && field.nodeName.toLowerCase() != 'fieldset' && !field.disabled && type != 'submit' && type != 'reset' && type != 'button' && type != 'file' && ((type != 'radio' && type != 'checkbox') || field.checked)) add($(field).val()) }) return result } $.fn.serialize = function(){ var result = [] this.serializeArray().forEach(function(elm){ result.push(encodeURIComponent(elm.name) + '=' + encodeURIComponent(elm.value)) }) return result.join('&') } $.fn.submit = function(callback) { if (0 in arguments) this.bind('submit', callback) else if (this.length) { var event = $.Event('submit') this.eq(0).trigger(event) if (!event.isDefaultPrevented()) this.get(0).submit() } return this } })(Zepto) ;(function($){ // __proto__ doesn't exist on IE<11, so redefine // the Z function to use object extension instead if (!('__proto__' in {})) { $.extend($.zepto, { Z: function(dom, selector){ dom = dom || [] $.extend(dom, $.fn) dom.selector = selector || '' dom.__Z = true return dom }, // this is a kludge but works isZ: function(object){ return $.type(object) === 'array' && '__Z' in object } }) } // getComputedStyle shouldn't freak out when called // without a valid element as argument try { getComputedStyle(undefined) } catch(e) { var nativeGetComputedStyle = getComputedStyle; window.getComputedStyle = function(element){ try { return nativeGetComputedStyle(element) } catch(e) { return null } } } })(Zepto) ; if (typeof exports === "object") { module.exports = Zepto; } },{}],3:[function(require,module,exports){ // Zepto.js // (c) 2010-2014 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. // The following code is heavily inspired by jQuery's $.fn.data() ;(function($){ var data = {}, dataAttr = $.fn.data, camelize = $.camelCase, exp = $.expando = 'Zepto' + (+new Date()), emptyArray = [] // Get value from node: // 1. first try key as given, // 2. then try camelized key, // 3. fall back to reading "data-*" attribute. function getData(node, name) { var id = node[exp], store = id && data[id] if (name === undefined) return store || setData(node) else { if (store) { if (name in store) return store[name] var camelName = camelize(name) if (camelName in store) return store[camelName] } return dataAttr.call($(node), name) } } // Store value under camelized key on node function setData(node, name, value) { var id = node[exp] || (node[exp] = ++$.uuid), store = data[id] || (data[id] = attributeData(node)) if (name !== undefined) store[camelize(name)] = value return store } // Read all "data-*" attributes from a node function attributeData(node) { var store = {} $.each(node.attributes || emptyArray, function(i, attr){ if (attr.name.indexOf('data-') == 0) store[camelize(attr.name.replace('data-', ''))] = $.zepto.deserializeValue(attr.value) }) return store } $.fn.data = function(name, value) { return value === undefined ? // set multiple values via object $.isPlainObject(name) ? this.each(function(i, node){ $.each(name, function(key, value){ setData(node, key, value) }) }) : // get value from first element (0 in this ? getData(this[0], name) : undefined) : // set value on all elements this.each(function(){ setData(this, name, value) }) } $.fn.removeData = function(names) { if (typeof names == 'string') names = names.split(/\s+/) return this.each(function(){ var id = this[exp], store = id && data[id] if (store) $.each(names || store, function(key){ delete store[names ? camelize(this) : key] }) }) } // Generate extended `remove` and `empty` functions ;['remove', 'empty'].forEach(function(methodName){ var origFn = $.fn[methodName] $.fn[methodName] = function() { var elements = this.find('*') if (methodName === 'remove') elements = elements.add(this) elements.removeData() return origFn.call(this) } }) })(Zepto) },{}],4:[function(require,module,exports){ 'use strict'; var _ = require('../common/utils.js'); var css = { wrapper: { position: 'relative', display: 'inline-block' }, hint: { position: 'absolute', top: '0', left: '0', borderColor: 'transparent', boxShadow: 'none', // #741: fix hint opacity issue on iOS opacity: '1' }, input: { position: 'relative', verticalAlign: 'top', backgroundColor: 'transparent' }, inputWithNoHint: { position: 'relative', verticalAlign: 'top' }, dropdown: { position: 'absolute', top: '100%', left: '0', zIndex: '100', display: 'none' }, suggestions: { display: 'block' }, suggestion: { whiteSpace: 'nowrap', cursor: 'pointer' }, suggestionChild: { whiteSpace: 'normal' }, ltr: { left: '0', right: 'auto' }, rtl: { left: 'auto', right: '0' } }; // ie specific styling if (_.isMsie()) { // ie6-8 (and 9?) doesn't fire hover and click events for elements with // transparent backgrounds, for a workaround, use 1x1 transparent gif _.mixin(css.input, { backgroundImage: 'url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)' }); } // ie7 and under specific styling if (_.isMsie() && _.isMsie() <= 7) { // if someone can tell me why this is necessary to align // the hint with the query in ie7, i'll send you $5 - @JakeHarding _.mixin(css.input, {marginTop: '-1px'}); } module.exports = css; },{"../common/utils.js":13}],5:[function(require,module,exports){ 'use strict'; var datasetKey = 'aaDataset'; var valueKey = 'aaValue'; var datumKey = 'aaDatum'; var _ = require('../common/utils.js'); var DOM = require('../common/dom.js'); var html = require('./html.js'); var css = require('./css.js'); var EventEmitter = require('./event_emitter.js'); // constructor // ----------- function Dataset(o) { o = o || {}; o.templates = o.templates || {}; if (!o.source) { _.error('missing source'); } if (o.name && !isValidName(o.name)) { _.error('invalid dataset name: ' + o.name); } // tracks the last query the dataset was updated for this.query = null; this.highlight = !!o.highlight; this.name = o.name || _.getUniqueId(); this.source = o.source; this.displayFn = getDisplayFn(o.display || o.displayKey); this.templates = getTemplates(o.templates, this.displayFn); this.$el = o.$menu && this.name && o.$menu.find('.aa-dataset-' + this.name).length > 0 ? DOM.element(o.$menu.find('.aa-dataset-' + this.name)[0]) : DOM.element(html.dataset.replace('%CLASS%', this.name)); this.$menu = o.$menu; } // static methods // -------------- Dataset.extractDatasetName = function extractDatasetName(el) { return DOM.element(el).data(datasetKey); }; Dataset.extractValue = function extractDatum(el) { return DOM.element(el).data(valueKey); }; Dataset.extractDatum = function extractDatum(el) { return DOM.element(el).data(datumKey); }; // instance methods // ---------------- _.mixin(Dataset.prototype, EventEmitter, { // ### private _render: function render(query, suggestions) { if (!this.$el) { return; } var that = this; var hasSuggestions; var renderArgs = [].slice.call(arguments, 2); this.$el.empty(); hasSuggestions = suggestions && suggestions.length; if (!hasSuggestions && this.templates.empty) { this.$el .html(getEmptyHtml.apply(this, renderArgs)) .prepend(that.templates.header ? getHeaderHtml.apply(this, renderArgs) : null) .append(that.templates.footer ? getFooterHtml.apply(this, renderArgs) : null); } else if (hasSuggestions) { this.$el .html(getSuggestionsHtml.apply(this, renderArgs)) .prepend(that.templates.header ? getHeaderHtml.apply(this, renderArgs) : null) .append(that.templates.footer ? getFooterHtml.apply(this, renderArgs) : null); } if (this.$menu) { this.$menu.addClass('aa-' + (hasSuggestions ? 'with' : 'without') + '-' + this.name) .removeClass('aa-' + (hasSuggestions ? 'without' : 'with') + '-' + this.name); } this.trigger('rendered'); function getEmptyHtml() { var args = [].slice.call(arguments, 0); args = [{query: query, isEmpty: true}].concat(args); return that.templates.empty.apply(this, args); } function getSuggestionsHtml() { var args = [].slice.call(arguments, 0); var $suggestions; var nodes; $suggestions = DOM.element(html.suggestions).css(css.suggestions); // jQuery#append doesn't support arrays as the first argument // until version 1.8, see http://bugs.jquery.com/ticket/11231 nodes = _.map(suggestions, getSuggestionNode); $suggestions.append.apply($suggestions, nodes); return $suggestions; function getSuggestionNode(suggestion) { var $el; $el = DOM.element(html.suggestion) .append(that.templates.suggestion.apply(this, [suggestion].concat(args))) .data(datasetKey, that.name) .data(valueKey, that.displayFn(suggestion) || null) .data(datumKey, suggestion); $el.children().each(function() { DOM.element(this).css(css.suggestionChild); }); return $el; } } function getHeaderHtml() { var args = [].slice.call(arguments, 0); args = [{query: query, isEmpty: !hasSuggestions}].concat(args); return that.templates.header.apply(this, args); } function getFooterHtml() { var args = [].slice.call(arguments, 0); args = [{query: query, isEmpty: !hasSuggestions}].concat(args); return that.templates.footer.apply(this, args); } }, // ### public getRoot: function getRoot() { return this.$el; }, update: function update(query) { var that = this; this.query = query; this.canceled = false; this.source(query, render); function render(suggestions) { // if the update has been canceled or if the query has changed // do not render the suggestions as they've become outdated if (!that.canceled && query === that.query) { // concat all the other arguments that could have been passed // to the render function, and forward them to _render var args = [].slice.call(arguments, 1); args = [query, suggestions].concat(args); that._render.apply(that, args); } } }, cancel: function cancel() { this.canceled = true; }, clear: function clear() { this.cancel(); this.$el.empty(); this.trigger('rendered'); }, isEmpty: function isEmpty() { return this.$el.is(':empty'); }, destroy: function destroy() { this.$el = null; } }); // helper functions // ---------------- function getDisplayFn(display) { display = display || 'value'; return _.isFunction(display) ? display : displayFn; function displayFn(obj) { return obj[display]; } } function getTemplates(templates, displayFn) { return { empty: templates.empty && _.templatify(templates.empty), header: templates.header && _.templatify(templates.header), footer: templates.footer && _.templatify(templates.footer), suggestion: templates.suggestion || suggestionTemplate }; function suggestionTemplate(context) { return '<p>' + displayFn(context) + '</p>'; } } function isValidName(str) { // dashes, underscores, letters, and numbers return (/^[_a-zA-Z0-9-]+$/).test(str); } module.exports = Dataset; },{"../common/dom.js":12,"../common/utils.js":13,"./css.js":4,"./event_emitter.js":8,"./html.js":9}],6:[function(require,module,exports){ 'use strict'; var _ = require('../common/utils.js'); var DOM = require('../common/dom.js'); var EventEmitter = require('./event_emitter.js'); var Dataset = require('./dataset.js'); var css = require('./css.js'); // constructor // ----------- function Dropdown(o) { var that = this; var onSuggestionClick; var onSuggestionMouseEnter; var onSuggestionMouseLeave; o = o || {}; if (!o.menu) { _.error('menu is required'); } if (!_.isArray(o.datasets) && !_.isObject(o.datasets)) { _.error('1 or more datasets required'); } if (!o.datasets) { _.error('datasets is required'); } this.isOpen = false; this.isEmpty = true; // bound functions onSuggestionClick = _.bind(this._onSuggestionClick, this); onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this); onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this); this.$menu = DOM.element(o.menu) .on('click.aa', '.aa-suggestion', onSuggestionClick) .on('mouseenter.aa', '.aa-suggestion', onSuggestionMouseEnter) .on('mouseleave.aa', '.aa-suggestion', onSuggestionMouseLeave); if (o.templates && o.templates.header) { this.$menu.prepend(_.templatify(o.templates.header)); } this.datasets = _.map(o.datasets, function(oDataset) { return initializeDataset(that.$menu, oDataset); }); _.each(this.datasets, function(dataset) { var root = dataset.getRoot(); if (root && root.parent().length === 0) { that.$menu.append(root); } dataset.onSync('rendered', that._onRendered, that); }); if (o.templates && o.templates.footer) { this.$menu.append(_.templatify(o.templates.footer)); } } // instance methods // ---------------- _.mixin(Dropdown.prototype, EventEmitter, { // ### private _onSuggestionClick: function onSuggestionClick($e) { this.trigger('suggestionClicked', DOM.element($e.currentTarget)); }, _onSuggestionMouseEnter: function onSuggestionMouseEnter($e) { this._removeCursor(); this._setCursor(DOM.element($e.currentTarget), true); }, _onSuggestionMouseLeave: function onSuggestionMouseLeave() { this._removeCursor(); }, _onRendered: function onRendered() { this.isEmpty = _.every(this.datasets, isDatasetEmpty); if (this.isEmpty) { this._hide(); } else if (this.isOpen) { this._show(); } this.trigger('datasetRendered'); function isDatasetEmpty(dataset) { return dataset.isEmpty(); } }, _hide: function() { this.$menu.hide(); }, _show: function() { // can't use jQuery#show because $menu is a span element we want // display: block; not dislay: inline; this.$menu.css('display', 'block'); }, _getSuggestions: function getSuggestions() { return this.$menu.find('.aa-suggestion'); }, _getCursor: function getCursor() { return this.$menu.find('.aa-cursor').first(); }, _setCursor: function setCursor($el, silent) { $el.first().addClass('aa-cursor'); if (!silent) { this.trigger('cursorMoved'); } }, _removeCursor: function removeCursor() { this._getCursor().removeClass('aa-cursor'); }, _moveCursor: function moveCursor(increment) { var $suggestions; var $oldCursor; var newCursorIndex; var $newCursor; if (!this.isOpen) { return; } $oldCursor = this._getCursor(); $suggestions = this._getSuggestions(); this._removeCursor(); // shifting before and after modulo to deal with -1 index newCursorIndex = $suggestions.index($oldCursor) + increment; newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1; if (newCursorIndex === -1) { this.trigger('cursorRemoved'); return; } else if (newCursorIndex < -1) { newCursorIndex = $suggestions.length - 1; } this._setCursor($newCursor = $suggestions.eq(newCursorIndex)); // in the case of scrollable overflow // make sure the cursor is visible in the menu this._ensureVisible($newCursor); }, _ensureVisible: function ensureVisible($el) { var elTop; var elBottom; var menuScrollTop; var menuHeight; elTop = $el.position().top; elBottom = elTop + $el.height() + parseInt($el.css('margin-top'), 10) + parseInt($el.css('margin-bottom'), 10); menuScrollTop = this.$menu.scrollTop(); menuHeight = this.$menu.height() + parseInt(this.$menu.css('paddingTop'), 10) + parseInt(this.$menu.css('paddingBottom'), 10); if (elTop < 0) { this.$menu.scrollTop(menuScrollTop + elTop); } else if (menuHeight < elBottom) { this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight)); } }, // ### public close: function close() { if (this.isOpen) { this.isOpen = false; this._removeCursor(); this._hide(); this.trigger('closed'); } }, open: function open() { if (!this.isOpen) { this.isOpen = true; if (!this.isEmpty) { this._show(); } this.trigger('opened'); } }, setLanguageDirection: function setLanguageDirection(dir) { this.$menu.css(dir === 'ltr' ? css.ltr : css.rtl); }, moveCursorUp: function moveCursorUp() { this._moveCursor(-1); }, moveCursorDown: function moveCursorDown() { this._moveCursor(+1); }, getDatumForSuggestion: function getDatumForSuggestion($el) { var datum = null; if ($el.length) { datum = { raw: Dataset.extractDatum($el), value: Dataset.extractValue($el), datasetName: Dataset.extractDatasetName($el) }; } return datum; }, getDatumForCursor: function getDatumForCursor() { return this.getDatumForSuggestion(this._getCursor().first()); }, getDatumForTopSuggestion: function getDatumForTopSuggestion() { return this.getDatumForSuggestion(this._getSuggestions().first()); }, update: function update(query) { _.each(this.datasets, updateDataset); function updateDataset(dataset) { dataset.update(query); } }, empty: function empty() { _.each(this.datasets, clearDataset); this.isEmpty = true; function clearDataset(dataset) { dataset.clear(); } }, isVisible: function isVisible() { return this.isOpen && !this.isEmpty; }, destroy: function destroy() { this.$menu.off('.aa'); this.$menu = null; _.each(this.datasets, destroyDataset); function destroyDataset(dataset) { dataset.destroy(); } } }); // helper functions // ---------------- Dropdown.Dataset = Dataset; function initializeDataset($menu, oDataset) { return new Dropdown.Dataset(_.mixin({'$menu': $menu}, oDataset)); } module.exports = Dropdown; },{"../common/dom.js":12,"../common/utils.js":13,"./css.js":4,"./dataset.js":5,"./event_emitter.js":8}],7:[function(require,module,exports){ 'use strict'; var namespace = 'autocomplete:'; var _ = require('../common/utils.js'); var DOM = require('../common/dom.js'); // constructor // ----------- function EventBus(o) { if (!o || !o.el) { _.error('EventBus initialized without el'); } this.$el = DOM.element(o.el); } // instance methods // ---------------- _.mixin(EventBus.prototype, { // ### public trigger: function(type) { var args = [].slice.call(arguments, 1); this.$el.trigger(namespace + type, args); } }); module.exports = EventBus; },{"../common/dom.js":12,"../common/utils.js":13}],8:[function(require,module,exports){ 'use strict'; var splitter = /\s+/; var nextTick = getNextTick(); module.exports = { onSync: onSync, onAsync: onAsync, off: off, trigger: trigger }; function on(method, types, cb, context) { var type; if (!cb) { return this; } types = types.split(splitter); cb = context ? bindContext(cb, context) : cb; this._callbacks = this._callbacks || {}; while (type = types.shift()) { this._callbacks[type] = this._callbacks[type] || {sync: [], async: []}; this._callbacks[type][method].push(cb); } return this; } function onAsync(types, cb, context) { return on.call(this, 'async', types, cb, context); } function onSync(types, cb, context) { return on.call(this, 'sync', types, cb, context); } function off(types) { var type; if (!this._callbacks) { return this; } types = types.split(splitter); while (type = types.shift()) { delete this._callbacks[type]; } return this; } function trigger(types) { var type; var callbacks; var args; var syncFlush; var asyncFlush; if (!this._callbacks) { return this; } types = types.split(splitter); args = [].slice.call(arguments, 1); while ((type = types.shift()) && (callbacks = this._callbacks[type])) { // eslint-disable-line syncFlush = getFlush(callbacks.sync, this, [type].concat(args)); asyncFlush = getFlush(callbacks.async, this, [type].concat(args)); if (syncFlush()) { nextTick(asyncFlush); } } return this; } function getFlush(callbacks, context, args) { return flush; function flush() { var cancelled; for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) { // only cancel if the callback explicitly returns false cancelled = callbacks[i].apply(context, args) === false; } return !cancelled; } } function getNextTick() { var nextTickFn; if (window.setImmediate) { // IE10+ nextTickFn = function nextTickSetImmediate(fn) { setImmediate(function() { fn(); }); }; } else { // old browsers nextTickFn = function nextTickSetTimeout(fn) { setTimeout(function() { fn(); }, 0); }; } return nextTickFn; } function bindContext(fn, context) { return fn.bind ? fn.bind(context) : function() { fn.apply(context, [].slice.call(arguments, 0)); }; } },{}],9:[function(require,module,exports){ 'use strict'; module.exports = { wrapper: '<span class="algolia-autocomplete"></span>', dropdown: '<span class="aa-dropdown-menu"></span>', dataset: '<div class="aa-dataset-%CLASS%"></div>', suggestions: '<span class="aa-suggestions"></span>', suggestion: '<div class="aa-suggestion"></div>' }; },{}],10:[function(require,module,exports){ 'use strict'; var specialKeyCodeMap; specialKeyCodeMap = { 9: 'tab', 27: 'esc', 37: 'left', 39: 'right', 13: 'enter', 38: 'up', 40: 'down' }; var _ = require('../common/utils.js'); var DOM = require('../common/dom.js'); var EventEmitter = require('./event_emitter.js'); // constructor // ----------- function Input(o) { var that = this; var onBlur; var onFocus; var onKeydown; var onInput; o = o || {}; if (!o.input) { _.error('input is missing'); } // bound functions onBlur = _.bind(this._onBlur, this); onFocus = _.bind(this._onFocus, this); onKeydown = _.bind(this._onKeydown, this); onInput = _.bind(this._onInput, this); this.$hint = DOM.element(o.hint); this.$input = DOM.element(o.input) .on('blur.aa', onBlur) .on('focus.aa', onFocus) .on('keydown.aa', onKeydown); // if no hint, noop all the hint related functions if (this.$hint.length === 0) { this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop; } // ie7 and ie8 don't support the input event // ie9 doesn't fire the input event when characters are removed // not sure if ie10 is compatible if (!_.isMsie()) { this.$input.on('input.aa', onInput); } else { this.$input.on('keydown.aa keypress.aa cut.aa paste.aa', function($e) { // if a special key triggered this, ignore it if (specialKeyCodeMap[$e.which || $e.keyCode]) { return; } // give the browser a chance to update the value of the input // before checking to see if the query changed _.defer(_.bind(that._onInput, that, $e)); }); } // the query defaults to whatever the value of the input is // on initialization, it'll most likely be an empty string this.query = this.$input.val(); // helps with calculating the width of the input's value this.$overflowHelper = buildOverflowHelper(this.$input); } // static methods // -------------- Input.normalizeQuery = function(str) { // strips leading whitespace and condenses all whitespace return (str || '').replace(/^\s*/g, '').replace(/\s{2,}/g, ' '); }; // instance methods // ---------------- _.mixin(Input.prototype, EventEmitter, { // ### private _onBlur: function onBlur() { this.resetInputValue(); this.trigger('blurred'); }, _onFocus: function onFocus() { this.trigger('focused'); }, _onKeydown: function onKeydown($e) { // which is normalized and consistent (but not for ie) var keyName = specialKeyCodeMap[$e.which || $e.keyCode]; this._managePreventDefault(keyName, $e); if (keyName && this._shouldTrigger(keyName, $e)) { this.trigger(keyName + 'Keyed', $e); } }, _onInput: function onInput() { this._checkInputValue(); }, _managePreventDefault: function managePreventDefault(keyName, $e) { var preventDefault; var hintValue; var inputValue; switch (keyName) { case 'tab': hintValue = this.getHint(); inputValue = this.getInputValue(); preventDefault = hintValue && hintValue !== inputValue && !withModifier($e); break; case 'up': case 'down': preventDefault = !withModifier($e); break; default: preventDefault = false; } if (preventDefault) { $e.preventDefault(); } }, _shouldTrigger: function shouldTrigger(keyName, $e) { var trigger; switch (keyName) { case 'tab': trigger = !withModifier($e); break; default: trigger = true; } return trigger; }, _checkInputValue: function checkInputValue() { var inputValue; var areEquivalent; var hasDifferentWhitespace; inputValue = this.getInputValue(); areEquivalent = areQueriesEquivalent(inputValue, this.query); hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false; this.query = inputValue; if (!areEquivalent) { this.trigger('queryChanged', this.query); } else if (hasDifferentWhitespace) { this.trigger('whitespaceChanged', this.query); } }, // ### public focus: function focus() { this.$input.focus(); }, blur: function blur() { this.$input.blur(); }, getQuery: function getQuery() { return this.query; }, setQuery: function setQuery(query) { this.query = query; }, getInputValue: function getInputValue() { return this.$input.val(); }, setInputValue: function setInputValue(value, silent) { this.$input.val(value); // silent prevents any additional events from being triggered if (silent) { this.clearHint(); } else { this._checkInputValue(); } }, resetInputValue: function resetInputValue() { this.setInputValue(this.query, true); }, getHint: function getHint() { return this.$hint.val(); }, setHint: function setHint(value) { this.$hint.val(value); }, clearHint: function clearHint() { this.setHint(''); }, clearHintIfInvalid: function clearHintIfInvalid() { var val; var hint; var valIsPrefixOfHint; var isValid; val = this.getInputValue(); hint = this.getHint(); valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0; isValid = val !== '' && valIsPrefixOfHint && !this.hasOverflow(); if (!isValid) { this.clearHint(); } }, getLanguageDirection: function getLanguageDirection() { return (this.$input.css('direction') || 'ltr').toLowerCase(); }, hasOverflow: function hasOverflow() { // 2 is arbitrary, just picking a small number to handle edge cases var constraint = this.$input.width() - 2; this.$overflowHelper.text(this.getInputValue()); return this.$overflowHelper.width() >= constraint; }, isCursorAtEnd: function() { var valueLength; var selectionStart; var range; valueLength = this.$input.val().length; selectionStart = this.$input[0].selectionStart; if (_.isNumber(selectionStart)) { return selectionStart === valueLength; } else if (document.selection) { // NOTE: this won't work unless the input has focus, the good news // is this code should only get called when the input has focus range = document.selection.createRange(); range.moveStart('character', -valueLength); return valueLength === range.text.length; } return true; }, destroy: function destroy() { this.$hint.off('.aa'); this.$input.off('.aa'); this.$hint = this.$input = this.$overflowHelper = null; } }); // helper functions // ---------------- function buildOverflowHelper($input) { return DOM.element('<pre aria-hidden="true"></pre>') .css({ // position helper off-screen position: 'absolute', visibility: 'hidden', // avoid line breaks and whitespace collapsing whiteSpace: 'pre', // use same font css as input to calculate accurate width fontFamily: $input.css('font-family'), fontSize: $input.css('font-size'), fontStyle: $input.css('font-style'), fontVariant: $input.css('font-variant'), fontWeight: $input.css('font-weight'), wordSpacing: $input.css('word-spacing'), letterSpacing: $input.css('letter-spacing'), textIndent: $input.css('text-indent'), textRendering: $input.css('text-rendering'), textTransform: $input.css('text-transform') }) .insertAfter($input); } function areQueriesEquivalent(a, b) { return Input.normalizeQuery(a) === Input.normalizeQuery(b); } function withModifier($e) { return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey; } module.exports = Input; },{"../common/dom.js":12,"../common/utils.js":13,"./event_emitter.js":8}],11:[function(require,module,exports){ 'use strict'; var attrsKey = 'aaAttrs'; var _ = require('../common/utils.js'); var DOM = require('../common/dom.js'); var EventBus = require('./event_bus.js'); var Input = require('./input.js'); var Dropdown = require('./dropdown.js'); var html = require('./html.js'); var css = require('./css.js'); // constructor // ----------- // THOUGHT: what if datasets could dynamically be added/removed? function Typeahead(o) { var $menu; var $input; var $hint; o = o || {}; if (!o.input) { _.error('missing input'); } this.isActivated = false; this.debug = !!o.debug; this.autoselect = !!o.autoselect; this.openOnFocus = !!o.openOnFocus; this.minLength = _.isNumber(o.minLength) ? o.minLength : 1; this.$node = buildDom(o); $menu = this.$node.find('.aa-dropdown-menu'); $input = this.$node.find('.aa-input'); $hint = this.$node.find('.aa-hint'); // #705: if there's scrollable overflow, ie doesn't support // blur cancellations when the scrollbar is clicked // // #351: preventDefault won't cancel blurs in ie <= 8 $input.on('blur.aa', function($e) { var active = document.activeElement; if (_.isMsie() && ($menu.is(active) || $menu.has(active).length > 0)) { $e.preventDefault(); // stop immediate in order to prevent Input#_onBlur from // getting exectued $e.stopImmediatePropagation(); _.defer(function() { $input.focus(); }); } }); // #351: prevents input blur due to clicks within dropdown menu $menu.on('mousedown.aa', function($e) { $e.preventDefault(); }); this.eventBus = o.eventBus || new EventBus({el: $input}); this.dropdown = new Typeahead.Dropdown({menu: $menu, datasets: o.datasets, templates: o.templates}) .onSync('suggestionClicked', this._onSuggestionClicked, this) .onSync('cursorMoved', this._onCursorMoved, this) .onSync('cursorRemoved', this._onCursorRemoved, this) .onSync('opened', this._onOpened, this) .onSync('closed', this._onClosed, this) .onAsync('datasetRendered', this._onDatasetRendered, this); this.input = new Typeahead.Input({input: $input, hint: $hint}) .onSync('focused', this._onFocused, this) .onSync('blurred', this._onBlurred, this) .onSync('enterKeyed', this._onEnterKeyed, this) .onSync('tabKeyed', this._onTabKeyed, this) .onSync('escKeyed', this._onEscKeyed, this) .onSync('upKeyed', this._onUpKeyed, this) .onSync('downKeyed', this._onDownKeyed, this) .onSync('leftKeyed', this._onLeftKeyed, this) .onSync('rightKeyed', this._onRightKeyed, this) .onSync('queryChanged', this._onQueryChanged, this) .onSync('whitespaceChanged', this._onWhitespaceChanged, this); this._setLanguageDirection(); } // instance methods // ---------------- _.mixin(Typeahead.prototype, { // ### private _onSuggestionClicked: function onSuggestionClicked(type, $el) { var datum; if (datum = this.dropdown.getDatumForSuggestion($el)) { this._select(datum); } }, _onCursorMoved: function onCursorMoved() { var datum = this.dropdown.getDatumForCursor(); this.input.setInputValue(datum.value, true); this.eventBus.trigger('cursorchanged', datum.raw, datum.datasetName); }, _onCursorRemoved: function onCursorRemoved() { this.input.resetInputValue(); this._updateHint(); }, _onDatasetRendered: function onDatasetRendered() { this._updateHint(); }, _onOpened: function onOpened() { this._updateHint(); this.eventBus.trigger('opened'); }, _onClosed: function onClosed() { this.input.clearHint(); this.eventBus.trigger('closed'); }, _onFocused: function onFocused() { this.isActivated = true; if (this.openOnFocus) { var query = this.input.getQuery(); if (query.length >= this.minLength) { this.dropdown.update(query); } else { this.dropdown.empty(); } this.dropdown.open(); } }, _onBlurred: function onBlurred() { if (!this.debug) { this.isActivated = false; this.dropdown.empty(); this.dropdown.close(); } }, _onEnterKeyed: function onEnterKeyed(type, $e) { var cursorDatum; var topSuggestionDatum; cursorDatum = this.dropdown.getDatumForCursor(); topSuggestionDatum = this.dropdown.getDatumForTopSuggestion(); if (cursorDatum) { this._select(cursorDatum); $e.preventDefault(); } else if (this.autoselect && topSuggestionDatum) { this._select(topSuggestionDatum); $e.preventDefault(); } }, _onTabKeyed: function onTabKeyed(type, $e) { var datum; if (datum = this.dropdown.getDatumForCursor()) { this._select(datum); $e.preventDefault(); } else { this._autocomplete(true); } }, _onEscKeyed: function onEscKeyed() { this.dropdown.close(); this.input.resetInputValue(); }, _onUpKeyed: function onUpKeyed() { var query = this.input.getQuery(); if (this.dropdown.isEmpty && query.length >= this.minLength) { this.dropdown.update(query); } else { this.dropdown.moveCursorUp(); } this.dropdown.open(); }, _onDownKeyed: function onDownKeyed() { var query = this.input.getQuery(); if (this.dropdown.isEmpty && query.length >= this.minLength) { this.dropdown.update(query); } else { this.dropdown.moveCursorDown(); } this.dropdown.open(); }, _onLeftKeyed: function onLeftKeyed() { if (this.dir === 'rtl') { this._autocomplete(); } }, _onRightKeyed: function onRightKeyed() { if (this.dir === 'ltr') { this._autocomplete(); } }, _onQueryChanged: function onQueryChanged(e, query) { this.input.clearHintIfInvalid(); if (query.length >= this.minLength) { this.dropdown.update(query); } else { this.dropdown.empty(); } this.dropdown.open(); this._setLanguageDirection(); }, _onWhitespaceChanged: function onWhitespaceChanged() { this._updateHint(); this.dropdown.open(); }, _setLanguageDirection: function setLanguageDirection() { var dir = this.input.getLanguageDirection(); if (this.dir !== dir) { this.dir = dir; this.$node.css('direction', dir); this.dropdown.setLanguageDirection(dir); } }, _updateHint: function updateHint() { var datum; var val; var query; var escapedQuery; var frontMatchRegEx; var match; datum = this.dropdown.getDatumForTopSuggestion(); if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) { val = this.input.getInputValue(); query = Input.normalizeQuery(val); escapedQuery = _.escapeRegExChars(query); // match input value, then capture trailing text frontMatchRegEx = new RegExp('^(?:' + escapedQuery + ')(.+$)', 'i'); match = frontMatchRegEx.exec(datum.value); // clear hint if there's no trailing text if (match) { this.input.setHint(val + match[1]); } else { this.input.clearHint(); } } else { this.input.clearHint(); } }, _autocomplete: function autocomplete(laxCursor) { var hint; var query; var isCursorAtEnd; var datum; hint = this.input.getHint(); query = this.input.getQuery(); isCursorAtEnd = laxCursor || this.input.isCursorAtEnd(); if (hint && query !== hint && isCursorAtEnd) { datum = this.dropdown.getDatumForTopSuggestion(); if (datum) { this.input.setInputValue(datum.value); } this.eventBus.trigger('autocompleted', datum.raw, datum.datasetName); } }, _select: function select(datum) { this.input.setQuery(datum.value); this.input.setInputValue(datum.value, true); this._setLanguageDirection(); this.eventBus.trigger('selected', datum.raw, datum.datasetName); this.dropdown.close(); // #118: allow click event to bubble up to the body before removing // the suggestions otherwise we break event delegation _.defer(_.bind(this.dropdown.empty, this.dropdown)); }, // ### public open: function open() { // if the menu is not activated yet, we need to update // the underlying dropdown menu to trigger the search // otherwise we're not gonna see anything if (!this.isActivated) { var query = this.input.getInputValue(); if (query.length >= this.minLength) { this.dropdown.update(query); } else { this.dropdown.empty(); } } this.dropdown.open(); }, close: function close() { this.dropdown.close(); }, setVal: function setVal(val) { // expect val to be a string, so be safe, and coerce val = _.toStr(val); if (this.isActivated) { this.input.setInputValue(val); } else { this.input.setQuery(val); this.input.setInputValue(val, true); } this._setLanguageDirection(); }, getVal: function getVal() { return this.input.getQuery(); }, destroy: function destroy() { this.input.destroy(); this.dropdown.destroy(); destroyDomStructure(this.$node); this.$node = null; } }); function buildDom(options) { var $input; var $wrapper; var $dropdown; var $hint; $input = DOM.element(options.input); $wrapper = DOM.element(html.wrapper).css(css.wrapper); // override the display property with the table-cell value // if the parent element is a table and the original input was a block // -> https://github.com/algolia/autocomplete.js/issues/16 if ($input.css('display') === 'block' && $input.parent().css('display') === 'table') { $wrapper.css('display', 'table-cell'); } $dropdown = DOM.element(html.dropdown).css(css.dropdown); if (options.templates && options.templates.dropdownMenu) { $dropdown.html(_.templatify(options.templates.dropdownMenu)()); } $hint = $input.clone().css(css.hint).css(getBackgroundStyles($input)); $hint .val('') .addClass('aa-hint') .removeAttr('id name placeholder required') .prop('readonly', true) .attr({autocomplete: 'off', spellcheck: 'false', tabindex: -1}); if ($hint.removeData) { $hint.removeData(); } // store the original values of the attrs that get modified // so modifications can be reverted on destroy $input.data(attrsKey, { dir: $input.attr('dir'), autocomplete: $input.attr('autocomplete'), spellcheck: $input.attr('spellcheck'), style: $input.attr('style') }); $input .addClass('aa-input') .attr({autocomplete: 'off', spellcheck: false}) .css(options.hint ? css.input : css.inputWithNoHint); // ie7 does not like it when dir is set to auto try { if (!$input.attr('dir')) { $input.attr('dir', 'auto'); } } catch (e) { // ignore } return $input .wrap($wrapper) .parent() .prepend(options.hint ? $hint : null) .append($dropdown); } function getBackgroundStyles($el) { return { backgroundAttachment: $el.css('background-attachment'), backgroundClip: $el.css('background-clip'), backgroundColor: $el.css('background-color'), backgroundImage: $el.css('background-image'), backgroundOrigin: $el.css('background-origin'), backgroundPosition: $el.css('background-position'), backgroundRepeat: $el.css('background-repeat'), backgroundSize: $el.css('background-size') }; } function destroyDomStructure($node) { var $input = $node.find('.aa-input'); // need to remove attrs that weren't previously defined and // revert attrs that originally had a value _.each($input.data(attrsKey), function(val, key) { if (val === undefined) { $input.removeAttr(key); } else { $input.attr(key, val); } }); $input .detach() .removeClass('aa-input') .insertAfter($node); if ($input.removeData) { $input.removeData(attrsKey); } $node.remove(); } Typeahead.Dropdown = Dropdown; Typeahead.Input = Input; module.exports = Typeahead; },{"../common/dom.js":12,"../common/utils.js":13,"./css.js":4,"./dropdown.js":6,"./event_bus.js":7,"./html.js":9,"./input.js":10}],12:[function(require,module,exports){ 'use strict'; module.exports = { element: null }; },{}],13:[function(require,module,exports){ 'use strict'; var DOM = require('./dom.js'); module.exports = { // those methods are implemented differently // depending on which build it is, using // $... or angular... or Zepto... or require(...) isArray: null, isFunction: null, isObject: null, bind: null, each: null, map: null, mixin: null, isMsie: function() { // from https://github.com/ded/bowser/blob/master/bowser.js return (/(msie|trident)/i).test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false; }, // http://stackoverflow.com/a/6969486 escapeRegExChars: function(str) { return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); }, isNumber: function(obj) { return typeof obj === 'number'; }, toStr: function toStr(s) { return s === undefined || s === null ? '' : s + ''; }, error: function(msg) { throw new Error(msg); }, every: function(obj, test) { var result = true; if (!obj) { return result; } this.each(obj, function(val, key) { result = test.call(null, val, key, obj); if (!result) { return false; } }); return !!result; }, getUniqueId: (function() { var counter = 0; return function() { return counter++; }; })(), templatify: function templatify(obj) { if (this.isFunction(obj)) { return obj; } var $template = DOM.element(obj); if ($template.prop('tagName') === 'SCRIPT') { return function template() { return $template.text(); }; } return function template() { return String(obj); }; }, defer: function(fn) { setTimeout(fn, 0); }, noop: function() {} }; },{"./dom.js":12}],14:[function(require,module,exports){ 'use strict'; var old$ = window.$; var zepto = require('npm-zepto'); require('npm-zepto/zepto/src/data.js'); window.$ = old$; // setup DOM element var DOM = require('../common/dom.js'); DOM.element = zepto; // setup utils functions var _ = require('../common/utils.js'); _.isArray = zepto.isArray; _.isFunction = zepto.isFunction; _.isObject = zepto.isPlainObject; _.bind = zepto.proxy; _.each = function(collection, cb) { // stupid argument order for jQuery.each zepto.each(collection, reverseArgs); function reverseArgs(index, value) { return cb(value, index); } }; _.map = zepto.map; _.mixin = zepto.extend; //////////////////////// var Typeahead = require('../autocomplete/typeahead.js'); var EventBus = require('../autocomplete/event_bus.js'); function autocomplete(selector, options, datasets) { var $input = zepto(selector); var eventBus = new EventBus({el: $input}); return new Typeahead({ input: $input, eventBus: eventBus, hint: options.hint === undefined ? true : !!options.hint, minLength: options.minLength, autoselect: options.autoselect, openOnFocus: options.openOnFocus, templates: options.templates, debug: options.debug, datasets: datasets }).input.$input; } module.exports = autocomplete; },{"../autocomplete/event_bus.js":7,"../autocomplete/typeahead.js":11,"../common/dom.js":12,"../common/utils.js":13,"npm-zepto":2,"npm-zepto/zepto/src/data.js":3}]},{},[1]);
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "utuko", "kyiukonyi" ], "DAY": [ "Jumapilyi", "Jumatatuu", "Jumanne", "Jumatanu", "Alhamisi", "Ijumaa", "Jumamosi" ], "ERANAMES": [ "Kabla ya Kristu", "Baada ya Kristu" ], "ERAS": [ "KK", "BK" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Januari", "Februari", "Machi", "Aprilyi", "Mei", "Junyi", "Julyai", "Agusti", "Septemba", "Oktoba", "Novemba", "Desemba" ], "SHORTDAY": [ "Jpi", "Jtt", "Jnn", "Jtn", "Alh", "Iju", "Jmo" ], "SHORTMONTH": [ "Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ago", "Sep", "Okt", "Nov", "Des" ], "STANDALONEMONTH": [ "Januari", "Februari", "Machi", "Aprilyi", "Mei", "Junyi", "Julyai", "Agusti", "Septemba", "Oktoba", "Novemba", "Desemba" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "TSh", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "jmc-tz", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'selectall', 'pl', { toolbar: 'Zaznacz wszystko' });
//! moment.js locale configuration //! locale : Serbian Cyrillic [sr-cyrl] //! author : Milan Janačković<milanjanackovic@gmail.com> : https://github.com/milan-j ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var translator = { words: { //Different grammatical cases m: ['један минут', 'једне минуте'], mm: ['минут', 'минуте', 'минута'], h: ['један сат', 'једног сата'], hh: ['сат', 'сата', 'сати'], dd: ['дан', 'дана', 'дана'], MM: ['месец', 'месеца', 'месеци'], yy: ['година', 'године', 'година'] }, correctGrammaticalCase: function (number, wordKey) { return number === 1 ? wordKey[0] : (number >= 2 && number <= 4 ? wordKey[1] : wordKey[2]); }, translate: function (number, withoutSuffix, key) { var wordKey = translator.words[key]; if (key.length === 1) { return withoutSuffix ? wordKey[0] : wordKey[1]; } else { return number + ' ' + translator.correctGrammaticalCase(number, wordKey); } } }; var sr_cyrl = moment.defineLocale('sr-cyrl', { months: 'јануар_фебруар_март_април_мај_јун_јул_август_септембар_октобар_новембар_децембар'.split('_'), monthsShort: 'јан._феб._мар._апр._мај_јун_јул_авг._сеп._окт._нов._дец.'.split('_'), monthsParseExact: true, weekdays: 'недеља_понедељак_уторак_среда_четвртак_петак_субота'.split('_'), weekdaysShort: 'нед._пон._уто._сре._чет._пет._суб.'.split('_'), weekdaysMin: 'не_по_ут_ср_че_пе_су'.split('_'), weekdaysParseExact : true, longDateFormat: { LT: 'H:mm', LTS : 'H:mm:ss', L: 'DD.MM.YYYY', LL: 'D. MMMM YYYY', LLL: 'D. MMMM YYYY H:mm', LLLL: 'dddd, D. MMMM YYYY H:mm' }, calendar: { sameDay: '[данас у] LT', nextDay: '[сутра у] LT', nextWeek: function () { switch (this.day()) { case 0: return '[у] [недељу] [у] LT'; case 3: return '[у] [среду] [у] LT'; case 6: return '[у] [суботу] [у] LT'; case 1: case 2: case 4: case 5: return '[у] dddd [у] LT'; } }, lastDay : '[јуче у] LT', lastWeek : function () { var lastWeekDays = [ '[прошле] [недеље] [у] LT', '[прошлог] [понедељка] [у] LT', '[прошлог] [уторка] [у] LT', '[прошле] [среде] [у] LT', '[прошлог] [четвртка] [у] LT', '[прошлог] [петка] [у] LT', '[прошле] [суботе] [у] LT' ]; return lastWeekDays[this.day()]; }, sameElse : 'L' }, relativeTime : { future : 'за %s', past : 'пре %s', s : 'неколико секунди', m : translator.translate, mm : translator.translate, h : translator.translate, hh : translator.translate, d : 'дан', dd : translator.translate, M : 'месец', MM : translator.translate, y : 'годину', yy : translator.translate }, ordinalParse: /\d{1,2}\./, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 1st is the first week of the year. } }); return sr_cyrl; }));
var when = require('when'), _ = require('lodash'), dataProvider = require('../models'), canThis = require('../permissions').canThis, filteredUserAttributes = require('./users').filteredAttributes, posts; // ## Posts posts = { // #### Browse // **takes:** filter / pagination parameters browse: function browse(options) { options = options || {}; // **returns:** a promise for a page of posts in a json object return dataProvider.Post.findPage(options).then(function (result) { var i = 0, omitted = result; for (i = 0; i < omitted.posts.length; i = i + 1) { omitted.posts[i].author = _.omit(omitted.posts[i].author, filteredUserAttributes); omitted.posts[i].user = _.omit(omitted.posts[i].user, filteredUserAttributes); } return omitted; }); }, // #### Read // **takes:** an identifier (id or slug?) read: function read(args) { // **returns:** a promise for a single post in a json object return dataProvider.Post.findOne(args).then(function (result) { var omitted; if (result) { omitted = result.toJSON(); omitted.author = _.omit(omitted.author, filteredUserAttributes); omitted.user = _.omit(omitted.user, filteredUserAttributes); return omitted; } return when.reject({code: 404, message: 'Post not found'}); }); }, getSlug: function getSlug(args) { return dataProvider.Base.Model.generateSlug(dataProvider.Post, args.title, {status: 'all'}).then(function (slug) { if (slug) { return slug; } return when.reject({code: 500, message: 'Could not generate slug'}); }); }, // #### Edit // **takes:** a json object with all the properties which should be updated edit: function edit(postData) { // **returns:** a promise for the resulting post in a json object if (!this.user) { return when.reject({code: 403, message: 'You do not have permission to edit this post.'}); } var self = this; return canThis(self.user).edit.post(postData.id).then(function () { return dataProvider.Post.edit(postData).then(function (result) { if (result) { var omitted = result.toJSON(); omitted.author = _.omit(omitted.author, filteredUserAttributes); omitted.user = _.omit(omitted.user, filteredUserAttributes); return omitted; } return when.reject({code: 404, message: 'Post not found'}); }).otherwise(function (error) { return dataProvider.Post.findOne({id: postData.id, status: 'all'}).then(function (result) { if (!result) { return when.reject({code: 404, message: 'Post not found'}); } return when.reject({message: error.message}); }); }); }, function () { return when.reject({code: 403, message: 'You do not have permission to edit this post.'}); }); }, // #### Add // **takes:** a json object representing a post, add: function add(postData) { // **returns:** a promise for the resulting post in a json object if (!this.user) { return when.reject({code: 403, message: 'You do not have permission to add posts.'}); } return canThis(this.user).create.post().then(function () { return dataProvider.Post.add(postData); }, function () { return when.reject({code: 403, message: 'You do not have permission to add posts.'}); }); }, // #### Destroy // **takes:** an identifier (id or slug?) destroy: function destroy(args) { // **returns:** a promise for a json response with the id of the deleted post if (!this.user) { return when.reject({code: 403, message: 'You do not have permission to remove posts.'}); } return canThis(this.user).remove.post(args.id).then(function () { return when(posts.read({id : args.id, status: 'all'})).then(function (result) { return dataProvider.Post.destroy(args.id).then(function () { var deletedObj = result; return deletedObj; }); }); }, function () { return when.reject({code: 403, message: 'You do not have permission to remove posts.'}); }); } }; module.exports = posts;
module.exports = "new-module/inner";
'use strict'; var packageJson = require('package-json'); module.exports = function (name, cb) { packageJson(name, 'latest', function (err, json) { if (err) { cb(err); return; } cb(null, json.version); }); };
var files = require('./files.js'); // Set METEOR_WATCH_FORCE_POLLING environment variable to a truthy value to // force the use of files.watchFile instead of pathwatcher.watch. // Enabled on Mac and Linux and disabled on Windows by default. var PATHWATCHER_ENABLED = !process.env.METEOR_WATCH_FORCE_POLLING; if (process.platform === "win32") { PATHWATCHER_ENABLED = false; } var DEFAULT_POLLING_INTERVAL = ~~process.env.METEOR_WATCH_POLLING_INTERVAL_MS || 5000; var NO_PATHWATCHER_POLLING_INTERVAL = ~~process.env.METEOR_WATCH_POLLING_INTERVAL_MS || 500; var suggestedRaisingWatchLimit = false; exports.watch = function watch(absPath, callback) { var lastPathwatcherEventTime = 0; function pathwatcherWrapper() { // It's tempting to call files.unwatchFile(absPath, watchFileWrapper) // here, but previous pathwatcher success is no guarantee of future // pathwatcher reliability. For example, pathwatcher works just fine // when file changes originate from within a Vagrant VM, but changes // to shared files made outside the VM are invisible to pathwatcher, // so our only hope of catching them is to continue polling. lastPathwatcherEventTime = +new Date; callback.apply(this, arguments); } var watcher = null; if (PATHWATCHER_ENABLED) { try { watcher = files.pathwatcherWatch(absPath, pathwatcherWrapper); } catch (e) { // If it isn't an actual pathwatcher failure, rethrow. if (e.message !== 'Unable to watch path') throw e; var constants = require('constants'); var archinfo = require('../utils/archinfo.js'); if (! suggestedRaisingWatchLimit && // Note: the not-super-documented require('constants') maps from // strings to SYSTEM errno values. System errno values aren't the same // as the numbers used internally by libuv! Once we're upgraded // to Node 0.12, we'll have the system errno as a string (on 'code'), // but the support for that wasn't in Node 0.10's uv. // See our PR https://github.com/atom/node-pathwatcher/pull/53 // (and make sure to read the final commit message, not the original // proposed PR, which had a slightly different interface). e.errno === constants.ENOSPC && // The only suggestion we currently have is for Linux. archinfo.matches(archinfo.host(), 'os.linux')) { suggestedRaisingWatchLimit = true; var Console = require('../console/console.js').Console; Console.arrowWarn( "It looks like a simple tweak to your system's configuration will " + "make many tools (including this Meteor command) more efficient. " + "To learn more, see " + Console.url("https://github.com/meteor/meteor/wiki/File-Change-Watcher-Efficiency")); } // ... ignore the error. We'll still have watchFile, which is good // enough. } }; var pollingInterval = watcher ? DEFAULT_POLLING_INTERVAL : NO_PATHWATCHER_POLLING_INTERVAL; function watchFileWrapper() { // If a pathwatcher event fired in the last polling interval, ignore // this event. if (new Date - lastPathwatcherEventTime > pollingInterval) { callback.apply(this, arguments); } } // We use files.watchFile in addition to pathwatcher.watch as a fail-safe to // detect file changes even on network file systems. However (unless the user // disabled pathwatcher or this pathwatcher call failed), we use a relatively // long default polling interval of 5000ms to save CPU cycles. files.watchFile(absPath, { persistent: false, interval: pollingInterval }, watchFileWrapper); var polling = true; return { close: function close() { if (watcher) { watcher.close(); watcher = null; } if (polling) { polling = false; files.unwatchFile(absPath, watchFileWrapper); } } }; };
/* * /MathJax/jax/element/mml/optable/Latin1Supplement.js * * Copyright (c) 2009-2016 The MathJax Consortium * * 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. */ (function(a){var c=a.mo.OPTYPES;var b=a.TEXCLASS;MathJax.Hub.Insert(a.mo.prototype,{OPTABLE:{postfix:{"\u00B0":c.ORD,"\u00B4":c.ACCENT,"\u00B8":c.ACCENT}}});MathJax.Ajax.loadComplete(a.optableDir+"/Latin1Supplement.js")})(MathJax.ElementJax.mml);
/** * 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. * * @flow */ 'use strict'; var React = require('react-native'); var { PickerIOS, Text, View, } = React; var PickerItemIOS = PickerIOS.Item; var CAR_MAKES_AND_MODELS = { amc: { name: 'AMC', models: ['AMX', 'Concord', 'Eagle', 'Gremlin', 'Matador', 'Pacer'], }, alfa: { name: 'Alfa-Romeo', models: ['159', '4C', 'Alfasud', 'Brera', 'GTV6', 'Giulia', 'MiTo', 'Spider'], }, aston: { name: 'Aston Martin', models: ['DB5', 'DB9', 'DBS', 'Rapide', 'Vanquish', 'Vantage'], }, audi: { name: 'Audi', models: ['90', '4000', '5000', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8', 'Q5', 'Q7'], }, austin: { name: 'Austin', models: ['America', 'Maestro', 'Maxi', 'Mini', 'Montego', 'Princess'], }, borgward: { name: 'Borgward', models: ['Hansa', 'Isabella', 'P100'], }, buick: { name: 'Buick', models: ['Electra', 'LaCrosse', 'LeSabre', 'Park Avenue', 'Regal', 'Roadmaster', 'Skylark'], }, cadillac: { name: 'Cadillac', models: ['Catera', 'Cimarron', 'Eldorado', 'Fleetwood', 'Sedan de Ville'], }, chevrolet: { name: 'Chevrolet', models: ['Astro', 'Aveo', 'Bel Air', 'Captiva', 'Cavalier', 'Chevelle', 'Corvair', 'Corvette', 'Cruze', 'Nova', 'SS', 'Vega', 'Volt'], }, }; var PickerExample = React.createClass({ getInitialState: function() { return { carMake: 'cadillac', modelIndex: 3, }; }, render: function() { var make = CAR_MAKES_AND_MODELS[this.state.carMake]; var selectionString = make.name + ' ' + make.models[this.state.modelIndex]; return ( <View> <Text>Please choose a make for your car:</Text> <PickerIOS selectedValue={this.state.carMake} onValueChange={(carMake) => this.setState({carMake, modelIndex: 0})}> {Object.keys(CAR_MAKES_AND_MODELS).map((carMake) => ( <PickerItemIOS key={carMake} value={carMake} label={CAR_MAKES_AND_MODELS[carMake].name} /> ) )} </PickerIOS> <Text>Please choose a model of {make.name}:</Text> <PickerIOS selectedValue={this.state.modelIndex} key={this.state.carMake} onValueChange={(modelIndex) => this.setState({modelIndex})}> {CAR_MAKES_AND_MODELS[this.state.carMake].models.map( (modelName, modelIndex) => ( <PickerItemIOS key={this.state.carmake + '_' + modelIndex} value={modelIndex} label={modelName} /> )) } </PickerIOS> <Text>You selected: {selectionString}</Text> </View> ); }, }); exports.displayName = (undefined: ?string); exports.title = '<PickerIOS>'; exports.description = 'Render lists of selectable options with UIPickerView.'; exports.examples = [ { title: '<PickerIOS>', render: function(): ReactElement { return <PickerExample />; }, }];
'use strict'; var Vue = require('vue'); var Vue__default = 'default' in Vue ? Vue['default'] : Vue; // @NOTE: We have to use Vue.nextTick because the element might not be // present at the time model changes, but will be in the next batch. // But because we use Vue.nextTick, the directive may already be unbound // by the time the callback executes, so we have to make sure it was not. var focus = { priority: 1000, bind: function() { var self = this; this.bound = true; this.focus = function() { if (self.bound === true) { self.el.focus(); } }; this.blur = function() { if (self.bound === true) { self.el.blur(); } }; }, update: function(value) { if (value) { Vue__default.nextTick(this.focus); } else { Vue__default.nextTick(this.blur); } }, unbind: function() { this.bound = false; }, }; var focusModel = { twoWay: true, priority: 1000, bind: function() { var self = this; this.bound = true; this.focus = function() { if (self.bound === true) { self.el.focus(); } }; this.blur = function() { if (self.bound === true) { self.el.blur(); } }; this.focusHandler = function() { self.set(true); }; this.blurHandler = function() { self.set(false); }; Vue.util.on(this.el, 'focus', this.focusHandler); Vue.util.on(this.el, 'blur', this.blurHandler); }, update: function(value) { if (value === true) { Vue__default.nextTick(this.focus); } else if (value === false) { Vue__default.nextTick(this.blur); } else { if (process.env.NODE_ENV !== 'production') { Vue.util.warn( this.name + '="' + this.expression + '" expects a boolean value, ' + 'got ' + JSON.stringify(value) ); } } }, unbind: function() { Vue.util.off(this.el, 'focus', this.focusHandler); Vue.util.off(this.el, 'blur', this.blurHandler); this.bound = false; }, }; var focusAuto = { priority: 100, bind: function() { var self = this; this.bound = true; Vue__default.nextTick(function() { if (self.bound === true) { self.el.focus(); } }); }, unbind: function(){ this.bound = false; }, }; var mixin = { directives: { focus: focus, focusModel: focusModel, focusAuto: focusAuto, }, }; exports.focus = focus; exports.focusModel = focusModel; exports.focusAuto = focusAuto; exports.mixin = mixin;
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=' => ', /** * The following methods are added to the YUI instance * @class YUI~dump */ /** * 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. * * @TODO dumping a window is causing an unhandled exception in * FireFox. * * This method is in the 'dump' module, which is not bundled with * the core YUI object * * @method dump * @param o {object} The object to dump * @param d {int} How deep to recurse child objects, default 3 * @return {string} the dump result */ 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@' );
(function (window) { 'use strict'; var c3 = {}; var CLASS = { target: 'c3-target', chart : 'c3-chart', chartLine: 'c3-chart-line', chartLines: 'c3-chart-lines', chartBar: 'c3-chart-bar', chartBars: 'c3-chart-bars', chartText: 'c3-chart-text', chartTexts: 'c3-chart-texts', chartArc: 'c3-chart-arc', chartArcs: 'c3-chart-arcs', chartArcsTitle: 'c3-chart-arcs-title', selectedCircle: 'c3-selected-circle', selectedCircles: 'c3-selected-circles', eventRect: 'c3-event-rect', eventRects: 'c3-event-rects', zoomRect: 'c3-zoom-rect', brush: 'c3-brush', focused: 'c3-focused', region: 'c3-region', regions: 'c3-regions', tooltip: 'c3-tooltip', tooltipName: 'c3-tooltip-name', shape: 'c3-shape', shapes: 'c3-shapes', line: 'c3-line', bar: 'c3-bar', bars: 'c3-bars', circle: 'c3-circle', circles: 'c3-circles', arc: 'c3-arc', area: 'c3-area', text: 'c3-text', texts: 'c3-texts', grid: 'c3-grid', xgrid: 'c3-xgrid', xgrids: 'c3-xgrids', xgridLine: 'c3-xgrid-line', xgridLines: 'c3-xgrid-lines', xgridFocus: 'c3-xgrid-focus', ygrid: 'c3-ygrid', ygrids: 'c3-ygrids', ygridLine: 'c3-ygrid-line', ygridLines: 'c3-ygrid-lines', axisX: 'c3-axis-x', axisXLabel: 'c3-axis-x-label', axisY: 'c3-axis-y', axisYLabel: 'c3-axis-y-label', axisY2: 'c3-axis-y2', axisY2Label: 'c3-axis-y2-label', legendItem: 'c3-legend-item', legendItemEvent: 'c3-legend-item-event', legendItemTile: 'c3-legend-item-tile', dragarea: 'c3-dragarea', EXPANDED: '_expanded_', SELECTED: '_selected_', INCLUDED: '_included_', }; c3.version = "0.1.24"; /* * Generate chart according to config */ c3.generate = function (config) { var d3 = window.d3 ? window.d3 : window.require ? window.require("d3") : undefined; var c3 = { data : {}, axis: {} }, cache = {}; /*-- Handle Config --*/ function checkConfig(key, message) { if (! (key in config)) { throw Error(message); } } function getConfig(keys, defaultValue) { var target = config, i, isLast, nextTarget; for (i = 0; i < keys.length; i++) { // return default if key not found if (typeof target === 'object' && !(keys[i] in target)) { return defaultValue; } // Check next key's value isLast = (i === keys.length - 1); nextTarget = target[keys[i]]; if ((!isLast && typeof nextTarget !== 'object') || (isLast && typeof defaultValue !== 'object' && typeof nextTarget === 'object')) { return defaultValue; } target = nextTarget; } return target; } // bindto - id to bind the chart var __bindto = getConfig(['bindto'], '#chart'); var __size_width = getConfig(['size', 'width']), __size_height = getConfig(['size', 'height']); var __padding_left = getConfig(['padding', 'left']), __padding_right = getConfig(['padding', 'right']); var __zoom_enabled = getConfig(['zoom', 'enabled'], false), __zoom_extent = getConfig(['zoom', 'extent']), __zoom_privileged = getConfig(['zoom', 'privileged'], false); var __onenter = getConfig(['onenter'], function () {}), __onleave = getConfig(['onleave'], function () {}); var __transition_duration = getConfig(['transition', 'duration'], 350); // data - data configuration checkConfig('data', 'data is required in config'); var __data_x = getConfig(['data', 'x']), __data_xs = getConfig(['data', 'xs'], {}), __data_x_format = getConfig(['data', 'x_format'], '%Y-%m-%d'), __data_id_converter = getConfig(['data', 'id_converter'], function (id) { return id; }), __data_names = getConfig(['data', 'names'], {}), __data_groups = getConfig(['data', 'groups'], []), __data_axes = getConfig(['data', 'axes'], {}), __data_type = getConfig(['data', 'type']), __data_types = getConfig(['data', 'types'], {}), __data_labels = getConfig(['data', 'labels'], {}), __data_order = getConfig(['data', 'order']), __data_regions = getConfig(['data', 'regions'], {}), __data_colors = getConfig(['data', 'colors'], {}), __data_selection_enabled = getConfig(['data', 'selection', 'enabled'], false), __data_selection_grouped = getConfig(['data', 'selection', 'grouped'], false), __data_selection_isselectable = getConfig(['data', 'selection', 'isselectable'], function () { return true; }), __data_selection_multiple = getConfig(['data', 'selection', 'multiple'], true), __data_onclick = getConfig(['data', 'onclick'], function () {}), __data_onenter = getConfig(['data', 'onenter'], function () {}), __data_onleave = getConfig(['data', 'onleave'], function () {}), __data_onselected = getConfig(['data', 'onselected'], function () {}), __data_onunselected = getConfig(['data', 'onunselected'], function () {}), __data_ondragstart = getConfig(['data', 'ondragstart'], function () {}), __data_ondragend = getConfig(['data', 'ondragend'], function () {}); // subchart var __subchart_show = getConfig(['subchart', 'show'], false), __subchart_size_height = __subchart_show ? getConfig(['subchart', 'size', 'height'], 60) : 0; // color var __color_pattern = getConfig(['color', 'pattern'], []); // legend var __legend_show = getConfig(['legend', 'show'], true), __legend_position = getConfig(['legend', 'position'], 'bottom'), __legend_item_onclick = getConfig(['legend', 'item', 'onclick']), __legend_equally = getConfig(['legend', 'equally'], false); // axis var __axis_rotated = getConfig(['axis', 'rotated'], false), __axis_x_type = getConfig(['axis', 'x', 'type'], 'indexed'), __axis_x_categories = getConfig(['axis', 'x', 'categories'], []), __axis_x_tick_centered = getConfig(['axis', 'x', 'tick', 'centered'], false), __axis_x_tick_format = getConfig(['axis', 'x', 'tick', 'format']), __axis_x_tick_culling = getConfig(['axis', 'x', 'tick', 'culling'], __axis_x_type === 'categorized' ? false : true), __axis_x_tick_count = getConfig(['axis', 'x', 'tick', 'count'], 10), __axis_x_max = getConfig(['axis', 'x', 'max']), __axis_x_min = getConfig(['axis', 'x', 'min']), __axis_x_default = getConfig(['axis', 'x', 'default']), __axis_x_label = getConfig(['axis', 'x', 'label'], {}), __axis_y_show = getConfig(['axis', 'y', 'show'], true), __axis_y_max = getConfig(['axis', 'y', 'max']), __axis_y_min = getConfig(['axis', 'y', 'min']), __axis_y_center = getConfig(['axis', 'y', 'center']), __axis_y_label = getConfig(['axis', 'y', 'label'], {}), __axis_y_inner = getConfig(['axis', 'y', 'inner'], false), __axis_y_tick_format = getConfig(['axis', 'y', 'tick', 'format']), __axis_y_padding = getConfig(['axis', 'y', 'padding']), __axis_y_ticks = getConfig(['axis', 'y', 'ticks'], 10), __axis_y2_show = getConfig(['axis', 'y2', 'show'], false), __axis_y2_max = getConfig(['axis', 'y2', 'max']), __axis_y2_min = getConfig(['axis', 'y2', 'min']), __axis_y2_center = getConfig(['axis', 'y2', 'center']), __axis_y2_label = getConfig(['axis', 'y2', 'label'], {}), __axis_y2_inner = getConfig(['axis', 'y2', 'inner'], false), __axis_y2_tick_format = getConfig(['axis', 'y2', 'tick', 'format']), __axis_y2_padding = getConfig(['axis', 'y2', 'padding']), __axis_y2_ticks = getConfig(['axis', 'y2', 'ticks'], 10); // grid var __grid_x_show = getConfig(['grid', 'x', 'show'], false), __grid_x_type = getConfig(['grid', 'x', 'type'], 'tick'), __grid_x_lines = getConfig(['grid', 'x', 'lines'], []), __grid_y_show = getConfig(['grid', 'y', 'show'], false), // not used // __grid_y_type = getConfig(['grid', 'y', 'type'], 'tick'), __grid_y_lines = getConfig(['grid', 'y', 'lines'], []), __grid_y_ticks = getConfig(['grid', 'y', 'ticks'], 10); // point - point of each data var __point_show = getConfig(['point', 'show'], true), __point_r = __point_show ? getConfig(['point', 'r'], 2.5) : 0, __point_focus_line_enabled = getConfig(['point', 'focus', 'line', 'enabled'], true), __point_focus_expand_enabled = getConfig(['point', 'focus', 'expand', 'enabled'], true), __point_focus_expand_r = getConfig(['point', 'focus', 'expand', 'r'], __point_focus_expand_enabled ? 4 : __point_r), __point_select_r = getConfig(['point', 'focus', 'select', 'r'], 8); // bar var __bar_width = getConfig(['bar', 'width']), __bar_width_ratio = getConfig(['bar', 'width', 'ratio'], 0.6); // pie var __pie_label_show = getConfig(['pie', 'label', 'show'], true), __pie_label_format = getConfig(['pie', 'label', 'format']), __pie_onclick = getConfig(['pie', 'onclick'], function () {}), __pie_onmouseover = getConfig(['pie', 'onmouseover'], function () {}), __pie_onmouseout = getConfig(['pie', 'onmouseout'], function () {}); // donut var __donut_label_show = getConfig(['donut', 'label', 'show'], true), __donut_label_format = getConfig(['donut', 'label', 'format']), __donut_title = getConfig(['donut', 'title'], ""), __donut_onclick = getConfig(['donut', 'onclick'], function () {}), __donut_onmouseover = getConfig(['donut', 'onmouseover'], function () {}), __donut_onmouseout = getConfig(['donut', 'onmouseout'], function () {}); // region - region to change style var __regions = getConfig(['regions'], []); // tooltip - show when mouseover on each data var __tooltip_show = getConfig(['tooltip', 'show'], true), __tooltip_format_title = getConfig(['tooltip', 'format', 'title']), __tooltip_format_value = getConfig(['tooltip', 'format', 'value']), __tooltip_contents = getConfig(['tooltip', 'contents'], function (d, defaultTitleFormat, defaultValueFormat, color) { var titleFormat = __tooltip_format_title ? __tooltip_format_title : defaultTitleFormat, valueFormat = __tooltip_format_value ? __tooltip_format_value : defaultValueFormat, text, i, title, value, name; for (i = 0; i < d.length; i++) { if (! (d[i] && (d[i].value || d[i].value === 0))) { continue; } if (! text) { title = titleFormat ? titleFormat(d[i].x) : d[i].x; text = "<table class='" + CLASS.tooltip + "'>" + (title || title === 0 ? "<tr><th colspan='2'>" + title + "</th></tr>" : ""); } name = d[i].name; value = valueFormat(d[i].value, d[i].ratio); text += "<tr class='" + CLASS.tooltipName + "-" + d[i].id + "'>"; text += "<td class='name'><span style='background-color:" + color(d[i].id) + "'></span>" + name + "</td>"; text += "<td class='value'>" + value + "</td>"; text += "</tr>"; } return text + "</table>"; }), __tooltip_init_show = getConfig(['tooltip', 'init', 'show'], false), __tooltip_init_x = getConfig(['tooltip', 'init', 'x'], 0), __tooltip_init_position = getConfig(['tooltip', 'init', 'position'], {top: '0px', left: '50px'}); /*-- Set Variables --*/ var clipId = (typeof __bindto === "string" ? __bindto.replace('#', '') : __bindto.id) + '-clip', clipPath = getClipPath(clipId); var isTimeSeries = (__axis_x_type === 'timeseries'), isCategorized = (__axis_x_type === 'categorized'), isCustomX = !isTimeSeries && (__data_x || notEmpty(__data_xs)); var dragStart = null, dragging = false, cancelClick = false, mouseover = false; var color = generateColor(__data_colors, __color_pattern); var defaultTimeFormat = (function () { var formats = [ [d3.time.format("%Y/%-m/%-d"), function () { return true; }], [d3.time.format("%-m/%-d"), function (d) { return d.getMonth(); }], [d3.time.format("%-m/%-d"), function (d) { return d.getDate() !== 1; }], [d3.time.format("%-m/%-d"), function (d) { return d.getDay() && d.getDate() !== 1; }], [d3.time.format("%I %p"), function (d) { return d.getHours(); }], [d3.time.format("%I:%M"), function (d) { return d.getMinutes(); }], [d3.time.format(":%S"), function (d) { return d.getSeconds(); }], [d3.time.format(".%L"), function (d) { return d.getMilliseconds(); }] ]; return function (date) { var i = formats.length - 1, f = formats[i]; while (!f[1](date)) { f = formats[--i]; } return f[0](date); }; })(); var hiddenTargetIds = []; /*-- Set Chart Params --*/ var margin, margin2, margin3, width, width2, height, height2, currentWidth, currentHeight, legendHeight, legendWidth; var radius, radiusExpanded, innerRadius, svgArc, svgArcExpanded, svgArcExpandedSub, pie; var xMin, xMax, yMin, yMax, subXMin, subXMax, subYMin, subYMax; var x, y, y2, subX, subY, subY2, xAxis, yAxis, yAxis2, subXAxis; var xOrient = __axis_rotated ? "left" : "bottom", yOrient = __axis_rotated ? (__axis_y_inner ? "top" : "bottom") : (__axis_y_inner ? "right" : "left"), y2Orient = __axis_rotated ? (__axis_y2_inner ? "bottom" : "top") : (__axis_y2_inner ? "left" : "right"), subXOrient = __axis_rotated ? "left" : "bottom"; var translate = { main : function () { return "translate(" + margin.left + "," + margin.top + ")"; }, context : function () { return "translate(" + margin2.left + "," + margin2.top + ")"; }, legend : function () { return "translate(" + margin3.left + "," + margin3.top + ")"; }, x : function () { return "translate(0," + (__axis_rotated ? 0 : height) + ")"; }, y : function () { return "translate(0," + (__axis_rotated ? height : 0) + ")"; }, y2 : function () { return "translate(" + (__axis_rotated ? 0 : width) + "," + (__axis_rotated ? 1 : 0) + ")"; }, subx : function () { return "translate(0," + (__axis_rotated ? 0 : height2) + ")"; }, arc: function () { return "translate(" + width / 2 + "," + height / 2 + ")"; } }; var isLegendRight = __legend_position === 'right'; var legendStep = 0, legendItemWidth = 0, legendItemHeight = 0; /*-- Define Functions --*/ function getClipPath(id) { return "url(" + document.URL.split('#')[0] + "#" + id + ")"; } function transformMain() { main.attr("transform", translate.main); main.select('.' + CLASS.axisX).attr("transform", translate.x); main.select('.' + CLASS.axisY).attr("transform", translate.y); main.select('.' + CLASS.axisY2).attr("transform", translate.y2); main.select('.' + CLASS.chartArcs).attr("transform", translate.arc); } function transformContext() { if (__subchart_show) { context.attr("transform", translate.context); context.select('.' + CLASS.axisX).attr("transform", translate.subx); } } function transformLegend(withTransition) { var duration = withTransition !== false ? 250 : 0; if (__legend_show) { legend.transition().duration(duration).attr("transform", translate.legend); } } function transformAll(withTransition) { transformMain(withTransition); transformContext(withTransition); transformLegend(withTransition); } //-- Sizes --// // TODO: configurabale var rotated_padding_left = 30, rotated_padding_right = 30, rotated_padding_top = 5; function updateSizes() { currentWidth = getCurrentWidth(); currentHeight = getCurrentHeight(); legendHeight = getLegendHeight(); legendWidth = getLegendWidth(); // for main margin = { top: __axis_rotated ? getHorizontalAxisHeight('y2') : rotated_padding_top, right: getCurrentPaddingRight(), bottom: getHorizontalAxisHeight(__axis_rotated ? 'y' : 'x') + (__axis_rotated ? 0 : __subchart_size_height) + (isLegendRight ? 0 : legendHeight), left: (__axis_rotated ? __subchart_size_height + rotated_padding_right : 0) + getCurrentPaddingLeft() }; width = currentWidth - margin.left - margin.right; height = currentHeight - margin.top - margin.bottom; if (width < 0) { width = 0; } if (height < 0) { height = 0; } // for context margin2 = { top: __axis_rotated ? margin.top : (currentHeight - __subchart_size_height - (isLegendRight ? 0 : legendHeight)), right: NaN, bottom: 20 + (isLegendRight ? 0 : legendHeight), left: __axis_rotated ? rotated_padding_left : margin.left }; width2 = __axis_rotated ? margin.left - rotated_padding_left - rotated_padding_right : width; height2 = __axis_rotated ? height : currentHeight - margin2.top - margin2.bottom; if (width2 < 0) { width2 = 0; } if (height2 < 0) { height2 = 0; } // for legend margin3 = { top: isLegendRight ? 0 : currentHeight - legendHeight, right: NaN, bottom: 0, left: isLegendRight ? currentWidth - legendWidth : 0 }; // for arc updateRadius(); if (isLegendRight && hasArcType(c3.data.targets)) { margin3.left = width / 2 + radiusExpanded; } } function updateRadius() { radiusExpanded = height / 2; radius = radiusExpanded * 0.95; innerRadius = hasDonutType(c3.data.targets) ? radius * 0.6 : 0; } function getSvgLeft() { var leftAxisClass = __axis_rotated ? CLASS.axisX : CLASS.axisY, leftAxis = d3.select('.' + leftAxisClass).node(), svgRect = leftAxis ? leftAxis.getBoundingClientRect() : {right: 0}, chartRect = d3.select(__bindto).node().getBoundingClientRect(), svgLeft = svgRect.right - chartRect.left - getCurrentPaddingLeft(); return svgLeft > 0 ? svgLeft : 0; } function getCurrentWidth() { return __size_width ? __size_width : getParentWidth(); } function getCurrentHeight() { var h = __size_height ? __size_height : getParentHeight(); return h > 0 ? h : 320; } function getCurrentPaddingLeft() { if (hasArcType(c3.data.targets)) { return 0; } else if (__padding_left) { return __padding_left; } else { return __axis_rotated || !__axis_y_show || __axis_y_inner ? 1 : getAxisWidthByAxisId('y'); } } function getCurrentPaddingRight() { var defaultPadding = 1; if (hasArcType(c3.data.targets)) { return 0; } else if (__padding_right) { return __padding_right; } else if (isLegendRight) { return legendWidth + (__axis_y2_show && !__axis_rotated ? getAxisWidthByAxisId('y2') : defaultPadding); } else if (__axis_y2_show) { return __axis_y2_inner || __axis_rotated ? defaultPadding : getAxisWidthByAxisId('y2'); } else { return defaultPadding; } } function getAxisWidthByAxisId(id) { var position = getAxisLabelPositionById(id); return position.isInner ? 20 + getMaxTickWidth(id) : 40 + getMaxTickWidth(id); } function getHorizontalAxisHeight(axisId) { if (axisId === 'y' && !__axis_y_show) { return __legend_show && !isLegendRight ? 10 : 1; } if (axisId === 'y2' && !__axis_y2_show) { return rotated_padding_top; } return (getAxisLabelPositionById(axisId).isInner ? 30 : 40) + (axisId === 'y2' ? -10 : 0); } function getParentWidth() { return +d3.select(__bindto).style("width").replace('px', ''); // TODO: if rotated, use height } function getParentHeight() { return +d3.select(__bindto).style('height').replace('px', ''); // TODO: if rotated, use width } function getAxisClipX(forHorizontal) { return forHorizontal ? -(1 + 4) : -(margin.left - 1); } function getAxisClipY(forHorizontal) { return forHorizontal ? -20 : -1; } function getXAxisClipX() { return getAxisClipX(!__axis_rotated); } function getXAxisClipY() { return getAxisClipY(!__axis_rotated); } function getYAxisClipX() { return getAxisClipX(__axis_rotated); } function getYAxisClipY() { return getAxisClipY(__axis_rotated); } function getAxisClipWidth(forHorizontal) { return forHorizontal ? width + 2 + 4 : margin.left + 20; } function getAxisClipHeight(forHorizontal) { return forHorizontal ? 80 : height + 2; } function getXAxisClipWidth() { return getAxisClipWidth(!__axis_rotated); } function getXAxisClipHeight() { return getAxisClipHeight(!__axis_rotated); } function getYAxisClipWidth() { return getAxisClipWidth(__axis_rotated); } function getYAxisClipHeight() { return getAxisClipHeight(__axis_rotated); } function getEventRectWidth() { var base = __axis_rotated ? height : width, maxDataCount = getMaxDataCount(), ratio = getXDomainRatio() * (hasBarType(c3.data.targets) ? (maxDataCount - (isCategorized ? 0.25 : 1)) / maxDataCount : 0.98); return maxDataCount > 1 ? (base * ratio) / (maxDataCount - 1) : base; } function updateLegendStep(step) { legendStep = step; } function updateLegendItemWidth(w) { legendItemWidth = w; } function updateLegendItemHeight(h) { legendItemHeight = h; } function getLegendWidth() { return __legend_show ? isLegendRight ? legendItemWidth * (legendStep + 1) : currentWidth : 0; } function getLegendHeight() { return __legend_show ? isLegendRight ? currentHeight : legendItemHeight * (legendStep + 1) : 0; } //-- Scales --// function updateScales() { var xAxisTickFormat, xAxisTicks, forInit = !x; // update edges xMin = __axis_rotated ? 1 : 0; xMax = __axis_rotated ? height : width; yMin = __axis_rotated ? 0 : height; yMax = __axis_rotated ? width : 1; subXMin = xMin; subXMax = xMax; subYMin = __axis_rotated ? 0 : height2; subYMax = __axis_rotated ? width2 : 1; // update scales x = getX(xMin, xMax, forInit ? undefined : x.domain(), function () { return xAxis.tickOffset(); }); y = getY(yMin, yMax); y2 = getY(yMin, yMax); subX = getX(xMin, xMax, orgXDomain, function (d) { return d % 1 ? 0 : subXAxis.tickOffset(); }); subY = getY(subYMin, subYMax); subY2 = getY(subYMin, subYMax); // update axes xAxisTickFormat = getXAxisTickFormat(); xAxisTicks = getXAxisTicks(); xAxis = getXAxis(x, xOrient, xAxisTickFormat, xAxisTicks); subXAxis = getXAxis(subX, subXOrient, xAxisTickFormat, xAxisTicks); yAxis = getYAxis(y, yOrient, __axis_y_tick_format, __axis_y_ticks); yAxis2 = getYAxis(y2, y2Orient, __axis_y2_tick_format, __axis_y2_ticks); // Set initialized scales to brush and zoom if (!forInit) { brush.scale(subX); if (__zoom_enabled) { zoom.scale(x); } } // update for arc updateArc(); } function updateArc() { svgArc = getSvgArc(); svgArcExpanded = getSvgArcExpanded(); svgArcExpandedSub = getSvgArcExpanded(0.98); } function getX(min, max, domain, offset) { var scale = ((isTimeSeries) ? d3.time.scale() : d3.scale.linear()).range([min, max]); // Set function and values for c3 scale.orgDomain = function () { return scale.domain(); }; if (isDefined(domain)) { scale.domain(domain); } if (isUndefined(offset)) { offset = function () { return 0; }; } // Define customized scale if categorized axis if (isCategorized) { var _scale = scale, key; scale = function (d) { return _scale(d) + offset(d); }; for (key in _scale) { scale[key] = _scale[key]; } scale.orgDomain = function () { return _scale.domain(); }; scale.domain = function (domain) { if (!arguments.length) { domain = _scale.domain(); return [domain[0], domain[1] + 1]; } _scale.domain(domain); return scale; }; } return scale; } function getY(min, max) { return d3.scale.linear().range([min, max]); } function getYScale(id) { return getAxisId(id) === 'y2' ? y2 : y; } function getSubYScale(id) { return getAxisId(id) === 'y2' ? subY2 : subY; } //-- Axes --// function getXAxis(scale, orient, tickFormat, ticks) { var axis = (isCategorized ? categoryAxis() : d3.svg.axis()).scale(scale).orient(orient); // Set tick axis.tickFormat(tickFormat).ticks(ticks); if (isCategorized) { axis.tickCentered(__axis_x_tick_centered); } else { axis.tickOffset = function () { var base = __axis_rotated ? height : width; return ((base * getXDomainRatio()) / getMaxDataCount()) / 2; }; } // Set categories if (isCategorized) { axis.categories(__axis_x_categories); } return axis; } function getYAxis(scale, orient, tickFormat, ticks) { return d3.svg.axis().scale(scale).orient(orient).tickFormat(tickFormat).ticks(ticks).outerTickSize(0); } function getAxisId(id) { return id in __data_axes ? __data_axes[id] : 'y'; } function getXAxisTickFormat() { var format = isTimeSeries ? defaultTimeFormat : isCategorized ? category : null; if (__axis_x_tick_format) { if (typeof __axis_x_tick_format === 'function') { format = __axis_x_tick_format; } else if (isTimeSeries) { format = function (date) { return d3.time.format(__axis_x_tick_format)(date); }; } } return format; } function getXAxisTicks() { var maxDataCount = getMaxDataCount(); return __axis_x_tick_culling && maxDataCount > __axis_x_tick_count ? __axis_x_tick_count : maxDataCount; } function getAxisLabelOptionByAxisId(axisId) { var option; if (axisId === 'y') { option = __axis_y_label; } else if (axisId === 'y2') { option = __axis_y2_label; } else if (axisId === 'x') { option = __axis_x_label; } return option; } function getAxisLabelText(axisId) { var option = getAxisLabelOptionByAxisId(axisId); return typeof option === 'string' ? option : option ? option.text : null; } function setAxisLabelText(axisId, text) { var option = getAxisLabelOptionByAxisId(axisId); if (typeof option === 'string') { if (axisId === 'y') { __axis_y_label = text; } else if (axisId === 'y2') { __axis_y2_label = text; } else if (axisId === 'x') { __axis_x_label = text; } } else if (option) { option.text = text; } } function getAxisLabelPosition(axisId, defaultPosition) { var option = getAxisLabelOptionByAxisId(axisId), position = (option && typeof option === 'object' && option.position) ? option.position : defaultPosition; return { isInner: position.indexOf('inner') >= 0, isOuter: position.indexOf('outer') >= 0, isLeft: position.indexOf('left') >= 0, isCenter: position.indexOf('center') >= 0, isRight: position.indexOf('right') >= 0, isTop: position.indexOf('top') >= 0, isMiddle: position.indexOf('middle') >= 0, isBottom: position.indexOf('bottom') >= 0 }; } function getXAxisLabelPosition() { return getAxisLabelPosition('x', __axis_rotated ? 'inner-top' : 'inner-right'); } function getYAxisLabelPosition() { return getAxisLabelPosition('y', __axis_rotated ? 'inner-right' : 'inner-top'); } function getY2AxisLabelPosition() { return getAxisLabelPosition('y2', __axis_rotated ? 'inner-right' : 'inner-top'); } function getAxisLabelPositionById(id) { return id === 'y2' ? getY2AxisLabelPosition() : id === 'y' ? getYAxisLabelPosition() : getXAxisLabelPosition(); } function textForXAxisLabel() { return getAxisLabelText('x'); } function textForYAxisLabel() { return getAxisLabelText('y'); } function textForY2AxisLabel() { return getAxisLabelText('y2'); } function xForAxisLabel(forHorizontal, position) { if (forHorizontal) { return position.isLeft ? 0 : position.isCenter ? width / 2 : width; } else { return position.isBottom ? -height : position.isMiddle ? -height / 2 : 0; } } function dxForAxisLabel(forHorizontal, position) { if (forHorizontal) { return position.isLeft ? "0.5em" : position.isRight ? "-0.5em" : "0"; } else { return position.isTop ? "-0.5em" : position.isBottom ? "0.5em" : "0"; } } function textAnchorForAxisLabel(forHorizontal, position) { if (forHorizontal) { return position.isLeft ? 'start' : position.isCenter ? 'middle' : 'end'; } else { return position.isBottom ? 'start' : position.isMiddle ? 'middle' : 'end'; } } function xForXAxisLabel() { return xForAxisLabel(!__axis_rotated, getXAxisLabelPosition()); } function xForYAxisLabel() { return xForAxisLabel(__axis_rotated, getYAxisLabelPosition()); } function xForY2AxisLabel() { return xForAxisLabel(__axis_rotated, getY2AxisLabelPosition()); } function dxForXAxisLabel() { return dxForAxisLabel(!__axis_rotated, getXAxisLabelPosition()); } function dxForYAxisLabel() { return dxForAxisLabel(__axis_rotated, getYAxisLabelPosition()); } function dxForY2AxisLabel() { return dxForAxisLabel(__axis_rotated, getY2AxisLabelPosition()); } function dyForXAxisLabel() { var position = getXAxisLabelPosition(); if (__axis_rotated) { return position.isInner ? "1.2em" : -30 - getMaxTickWidth('x'); } else { return position.isInner ? "-0.5em" : "3em"; } } function dyForYAxisLabel() { var position = getYAxisLabelPosition(); if (__axis_rotated) { return position.isInner ? "-0.5em" : "3em"; } else { return position.isInner ? "1.2em" : -20 - getMaxTickWidth('y'); } } function dyForY2AxisLabel() { var position = getY2AxisLabelPosition(); if (__axis_rotated) { return position.isInner ? "1.2em" : "-2.2em"; } else { return position.isInner ? "-0.5em" : 30 + getMaxTickWidth('y2'); } } function textAnchorForXAxisLabel() { return textAnchorForAxisLabel(!__axis_rotated, getXAxisLabelPosition()); } function textAnchorForYAxisLabel() { return textAnchorForAxisLabel(__axis_rotated, getYAxisLabelPosition()); } function textAnchorForY2AxisLabel() { return textAnchorForAxisLabel(__axis_rotated, getY2AxisLabelPosition()); } function getMaxTickWidth(id) { var maxWidth = 0, axisClass = id === 'x' ? CLASS.axisX : id === 'y' ? CLASS.axisY : CLASS.axisY2; d3.selectAll('.' + axisClass + ' .tick text').each(function () { var box = this.getBBox(); if (maxWidth < box.width) { maxWidth = box.width; } }); return maxWidth < 20 ? 20 : maxWidth; } function categoryAxis() { var scale = d3.scale.linear(), orient = "bottom"; var tickMajorSize = 6, /*tickMinorSize = 6,*/ tickEndSize = 6, tickPadding = 3, tickCentered = false, tickTextNum = 10, tickOffset = 0, tickFormat = null, tickCulling = true; var categories = []; function axisX(selection, x) { selection.attr("transform", function (d) { return "translate(" + (x(d) + tickOffset) + ", 0)"; }); } function axisY(selection, y) { selection.attr("transform", function (d) { return "translate(0," + y(d) + ")"; }); } function scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [ start, stop ] : [ stop, start ]; } function generateTicks(domain) { var ticks = []; for (var i = Math.ceil(domain[0]); i < domain[1]; i++) { ticks.push(i); } if (ticks.length > 0 && ticks[0] > 0) { ticks.unshift(ticks[0] - (ticks[1] - ticks[0])); } return ticks; } function shouldShowTickText(ticks, i) { var length = ticks.length - 1; return length <= tickTextNum || i % Math.ceil(length / tickTextNum) === 0; } function category(i) { return i < categories.length ? categories[i] : i; } function formattedCategory(i) { var c = category(i); return tickFormat ? tickFormat(c) : c; } function axis(g) { g.each(function () { var g = d3.select(this); var ticks = generateTicks(scale.domain()); var tick = g.selectAll(".tick.major").data(ticks, String), tickEnter = tick.enter().insert("g", "path").attr("class", "tick major").style("opacity", 1e-6), tickExit = d3.transition(tick.exit()).style("opacity", 1e-6).remove(), tickUpdate = d3.transition(tick).style("opacity", 1), tickTransform, tickX; var range = scale.rangeExtent ? scale.rangeExtent() : scaleExtent(scale.range()), path = g.selectAll(".domain").data([ 0 ]); path.enter().append("path").attr("class", "domain"); var pathUpdate = d3.transition(path); var scale1 = scale.copy(), scale0 = this.__chart__ || scale1; this.__chart__ = scale1; tickEnter.append("line"); tickEnter.append("text"); var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text"), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"); tickOffset = (scale1(1) - scale1(0)) / 2; tickX = tickCentered ? 0 : tickOffset; switch (orient) { case "bottom": { tickTransform = axisX; lineEnter.attr("y2", tickMajorSize); textEnter.attr("y", Math.max(tickMajorSize, 0) + tickPadding); lineUpdate.attr("x1", tickX).attr("x2", tickX).attr("y2", tickMajorSize); textUpdate.attr("x", 0).attr("y", Math.max(tickMajorSize, 0) + tickPadding); text.attr("dy", ".71em").style("text-anchor", "middle"); text.text(function (i) { return shouldShowTickText(ticks, i) ? formattedCategory(i) : ""; }); pathUpdate.attr("d", "M" + range[0] + "," + tickEndSize + "V0H" + range[1] + "V" + tickEndSize); break; } /* TODO: implement case "top": { tickTransform = axisX lineEnter.attr("y2", -tickMajorSize) textEnter.attr("y", -(Math.max(tickMajorSize, 0) + tickPadding)) lineUpdate.attr("x2", 0).attr("y2", -tickMajorSize) textUpdate.attr("x", 0).attr("y", -(Math.max(tickMajorSize, 0) + tickPadding)) text.attr("dy", "0em").style("text-anchor", "middle") pathUpdate.attr("d", "M" + range[0] + "," + -tickEndSize + "V0H" + range[1] + "V" + -tickEndSize) break } */ case "left": { tickTransform = axisY; lineEnter.attr("x2", -tickMajorSize); textEnter.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding)); lineUpdate.attr("x2", -tickMajorSize).attr("y2", 0); textUpdate.attr("x", -(Math.max(tickMajorSize, 0) + tickPadding)).attr("y", tickOffset); text.attr("dy", ".32em").style("text-anchor", "end"); text.text(function (i) { return shouldShowTickText(ticks, i) ? formattedCategory(i) : ""; }); pathUpdate.attr("d", "M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize); break; } /* case "right": { tickTransform = axisY lineEnter.attr("x2", tickMajorSize) textEnter.attr("x", Math.max(tickMajorSize, 0) + tickPadding) lineUpdate.attr("x2", tickMajorSize).attr("y2", 0) textUpdate.attr("x", Math.max(tickMajorSize, 0) + tickPadding).attr("y", 0) text.attr("dy", ".32em").style("text-anchor", "start") pathUpdate.attr("d", "M" + tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + tickEndSize) break } */ } if (scale.ticks) { tickEnter.call(tickTransform, scale0); tickUpdate.call(tickTransform, scale1); tickExit.call(tickTransform, scale1); } else { var dx = scale1.rangeBand() / 2, x = function (d) { return scale1(d) + dx; }; tickEnter.call(tickTransform, x); tickUpdate.call(tickTransform, x); } }); } axis.scale = function (x) { if (!arguments.length) { return scale; } scale = x; return axis; }; axis.orient = function (x) { if (!arguments.length) { return orient; } orient = x in {top: 1, right: 1, bottom: 1, left: 1} ? x + "" : "bottom"; return axis; }; axis.categories = function (x) { if (!arguments.length) { return categories; } categories = x; return axis; }; axis.tickCentered = function (x) { if (!arguments.length) { return tickCentered; } tickCentered = x; return axis; }; axis.tickFormat = function (format) { if (!arguments.length) { return tickFormat; } tickFormat = format; return axis; }; axis.tickOffset = function () { return tickOffset; }; axis.ticks = function (n) { if (!arguments.length) { return tickTextNum; } tickTextNum = n; return axis; }; axis.tickCulling = function (culling) { if (!arguments.length) { return tickCulling; } tickCulling = culling; return axis; }; return axis; } //-- Arc --// pie = d3.layout.pie().value(function (d) { return d.values.reduce(function (a, b) { return a + b.value; }, 0); }); function updateAngle(d) { var found = false; pie(filterTargetsToShow(c3.data.targets)).forEach(function (t) { if (! found && t.data.id === d.data.id) { found = true; d = t; return; } }); return found ? d : null; } function getSvgArc() { var arc = d3.svg.arc().outerRadius(radius).innerRadius(innerRadius), newArc = function (d, withoutUpdate) { var updated; if (withoutUpdate) { return arc(d); } // for interpolate updated = updateAngle(d); return updated ? arc(updated) : "M 0 0"; }; // TODO: extends all function newArc.centroid = arc.centroid; return newArc; } function getSvgArcExpanded(rate) { var arc = d3.svg.arc().outerRadius(radiusExpanded * (rate ? rate : 1)).innerRadius(innerRadius); return function (d) { var updated = updateAngle(d); return updated ? arc(updated) : "M 0 0"; }; } function getArc(d, withoutUpdate) { return isArcType(d.data) ? svgArc(d, withoutUpdate) : "M 0 0"; } function transformForArcLabel(d) { var updated = updateAngle(d), c, x, y, h, translate = ""; if (updated) { c = svgArc.centroid(updated); x = c[0], y = c[1], h = Math.sqrt(x * x + y * y); translate = "translate(" + ((x / h) * radius * 0.8) + ',' + ((y / h) * radius * 0.8) + ")"; } return translate; } function getArcRatio(d) { return d ? (d.endAngle - d.startAngle) / (Math.PI * 2) : null; } function convertToArcData(d) { return addName({ id: d.data.id, value: d.value, ratio: getArcRatio(d) }); } function textForArcLabel(d) { var updated, value, ratio, format; if (! shouldShowArcLable()) { return ""; } updated = updateAngle(d); value = updated ? updated.value : null; ratio = getArcRatio(updated); format = getArcLabelFormat(); return format ? format(value, ratio) : defaultArcValueFormat(value, ratio); } function expandArc(id, withoutFadeOut) { var target = svg.selectAll('.' + CLASS.chartArc + selectorTarget(id)), noneTargets = svg.selectAll('.' + CLASS.arc).filter(function (data) { return data.data.id !== id; }); target.selectAll('path') .transition().duration(50) .attr("d", svgArcExpanded) .transition().duration(100) .attr("d", svgArcExpandedSub) .each(function (d) { if (isDonutType(d.data)) { // callback here } }); if (!withoutFadeOut) { noneTargets.style("opacity", 0.3); } } function unexpandArc(id) { var target = svg.selectAll('.' + CLASS.chartArc + selectorTarget(id)); target.selectAll('path') .transition().duration(50) .attr("d", svgArc); svg.selectAll('.' + CLASS.arc) .style("opacity", 1); } function shouldShowArcLable() { return hasDonutType(c3.data.targets) ? __donut_label_show : __pie_label_show; } function getArcLabelFormat() { return hasDonutType(c3.data.targets) ? __donut_label_format : __pie_label_format; } function getArcTitle() { return hasDonutType(c3.data.targets) ? __donut_title : ""; } function getArcOnClick() { var callback = hasDonutType(c3.data.targets) ? __donut_onclick : __pie_onclick; return typeof callback === 'function' ? callback : function () {}; } function getArcOnMouseOver() { var callback = hasDonutType(c3.data.targets) ? __donut_onmouseover : __pie_onmouseover; return typeof callback === 'function' ? callback : function () {}; } function getArcOnMouseOut() { var callback = hasDonutType(c3.data.targets) ? __donut_onmouseout : __pie_onmouseout; return typeof callback === 'function' ? callback : function () {}; } //-- Domain --// function getYDomainMin(targets) { var ids = getTargetIds(targets), ys = getValuesAsIdKeyed(targets), j, k, baseId, idsInGroup, id, hasNegativeValue; if (__data_groups.length > 0) { hasNegativeValue = hasNegativeValueInTargets(targets); for (j = 0; j < __data_groups.length; j++) { // Determine baseId idsInGroup = __data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; }); if (idsInGroup.length === 0) { continue; } baseId = idsInGroup[0]; // Consider negative values if (hasNegativeValue && ys[baseId]) { ys[baseId].forEach(function (v, i) { ys[baseId][i] = v < 0 ? v : 0; }); } // Compute min for (k = 1; k < idsInGroup.length; k++) { id = idsInGroup[k]; if (! ys[id]) { continue; } ys[id].forEach(function (v, i) { if (getAxisId(id) === getAxisId(baseId) && ys[baseId] && !(hasNegativeValue && +v > 0)) { ys[baseId][i] += +v; } }); } } } return d3.min(Object.keys(ys).map(function (key) { return d3.min(ys[key]); })); } function getYDomainMax(targets) { var ids = getTargetIds(targets), ys = getValuesAsIdKeyed(targets), j, k, baseId, idsInGroup, id, hasPositiveValue; if (__data_groups.length > 0) { hasPositiveValue = hasPositiveValueInTargets(targets); for (j = 0; j < __data_groups.length; j++) { // Determine baseId idsInGroup = __data_groups[j].filter(function (id) { return ids.indexOf(id) >= 0; }); if (idsInGroup.length === 0) { continue; } baseId = idsInGroup[0]; // Consider positive values if (hasPositiveValue && ys[baseId]) { ys[baseId].forEach(function (v, i) { ys[baseId][i] = v > 0 ? v : 0; }); } // Compute max for (k = 1; k < idsInGroup.length; k++) { id = idsInGroup[k]; if (! ys[id]) { continue; } ys[id].forEach(function (v, i) { if (getAxisId(id) === getAxisId(baseId) && ys[baseId] && !(hasPositiveValue && +v < 0)) { ys[baseId][i] += +v; } }); } } } return d3.max(Object.keys(ys).map(function (key) { return d3.max(ys[key]); })); } function getYDomain(targets, axisId) { var yTargets = targets.filter(function (d) { return getAxisId(d.id) === axisId; }), yMin = axisId === 'y2' ? __axis_y2_min : __axis_y_min, yMax = axisId === 'y2' ? __axis_y2_max : __axis_y_max, yDomainMin = isValue(yMin) ? yMin : getYDomainMin(yTargets), yDomainMax = isValue(yMax) ? yMax : getYDomainMax(yTargets), domainLength, padding, padding_top, padding_bottom, center = axisId === 'y2' ? __axis_y2_center : __axis_y_center, yDomainAbs, widths, diff, ratio, showDataLabel = hasDataLabel() && __axis_rotated; if (yTargets.length === 0) { // use current domain if target of axisId is none return axisId === 'y2' ? y2.domain() : y.domain(); } if (yDomainMin === yDomainMax) { yDomainMin < 0 ? yDomainMax = 0 : yDomainMin = 0; } domainLength = Math.abs(yDomainMax - yDomainMin); padding = padding_top = padding_bottom = showDataLabel ? 0 : domainLength * 0.1; if (center) { yDomainAbs = Math.max(Math.abs(yDomainMin), Math.abs(yDomainMax)); yDomainMax = yDomainAbs - center; yDomainMin = center - yDomainAbs; } if (axisId === 'y' && __axis_y_padding) { padding_top = isValue(__axis_y_padding.top) ? __axis_y_padding.top : padding; padding_bottom = isValue(__axis_y_padding.bottom) ? __axis_y_padding.bottom : padding; } if (axisId === 'y2' && __axis_y2_padding) { padding_top = isValue(__axis_y2_padding.top) ? __axis_y2_padding.top : padding; padding_bottom = isValue(__axis_y2_padding.bottom) ? __axis_y2_padding.bottom : padding; } // add padding for data label if (showDataLabel) { widths = getDataLabelWidth(yDomainMin, yDomainMax); diff = diffDomain(y.range()); ratio = [widths[0] / diff, widths[1] / diff]; padding_top += domainLength * (ratio[1] / (1 - ratio[0] - ratio[1])); padding_bottom += domainLength * (ratio[0] / (1 - ratio[0] - ratio[1])); } // Bar chart with only positive values should be 0-based if (hasBarType(yTargets) && !hasNegativeValueInTargets(yTargets)) { padding_bottom = yDomainMin; } return [yDomainMin - padding_bottom, yDomainMax + padding_top]; } function getXDomainRatio(isSub) { var orgDiff = diffDomain(orgXDomain), currentDiff = diffDomain(x.domain()); return isSub || currentDiff === 0 ? 1 : orgDiff / currentDiff; } function getXDomainMin(targets) { return __axis_x_min ? __axis_x_min : d3.min(targets, function (t) { return d3.min(t.values, function (v) { return v.x; }); }); } function getXDomainMax(targets) { return __axis_x_max ? __axis_x_max : d3.max(targets, function (t) { return d3.max(t.values, function (v) { return v.x; }); }); } function getXDomainPadding(targets, domain) { var firstX = domain[0], lastX = domain[1], diff = Math.abs(firstX - lastX), maxDataCount, padding; if (isCategorized) { padding = 0; } else if (hasBarType(targets)) { maxDataCount = getMaxDataCount(); padding = maxDataCount > 1 ? (diff / (maxDataCount - 1)) / 2 : 0.5; } else { padding = diff * 0.01; } return padding; } function getXDomain(targets) { var xDomain = [getXDomainMin(targets), getXDomainMax(targets)], firstX = xDomain[0], lastX = xDomain[1], padding = getXDomainPadding(targets, xDomain), min = isTimeSeries ? new Date(firstX.getTime() - padding) : firstX - padding, max = isTimeSeries ? new Date(lastX.getTime() + padding) : lastX + padding; return [min, max]; } function diffDomain(d) { return d[1] - d[0]; } //-- Cache --// function hasCaches(ids) { for (var i = 0; i < ids.length; i++) { if (! (ids[i] in cache)) { return false; } } return true; } function addCache(id, target) { cache[id] = cloneTarget(target); } function getCaches(ids) { var targets = []; for (var i = 0; i < ids.length; i++) { if (ids[i] in cache) { targets.push(cloneTarget(cache[ids[i]])); } } return targets; } //-- Regions --// function regionStart(d) { return ('start' in d) ? x(isTimeSeries ? parseDate(d.start) : d.start) : 0; } function regionWidth(d) { var start = regionStart(d), end = ('end' in d) ? x(isTimeSeries ? parseDate(d.end) : d.end) : width, w = end - start; return (w < 0) ? 0 : w; } //-- Data --// function isX(key) { return (__data_x && key === __data_x) || (notEmpty(__data_xs) && hasValue(__data_xs, key)); } function isNotX(key) { return !isX(key); } function getXKey(id) { return __data_x ? __data_x : notEmpty(__data_xs) ? __data_xs[id] : null; } function getXValue(id, i) { return id in c3.data.x && c3.data.x[id] && c3.data.x[id][i] ? c3.data.x[id][i] : i; } function addXs(xs) { Object.keys(xs).forEach(function (id) { __data_xs[id] = xs[id]; }); } function addName(data) { var name; if (data) { name = __data_names[data.id]; data.name = name ? name : data.id; } return data; } function updateTargetX(targets, x) { targets.forEach(function (t) { t.values.forEach(function (v, i) { v.x = generateTargetX(x[i], t.id, i); }); c3.data.x[t.id] = x; }); } function updateTargetXs(targets, xs) { targets.forEach(function (t) { if (xs[t.id]) { updateTargetX([t], xs[t.id]); } }); } function generateTargetX(rawX, id, index) { var x; if (isTimeSeries) { x = rawX ? rawX instanceof Date ? rawX : parseDate(rawX) : parseDate(getXValue(id, index)); } else if (isCustomX && !isCategorized) { x = rawX ? +rawX : getXValue(id, index); } else { x = index; } return x; } function convertRowsToData(rows) { var keys = rows[0], new_row = {}, new_rows = [], i, j; for (i = 1; i < rows.length; i++) { new_row = {}; for (j = 0; j < rows[i].length; j++) { new_row[keys[j]] = rows[i][j]; } new_rows.push(new_row); } return new_rows; } function convertColumnsToData(columns) { var new_rows = [], i, j, key; for (i = 0; i < columns.length; i++) { key = columns[i][0]; for (j = 1; j < columns[i].length; j++) { if (isUndefined(new_rows[j - 1])) { new_rows[j - 1] = {}; } new_rows[j - 1][key] = columns[i][j]; } } return new_rows; } function convertDataToTargets(data) { var ids = d3.keys(data[0]).filter(isNotX), xs = d3.keys(data[0]).filter(isX), targets; // save x for update data by load when custom x and c3.x API ids.forEach(function (id) { var xKey = getXKey(id); if (isCustomX || isTimeSeries) { if (xs.indexOf(xKey) >= 0) { c3.data.x[id] = data.map(function (d) { return d[xKey]; }); } // MEMO: if no x included, use same x of current will be used } else { c3.data.x[id] = data.map(function (d, i) { return i; }); } }); // check x is defined ids.forEach(function (id) { if (!c3.data.x[id]) { throw new Error('x is not defined for id = "' + id + '".'); } }); // convert to target targets = ids.map(function (id, index) { var convertedId = __data_id_converter(id); return { id: convertedId, id_org: id, values: data.map(function (d, i) { var xKey = getXKey(id), rawX = d[xKey], x = generateTargetX(rawX, id, i); // use x as categories if custom x and categorized if (isCustomX && isCategorized && index === 0 && rawX) { if (i === 0) { __axis_x_categories = []; } __axis_x_categories.push(rawX); } // mark as x = undefined if value is undefined and filter to remove after mapped if (typeof d[id] === 'undefined') { x = undefined; } return {x: x, value: d[id] !== null && !isNaN(d[id]) ? +d[id] : null, id: convertedId}; }).filter(function (v) { return typeof v.x !== 'undefined'; }) }; }); // finish targets targets.forEach(function (t) { var i; // sort values by its x t.values = t.values.sort(function (v1, v2) { var x1 = v1.x || v1.x === 0 ? v1.x : Infinity, x2 = v2.x || v2.x === 0 ? v2.x : Infinity; return x1 - x2; }); // indexing each value i = 0; t.values.forEach(function (v) { v.index = i++; }); }); // set target types if (__data_type) { setTargetType(getTargetIds(targets).filter(function (id) { return ! (id in __data_types); }), __data_type); } // cache as original id keyed targets.forEach(function (d) { addCache(d.id_org, d); }); return targets; } function cloneTarget(target) { return { id : target.id, id_org : target.id_org, values : target.values.map(function (d) { return {x: d.x, value: d.value, id: d.id}; }) }; } function getPrevX(i) { return i > 0 && c3.data.targets[0].values[i - 1] ? c3.data.targets[0].values[i - 1].x : undefined; } function getNextX(i) { return i < getMaxDataCount() - 1 ? c3.data.targets[0].values[i + 1].x : undefined; } function getMaxDataCount() { return d3.max(c3.data.targets, function (t) { return t.values.length; }); } function getMaxDataCountTarget() { var length = c3.data.targets.length, max = 0, maxTarget; if (length > 1) { c3.data.targets.forEach(function (t) { if (t.values.length > max) { maxTarget = t; max = t.values.length; } }); } else { maxTarget = length ? c3.data.targets[0] : null; } return maxTarget; } function getTargetIds(targets) { targets = isUndefined(targets) ? c3.data.targets : targets; return targets.map(function (d) { return d.id; }); } function hasTarget(id) { var ids = getTargetIds(), i; for (i = 0; i < ids.length; i++) { if (ids[i] === id) { return true; } } return false; } function getTargets(filter) { return isDefined(filter) ? c3.data.targets.filter(filter) : c3.data.targets; } function isTargetToShow(targetId) { return hiddenTargetIds.indexOf(targetId) < 0; } function filterTargetsToShow(targets) { return targets.filter(function (t) { return isTargetToShow(t.id); }); } function addHiddenTargetIds(targetIds) { hiddenTargetIds = hiddenTargetIds.concat(targetIds); } function removeHiddenTargetIds(targetIds) { hiddenTargetIds = hiddenTargetIds.filter(function (id) { return targetIds.indexOf(id) < 0; }); } function getValuesAsIdKeyed(targets) { var ys = {}; targets.forEach(function (t) { ys[t.id] = []; t.values.forEach(function (v) { ys[t.id].push(v.value); }); }); return ys; } function checkValueInTargets(targets, checker) { var ids = Object.keys(targets), i, j, values; for (i = 0; i < ids.length; i++) { values = targets[ids[i]].values; for (j = 0; j < values.length; j++) { if (checker(values[j].value)) { return true; } } } return false; } function hasNegativeValueInTargets(targets) { return checkValueInTargets(targets, function (v) { return v < 0; }); } function hasPositiveValueInTargets(targets) { return checkValueInTargets(targets, function (v) { return v > 0; }); } function category(i) { return i < __axis_x_categories.length ? __axis_x_categories[i] : i; } function generateClass(prefix, targetId) { return " " + prefix + " " + prefix + getTargetSelectorSuffix(targetId); } function classText(d) { return generateClass(CLASS.text, d.id); } function classTexts(d) { return generateClass(CLASS.texts, d.id); } function classShape(d, i) { return generateClass(CLASS.shape, i); } function classShapes(d) { return generateClass(CLASS.shapes, d.id); } function classLine(d) { return classShapes(d) + generateClass(CLASS.line, d.id); } function classCircle(d, i) { return classShape(d, i) + generateClass(CLASS.circle, i); } function classCircles(d) { return classShapes(d) + generateClass(CLASS.circles, d.id); } function classBar(d, i) { return classShape(d, i) + generateClass(CLASS.bar, i); } function classBars(d) { return classShapes(d) + generateClass(CLASS.bars, d.id); } function classArc(d) { return classShapes(d.data) + generateClass(CLASS.arc, d.data.id); } function classArea(d) { return classShapes(d) + generateClass(CLASS.area, d.id); } function classRegion(d, i) { return generateClass(CLASS.region, i) + ' ' + ('class' in d ? d.class : ''); } function classEvent(d, i) { return generateClass(CLASS.eventRect, i); } function getTargetSelectorSuffix(targetId) { return targetId || targetId === 0 ? '-' + (targetId.replace ? targetId.replace(/([^a-zA-Z0-9-_])/g, '-') : targetId) : ''; } function selectorTarget(id) { return '.' + CLASS.target + getTargetSelectorSuffix(id); } function initialOpacity(d) { return d.value !== null && withoutFadeIn[d.id] ? 1 : 0; } function initialOpacityForText(d) { var targetOpacity = opacityForText(d); return initialOpacity(d) * targetOpacity; } function opacityForCircle(d) { return isValue(d.value) ? isScatterType(d) ? 0.5 : 1 : 0; } function opacityForText() { return hasDataLabel() ? 1 : 0; } function hasDataLabel() { if (typeof __data_labels === 'boolean' && __data_labels) { return true; } else if (typeof __data_labels === 'object' && notEmpty(__data_labels)) { return true; } return false; } function getDataLabelWidth(min, max) { var widths = [], paddingCoef = 1.3; d3.select('svg').selectAll('.dummy') .data([min, max]) .enter().append('text') .text(function (d) { return d; }) .each(function (d, i) { var box = this.getBBox(); widths[i] = box.width * paddingCoef; }) .remove(); return widths; } function defaultValueFormat(v) { var yFormat = __axis_y_tick_format ? __axis_y_tick_format : function (v) { return isValue(v) ? +v : ""; }; return yFormat(v); } function defaultArcValueFormat(v, ratio) { return (ratio * 100).toFixed(1) + '%'; } function formatByAxisId(id) { var defaultFormat = function (v) { return isValue(v) ? +v : ""; }, axisId = getAxisId(id), format = defaultFormat; // find format according to axis id if (typeof __data_labels.format === 'function') { format = __data_labels.format; } else if (typeof __data_labels.format === 'object') { if (typeof __data_labels.format[axisId] === 'function') { format = __data_labels.format[axisId]; } } return format; } function xx(d) { return d ? x(d.x) : null; } function xv(d) { return x(isTimeSeries ? parseDate(d.value) : d.value); } function yv(d) { return y(d.value); } function subxx(d) { return subX(d.x); } function findSameXOfValues(values, index) { var i, targetX = values[index].x, sames = []; for (i = index - 1; i >= 0; i--) { if (targetX !== values[i].x) { break; } sames.push(values[i]); } for (i = index; i < values.length; i++) { if (targetX !== values[i].x) { break; } sames.push(values[i]); } return sames; } function findClosestOfValues(values, pos, _min, _max) { // MEMO: values must be sorted by x var min = _min ? _min : 0, max = _max ? _max : values.length - 1, med = Math.floor((max - min) / 2) + min, value = values[med], diff = x(value.x) - pos[0], candidates; // Update range for search diff > 0 ? max = med : min = med; // if candidates are two closest min and max, stop recursive call if ((max - min) === 1 || (min === 0 && max === 0)) { // Get candidates that has same min and max index candidates = []; if (values[min].x) { candidates = candidates.concat(findSameXOfValues(values, min)); } if (values[max].x) { candidates = candidates.concat(findSameXOfValues(values, max)); } // Determine the closest and return return findClosest(candidates, pos); } return findClosestOfValues(values, pos, min, max); } function findClosestFromTargets(targets, pos) { var candidates; // map to array of closest points of each target candidates = targets.map(function (target) { return findClosestOfValues(target.values, pos); }); // decide closest point and return return findClosest(candidates, pos); } function findClosest(values, pos) { var minDist, closest; values.forEach(function (v) { var d = dist(v, pos); if (d < minDist || ! minDist) { minDist = d; closest = v; } }); return closest; } function getPathBox(path) { var box = path.getBoundingClientRect(), items = [path.pathSegList.getItem(0), path.pathSegList.getItem(1)], minX = items[0].x, minY = Math.min(items[0].y, items[1].y); return {x: minX, y: minY, width: box.width, height: box.height}; } function isOrderDesc() { return __data_order && __data_order.toLowerCase() === 'desc'; } function isOrderAsc() { return __data_order && __data_order.toLowerCase() === 'asc'; } function orderTargets(targets) { var orderAsc = isOrderAsc(), orderDesc = isOrderDesc(); if (orderAsc || orderDesc) { targets.sort(function (t1, t2) { var reducer = function (p, c) { return p + Math.abs(c.value); }; var t1Sum = t1.values.reduce(reducer, 0), t2Sum = t2.values.reduce(reducer, 0); return orderAsc ? t2Sum - t1Sum : t1Sum - t2Sum; }); } else if (typeof __data_order === 'function') { targets.sort(__data_order); } // TODO: accept name array for order return targets; } //-- Tooltip --// function showTooltip(selectedData, mouse) { var tWidth, tHeight; var svgLeft, tooltipLeft, tooltipRight, tooltipTop, chartRight; var forArc = hasArcType(c3.data.targets); var valueFormat = forArc ? defaultArcValueFormat : defaultValueFormat; var dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }); if (! __tooltip_show) { return; } // don't show tooltip when no data if (dataToShow.length === 0) { return; } // Construct tooltip tooltip.html(__tooltip_contents(selectedData, getXAxisTickFormat(), valueFormat, color)).style("display", "block"); // Get tooltip dimensions tWidth = tooltip.property('offsetWidth'); tHeight = tooltip.property('offsetHeight'); // Determin tooltip position if (forArc) { tooltipLeft = (width / 2) + mouse[0]; tooltipTop = (height / 2) + mouse[1] + 20; } else { if (__axis_rotated) { svgLeft = getSvgLeft(); tooltipLeft = svgLeft + mouse[0] + 100; tooltipRight = tooltipLeft + tWidth; chartRight = getCurrentWidth() - getCurrentPaddingRight(); tooltipTop = x(dataToShow[0].x) + 20; } else { svgLeft = getSvgLeft(); tooltipLeft = svgLeft + getCurrentPaddingLeft() + x(dataToShow[0].x) + 20; tooltipRight = tooltipLeft + tWidth; chartRight = svgLeft + getCurrentWidth() - getCurrentPaddingRight(); tooltipTop = mouse[1] + 15; } if (tooltipRight > chartRight) { tooltipLeft -= tWidth + 60; } if (tooltipTop + tHeight > getCurrentHeight()) { tooltipTop -= tHeight + 30; } } // Set tooltip tooltip .style("top", tooltipTop + "px") .style("left", tooltipLeft + 'px'); } function hideTooltip() { tooltip.style("display", "none"); } function showXGridFocus(selectedData) { var dataToShow = selectedData.filter(function (d) { return d && isValue(d.value); }); if (! __tooltip_show) { return; } // Hide when scatter plot exists if (hasScatterType(c3.data.targets) || hasArcType(c3.data.targets)) { return; } main.selectAll('line.' + CLASS.xgridFocus) .style("visibility", "visible") .data([dataToShow[0]]) .attr(__axis_rotated ? 'y1' : 'x1', xx) .attr(__axis_rotated ? 'y2' : 'x2', xx); } function hideXGridFocus() { main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden"); } //-- Circle --// function circleX(d) { return d.x || d.x === 0 ? x(d.x) : null; } function circleY(d) { return getYScale(d.id)(d.value); } //-- Bar --// function getBarIndices() { var indices = {}, i = 0, j, k; filterTargetsToShow(getTargets(isBarType)).forEach(function (d) { for (j = 0; j < __data_groups.length; j++) { if (__data_groups[j].indexOf(d.id) < 0) { continue; } for (k = 0; k < __data_groups[j].length; k++) { if (__data_groups[j][k] in indices) { indices[d.id] = indices[__data_groups[j][k]]; break; } } } if (isUndefined(indices[d.id])) { indices[d.id] = i++; } }); indices.__max__ = i - 1; return indices; } function getBarX(barW, barTargetsNum, barIndices, isSub) { var scale = isSub ? subX : x; return function (d) { var barIndex = d.id in barIndices ? barIndices[d.id] : 0; return d.x || d.x === 0 ? scale(d.x) - barW * (barTargetsNum / 2 - barIndex) : 0; }; } function getBarY(isSub) { return function (d) { var scale = isSub ? getSubYScale(d.id) : getYScale(d.id); return scale(d.value); }; } function getBarOffset(barIndices, isSub) { var targets = orderTargets(filterTargetsToShow(getTargets(isBarType))), targetIds = targets.map(function (t) { return t.id; }); return function (d, i) { var scale = isSub ? getSubYScale(d.id) : getYScale(d.id), y0 = scale(0), offset = y0; targets.forEach(function (t) { if (t.id === d.id || barIndices[t.id] !== barIndices[d.id]) { return; } if (targetIds.indexOf(t.id) < targetIds.indexOf(d.id) && t.values[i].value * d.value > 0) { offset += scale(t.values[i].value) - y0; } }); return offset; }; } function getBarW(axis, barTargetsNum) { return __bar_width ? __bar_width : barTargetsNum ? (axis.tickOffset() * 2 * __bar_width_ratio) / barTargetsNum : 0; } //-- Type --// function setTargetType(targets, type) { var targetIds = isUndefined(targets) ? getTargetIds() : targets; if (typeof targetIds === 'string') { targetIds = [targetIds]; } for (var i = 0; i < targetIds.length; i++) { withoutFadeIn[targetIds[i]] = (type === __data_types[targetIds[i]]); __data_types[targetIds[i]] = type; } } function hasType(targets, type) { var has = false; targets.forEach(function (t) { if (__data_types[t.id] === type) { has = true; } if (!(t.id in __data_types) && type === 'line') { has = true; } }); return has; } /* not used function hasLineType(targets) { return hasType(targets, 'line'); } */ function hasBarType(targets) { return hasType(targets, 'bar'); } function hasScatterType(targets) { return hasType(targets, 'scatter'); } function hasPieType(targets) { return hasType(targets, 'pie'); } function hasDonutType(targets) { return hasType(targets, 'donut'); } function hasArcType(targets) { return hasPieType(targets) || hasDonutType(targets); } function isLineType(d) { var id = (typeof d === 'string') ? d : d.id; return !(id in __data_types) || __data_types[id] === 'line' || __data_types[id] === 'spline' || __data_types[id] === 'area' || __data_types[id] === 'area-spline'; } function isSplineType(d) { var id = (typeof d === 'string') ? d : d.id; return __data_types[id] === 'spline' || __data_types[id] === 'area-spline'; } function isBarType(d) { var id = (typeof d === 'string') ? d : d.id; return __data_types[id] === 'bar'; } function isScatterType(d) { var id = (typeof d === 'string') ? d : d.id; return __data_types[id] === 'scatter'; } function isPieType(d) { var id = (typeof d === 'string') ? d : d.id; return __data_types[id] === 'pie'; } function isDonutType(d) { var id = (typeof d === 'string') ? d : d.id; return __data_types[id] === 'donut'; } function isArcType(d) { return isPieType(d) || isDonutType(d); } /* not used function lineData(d) { return isLineType(d) ? d.values : []; } function scatterData(d) { return isScatterType(d) ? d.values : []; } */ function barData(d) { return isBarType(d) ? d.values : []; } function lineOrScatterData(d) { return isLineType(d) || isScatterType(d) ? d.values : []; } function barOrLineData(d) { return isBarType(d) || isLineType(d) ? d.values : []; } //-- Color --// function generateColor(_colors, _pattern) { var ids = [], colors = _colors, pattern = notEmpty(_pattern) ? _pattern : ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']; //same as d3.scale.category10() return function (id) { // if specified, choose that color if (id in colors) { return _colors[id]; } // if not specified, choose from pattern if (ids.indexOf(id) === -1) { ids.push(id); } return pattern[ids.indexOf(id) % pattern.length]; }; } //-- Date --// function parseDate(date) { var parsedDate; if (!date) { throw Error(date + " can not be parsed as d3.time with format " + __data_x_format + ". Maybe 'x' of this data is not defined. See data.x or data.xs option."); } parsedDate = __data_x_format ? d3.time.format(__data_x_format).parse(date) : new Date(date); if (!parsedDate) { throw Error("Failed to parse '" + date + "' with format " + __data_x_format); } return parsedDate; } //-- Util --// function isWithinCircle(_this, _r) { var mouse = d3.mouse(_this), d3_this = d3.select(_this); var cx = d3_this.attr("cx") * 1, cy = d3_this.attr("cy") * 1; return Math.sqrt(Math.pow(cx - mouse[0], 2) + Math.pow(cy - mouse[1], 2)) < _r; } function isWithinBar(_this) { var mouse = d3.mouse(_this), box = _this.getBBox(); var x = box.x, y = box.y, w = box.width, h = box.height, offset = 2; var sx = x - offset, ex = x + w + offset, sy = y + h + offset, ey = y - offset; return sx < mouse[0] && mouse[0] < ex && ey < mouse[1] && mouse[1] < sy; } function isWithinRegions(x, regions) { var i; for (i = 0; i < regions.length; i++) { if (regions[i].start < x && x <= regions[i].end) { return true; } } return false; } function notEmpty(o) { return Object.keys(o).length > 0; } function hasValue(dict, value) { var found = false; Object.keys(dict).forEach(function (key) { if (dict[key] === value) { found = true; } }); return found; } function dist(data, pos) { return Math.pow(x(data.x) - pos[0], 2) + Math.pow(y(data.value) - pos[1], 2); } function endall(transition, callback) { var n = 0; transition .each(function () { ++n; }) .each("end", function () { if (!--n) { callback.apply(this, arguments); } }); } //-- Selection --// function selectPoint(target, d, i) { __data_onselected(d, target.node()); // add selected-circle on low layer g main.select('.' + CLASS.selectedCircles + getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i) .data([d]) .enter().append('circle') .attr("class", function () { return generateClass(CLASS.selectedCircle, i); }) .attr("cx", __axis_rotated ? circleY : circleX) .attr("cy", __axis_rotated ? circleX : circleY) .attr("stroke", function () { return color(d.id); }) .attr("r", __point_select_r * 1.4) .transition().duration(100) .attr("r", __point_select_r); } function unselectPoint(target, d, i) { __data_onunselected(d, target.node()); // remove selected-circle from low layer g main.select('.' + CLASS.selectedCircles + getTargetSelectorSuffix(d.id)).selectAll('.' + CLASS.selectedCircle + '-' + i) .transition().duration(100).attr('r', 0) .remove(); } function togglePoint(selected, target, d, i) { selected ? selectPoint(target, d, i) : unselectPoint(target, d, i); } function selectBar(target, d) { __data_onselected(d, target.node()); target.transition().duration(100).style("fill", function () { return d3.rgb(color(d.id)).darker(1); }); } function unselectBar(target, d) { __data_onunselected(d, target.node()); target.transition().duration(100).style("fill", function () { return color(d.id); }); } function toggleBar(selected, target, d, i) { selected ? selectBar(target, d, i) : unselectBar(target, d, i); } function filterRemoveNull(data) { return data.filter(function (d) { return isValue(d.value); }); } //-- Shape --// function getCircles(i, id) { return (id ? main.selectAll('.' + CLASS.circles + getTargetSelectorSuffix(id)) : main).selectAll('.' + CLASS.circle + (isValue(i) ? '-' + i : '')); } function expandCircles(i, id) { getCircles(i, id) .classed(CLASS.EXPANDED, true) .attr('r', __point_focus_expand_r); } function unexpandCircles(i) { getCircles(i) .filter(function () { return d3.select(this).classed(CLASS.EXPANDED); }) .classed(CLASS.EXPANDED, false) .attr('r', __point_r); } function getBars(i) { return main.selectAll('.' + CLASS.bar + (isValue(i) ? '-' + i : '')); } function expandBars(i) { getBars(i).classed(CLASS.EXPANDED, true); } function unexpandBars(i) { getBars(i).classed(CLASS.EXPANDED, false); } // For main region var lineOnMain = (function () { var line = d3.svg.line() .x(__axis_rotated ? function (d) { return getYScale(d.id)(d.value); } : xx) .y(__axis_rotated ? xx : function (d) { return getYScale(d.id)(d.value); }); return function (d) { var data = filterRemoveNull(d.values), x0, y0; if (isLineType(d)) { isSplineType(d) ? line.interpolate("cardinal") : line.interpolate("linear"); return __data_regions[d.id] ? lineWithRegions(data, x, getYScale(d.id), __data_regions[d.id]) : line(data); } else { x0 = x(data[0].x); y0 = getYScale(d.id)(data[0].value); return __axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0; } }; })(); var areaOnMain = (function () { var area; if (__axis_rotated) { area = d3.svg.area() .x0(function (d) { return getYScale(d.id)(0); }) .x1(function (d) { return getYScale(d.id)(d.value); }) .y(xx); } else { area = d3.svg.area() .x(xx) .y0(function (d) { return getYScale(d.id)(0); }) .y1(function (d) { return getYScale(d.id)(d.value); }); } return function (d) { var data = filterRemoveNull(d.values), x0, y0; if (hasType([d], 'area') || hasType([d], 'area-spline')) { isSplineType(d) ? area.interpolate("cardinal") : area.interpolate("linear"); return area(data); } else { x0 = x(data[0].x); y0 = getYScale(d.id)(data[0].value); return __axis_rotated ? "M " + y0 + " " + x0 : "M " + x0 + " " + y0; } }; })(); function generateDrawBar(barIndices, isSub) { var getPoints = generateGetBarPoints(barIndices, isSub); return function (d, i) { // 4 points that make a bar var points = getPoints(d, i); // switch points if axis is rotated, not applicable for sub chart var indexX = __axis_rotated ? 1 : 0; var indexY = __axis_rotated ? 0 : 1; var path = 'M ' + points[0][indexX] + ',' + points[0][indexY] + ' ' + 'L' + points[1][indexX] + ',' + points[1][indexY] + ' ' + 'L' + points[2][indexX] + ',' + points[2][indexY] + ' ' + 'L' + points[3][indexX] + ',' + points[3][indexY] + ' ' + 'z'; return path; }; } function generateXYForText(barIndices, forX) { var getPoints = generateGetBarPoints(barIndices, false), getter = forX ? getXForText : getYForText; return function (d, i) { return getter(getPoints(d, i), d, this); }; } function getXForText(points, d) { var padding; if (__axis_rotated) { padding = isBarType(d) ? 4 : 6; return points[2][1] + padding * (d.value < 0 ? -1 : 1); } else { return points[0][0] + (points[2][0] - points[0][0]) / 2; } } function getYForText(points, d, textElement) { var box = textElement.getBBox(); if (__axis_rotated) { return (points[0][0] + points[2][0] + box.height * 0.6) / 2; } else { return points[2][1] + (d.value < 0 ? box.height : isBarType(d) ? -3 : -6); } } function generateGetBarPoints(barIndices, isSub) { var barTargetsNum = barIndices.__max__ + 1, barW = getBarW(xAxis, barTargetsNum), x = getBarX(barW, barTargetsNum, barIndices, !!isSub), y = getBarY(!!isSub), barOffset = getBarOffset(barIndices, !!isSub), yScale = isSub ? getSubYScale : getYScale; return function (d, i) { var y0 = yScale(d.id)(0), offset = barOffset(d, i) || y0, // offset is for stacked bar chart posX = x(d), posY = y(d); // fix posY not to overflow opposite quadrant if (__axis_rotated) { if ((d.value > 0 && posY < offset) || (d.value < 0 && posY > offset)) { posY = offset; } } // 4 points that make a bar return [ [posX, offset], [posX, posY - (y0 - offset)], [posX + barW, posY - (y0 - offset)], [posX + barW, offset] ]; }; } // For brush region var lineOnSub = (function () { var line = d3.svg.line() .x(__axis_rotated ? function (d) { return getSubYScale(d.id)(d.value); } : subxx) .y(__axis_rotated ? subxx : function (d) { return getSubYScale(d.id)(d.value); }); return function (d) { var data = filterRemoveNull(d.values); return isLineType(d) ? line(data) : "M " + subX(data[0].x) + " " + getSubYScale(d.id)(data[0].value); }; })(); function lineWithRegions(d, x, y, _regions) { var prev = -1, i, j; var s = "M", sWithRegion; var xp, yp, dx, dy, dd, diff; var xValue, yValue; var regions = []; // Check start/end of regions if (isDefined(_regions)) { for (i = 0; i < _regions.length; i++) { regions[i] = {}; if (isUndefined(_regions[i].start)) { regions[i].start = d[0].x; } else { regions[i].start = isTimeSeries ? parseDate(_regions[i].start) : _regions[i].start; } if (isUndefined(_regions[i].end)) { regions[i].end = d[d.length - 1].x; } else { regions[i].end = isTimeSeries ? parseDate(_regions[i].end) : _regions[i].end; } } } // Set scales xValue = __axis_rotated ? function (d) { return y(d.value); } : function (d) { return x(d.x); }; yValue = __axis_rotated ? function (d) { return x(d.x); } : function (d) { return y(d.value); }; // Define svg generator function for region if (isTimeSeries) { sWithRegion = function (d0, d1, j, diff) { var x0 = d0.x.getTime(), x_diff = d1.x - d0.x, xv0 = new Date(x0 + x_diff * j), xv1 = new Date(x0 + x_diff * (j + diff)); return "M" + x(xv0) + " " + y(yp(j)) + " " + x(xv1) + " " + y(yp(j + diff)); }; } else { sWithRegion = function (d0, d1, j, diff) { return "M" + x(xp(j)) + " " + y(yp(j)) + " " + x(xp(j + diff)) + " " + y(yp(j + diff)); }; } // Generate for (i = 0; i < d.length; i++) { // Draw as normal if (isUndefined(regions) || ! isWithinRegions(d[i].x, regions)) { s += " " + xValue(d[i]) + " " + yValue(d[i]); } // Draw with region // TODO: Fix for horizotal charts else { xp = getX(d[i - 1].x, d[i].x); yp = getY(d[i - 1].value, d[i].value); dx = x(d[i].x) - x(d[i - 1].x); dy = y(d[i].value) - y(d[i - 1].value); dd = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2)); diff = 2 / dd; var diffx2 = diff * 2; for (j = diff; j <= 1; j += diffx2) { s += sWithRegion(d[i - 1], d[i], j, diff); } } prev = d[i].x; } return s; } //-- Define brush/zoom -// var brush, zoom = function () {}; brush = d3.svg.brush().on("brush", redrawForBrush); brush.update = function () { if (context) { context.select('.' + CLASS.brush).call(this); } return this; }; brush.scale = function (scale) { return __axis_rotated ? this.y(scale) : this.x(scale); }; if (__zoom_enabled) { zoom = d3.behavior.zoom() .on("zoomstart", function () { zoom.altDomain = d3.event.sourceEvent.altKey ? x.orgDomain() : null; }) .on("zoom", __zoom_enabled ? redrawForZoom : null); zoom.scale = function (scale) { return __axis_rotated ? this.y(scale) : this.x(scale); }; zoom.orgScaleExtent = function () { var extent = __zoom_extent ? __zoom_extent : [1, 10]; return [extent[0], Math.max(getMaxDataCount() / extent[1], extent[1])]; }; zoom.updateScaleExtent = function () { var ratio = diffDomain(x.orgDomain()) / diffDomain(orgXDomain), extent = this.orgScaleExtent(); this.scaleExtent([extent[0] * ratio, extent[1] * ratio]); return this; }; } /*-- Draw Chart --*/ // for svg elements var svg, defs, main, context, legend, tooltip, selectChart; // for brush area culculation var orgXDomain; // for save value var orgAreaOpacity, withoutFadeIn = {}; function init(data) { var eventRect, grid; var i; selectChart = d3.select(__bindto); if (selectChart.empty()) { throw new Error('No bind element found. Check the selector specified by "bindto" and existance of that element. Default "bindto" is "#chart".'); } else { selectChart.html(""); } // Set class selectChart.classed("c3", true); // Init data as targets c3.data.x = {}; c3.data.targets = convertDataToTargets(data); // TODO: set names if names not specified // Init sizes and scales updateSizes(); updateScales(); // Set domains for each scale x.domain(d3.extent(getXDomain(c3.data.targets))); y.domain(getYDomain(c3.data.targets, 'y')); y2.domain(getYDomain(c3.data.targets, 'y2')); subX.domain(x.domain()); subY.domain(y.domain()); subY2.domain(y2.domain()); // Save original x domain for zoom update orgXDomain = x.domain(); // Set initialized scales to brush and zoom brush.scale(subX); if (__zoom_enabled) { zoom.scale(x); } /*-- Basic Elements --*/ // Define svgs svg = selectChart.append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .on('mouseenter', __onenter) .on('mouseleave', __onleave); // Define defs defs = svg.append("defs"); defs.append("clipPath") .attr("id", clipId) .append("rect") .attr("width", width) .attr("height", height); defs.append("clipPath") .attr("id", "xaxis-clip") .append("rect") .attr("x", getXAxisClipX) .attr("y", getXAxisClipY) .attr("width", getXAxisClipWidth) .attr("height", getXAxisClipHeight); defs.append("clipPath") .attr("id", "yaxis-clip") .append("rect") .attr("x", getYAxisClipX) .attr("y", getYAxisClipY) .attr("width", getYAxisClipWidth) .attr("height", getYAxisClipHeight); // Define regions main = svg.append("g").attr("transform", translate.main); context = __subchart_show ? svg.append("g").attr("transform", translate.context) : null; legend = __legend_show ? svg.append("g").attr("transform", translate.legend) : null; // Define tooltip tooltip = d3.select(__bindto) .style("position", "relative") .append("div") .style("position", "absolute") .style("pointer-events", "none") .style("z-index", "10") .style("display", "none"); /*-- Main Region --*/ // Add Axis main.append("g") .attr("class", CLASS.axisX) .attr("clip-path", __axis_rotated ? "" : getClipPath("xaxis-clip")) .attr("transform", translate.x) .append("text") .attr("class", CLASS.axisXLabel) .attr("transform", __axis_rotated ? "rotate(-90)" : "") .attr("dx", dxForXAxisLabel) .attr("dy", dyForXAxisLabel) .style("text-anchor", textAnchorForXAxisLabel); if (__axis_y_show) { main.append("g") .attr("class", CLASS.axisY) .attr("clip-path", __axis_rotated ? getClipPath("yaxis-clip") : "") .append("text") .attr("class", CLASS.axisYLabel) .attr("transform", __axis_rotated ? "" : "rotate(-90)") .attr("dx", dxForYAxisLabel) .attr("dy", dyForYAxisLabel) .style("text-anchor", textAnchorForYAxisLabel); } if (__axis_y2_show) { main.append("g") .attr("class", CLASS.axisY2) // clip-path? .attr("transform", translate.y2) .append("text") .attr("class", CLASS.axisY2Label) .attr("transform", __axis_rotated ? "" : "rotate(-90)") .attr("dx", dxForY2AxisLabel) .style("text-anchor", textAnchorForY2AxisLabel); } // Grids grid = main.append('g') .attr("clip-path", clipPath) .attr('class', CLASS.grid); // X-Grid if (__grid_x_show) { grid.append("g").attr("class", CLASS.xgrids); } if (notEmpty(__grid_x_lines)) { grid.append('g').attr("class", CLASS.xgridLines); } if (__point_focus_line_enabled) { grid.append('g') .attr("class", CLASS.xgridFocus) .append('line') .attr('class', CLASS.xgridFocus) .attr("x1", __axis_rotated ? 0 : -10) .attr("x2", __axis_rotated ? width : -10) .attr("y1", __axis_rotated ? -10 : margin.top) .attr("y2", __axis_rotated ? -10 : height); } // Y-Grid if (__grid_y_show) { grid.append('g').attr('class', CLASS.ygrids); } if (notEmpty(__grid_y_lines)) { grid.append('g').attr('class', CLASS.ygridLines); } // Regions main.append('g') .attr("clip-path", clipPath) .attr("class", CLASS.regions); // Define g for chart area main.append('g') .attr("clip-path", clipPath) .attr('class', CLASS.chart); // Cover whole with rects for events eventRect = main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.eventRects) .style('fill-opacity', 0) .style('cursor', __zoom_enabled ? __axis_rotated ? 'ns-resize' : 'ew-resize' : null); // Define g for bar chart area main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartBars); // Define g for line chart area main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartLines); // Define g for arc chart area main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartArcs) .attr("transform", translate.arc) .append('text') .attr('class', CLASS.chartArcsTitle) .style("text-anchor", "middle") .text(getArcTitle()); main.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartTexts); if (__zoom_enabled) { // TODO: __zoom_privileged here? // if zoom privileged, insert rect to forefront main.insert('rect', __zoom_privileged ? null : 'g.' + CLASS.grid) .attr('class', CLASS.zoomRect) .attr('width', width) .attr('height', height) .style('opacity', 0) .style('cursor', __axis_rotated ? 'ns-resize' : 'ew-resize') .call(zoom).on("dblclick.zoom", null); } // Set default extent if defined if (__axis_x_default) { brush.extent(typeof __axis_x_default !== 'function' ? __axis_x_default : __axis_x_default(getXDomain())); } /*-- Context Region --*/ if (__subchart_show) { // Define g for chart area context.append('g') .attr("clip-path", clipPath) .attr('class', CLASS.chart); // Define g for bar chart area context.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartBars); // Define g for line chart area context.select('.' + CLASS.chart).append("g") .attr("class", CLASS.chartLines); // Add extent rect for Brush context.append("g") .attr("clip-path", clipPath) .attr("class", CLASS.brush) .call(brush) .selectAll("rect") .attr(__axis_rotated ? "width" : "height", __axis_rotated ? width2 : height2); // ATTENTION: This must be called AFTER chart added // Add Axis context.append("g") .attr("class", CLASS.axisX) .attr("transform", translate.subx) .attr("clip-path", __axis_rotated ? "" : getClipPath("xaxis-clip")); } // Set targets updateTargets(c3.data.targets); // Update ticks for width calculation if (__axis_rotated) { main.select('.' + CLASS.axisX).style("opacity", 0).call(xAxis); } else { main.select('.' + CLASS.axisY).style("opacity", 0).call(yAxis); main.select('.' + CLASS.axisY2).style("opacity", 0).call(yAxis2); } // Draw with targets updateAndRedraw({withTransform: true, withLegend: true, durationForAxis: 0}); // Show tooltip if needed if (__tooltip_init_show) { if (isTimeSeries && typeof __tooltip_init_x === 'string') { __tooltip_init_x = parseDate(__tooltip_init_x); for (i = 0; i < c3.data.targets[0].values.length; i++) { if ((c3.data.targets[0].values[i].x - __tooltip_init_x) === 0) { break; } } __tooltip_init_x = i; } tooltip.html(__tooltip_contents(c3.data.targets.map(function (d) { return addName(d.values[__tooltip_init_x]); }), getXAxisTickFormat(), defaultValueFormat, color)); tooltip.style("top", __tooltip_init_position.top) .style("left", __tooltip_init_position.left) .style("display", "block"); } // Bind resize event if (window.onresize == null) { window.onresize = generateResize(); } if (window.onresize.add) { window.onresize.add(function () { updateAndRedraw({withTransition: false, withLegend: true}); }); } } function generateEventRectsForSingleX(eventRectEnter) { eventRectEnter.append("rect") .attr("class", classEvent) .style("cursor", __data_selection_enabled && __data_selection_grouped ? "pointer" : null) .on('mouseover', function (_, i) { if (dragging) { return; } // do nothing if dragging if (hasArcType(c3.data.targets)) { return; } var selectedData = c3.data.targets.map(function (d) { return addName(d.values[i]); }); var j, newData; // Sort selectedData as names order if (Object.keys(__data_names).length > 0) { newData = []; for (var id in __data_names) { for (j = 0; j < selectedData.length; j++) { if (selectedData[j].id === id) { newData.push(selectedData[j]); selectedData.shift(j); break; } } } selectedData = newData.concat(selectedData); // Add remained } // Expand shapes if needed if (__point_focus_expand_enabled) { expandCircles(i); } expandBars(i); // Call event handler main.selectAll('.' + CLASS.shape + '-' + i).each(function (d) { __data_onenter(d); }); }) .on('mouseout', function (_, i) { if (hasArcType(c3.data.targets)) { return; } hideXGridFocus(); hideTooltip(); // Undo expanded shapes unexpandCircles(i); unexpandBars(); // Call event handler main.selectAll('.' + CLASS.shape + '-' + i).each(function (d) { __data_onleave(d); }); }) .on('mousemove', function (_, i) { var selectedData; if (dragging) { return; } // do nothing when dragging if (hasArcType(c3.data.targets)) { return; } // Show tooltip selectedData = filterTargetsToShow(c3.data.targets).map(function (d) { return addName(d.values[i]); }); showTooltip(selectedData, d3.mouse(this)); // Show xgrid focus line showXGridFocus(selectedData); if (! __data_selection_enabled) { return; } if (__data_selection_grouped) { return; } // nothing to do when grouped main.selectAll('.' + CLASS.shape + '-' + i) .filter(function (d) { return __data_selection_isselectable(d); }) .each(function () { var _this = d3.select(this).classed(CLASS.EXPANDED, true); if (this.nodeName === 'circle') { _this.attr('r', __point_focus_expand_r); } svg.select('.' + CLASS.eventRect + '-' + i).style('cursor', null); }) .filter(function () { if (this.nodeName === 'circle') { return isWithinCircle(this, __point_select_r); } else if (this.nodeName === 'path') { return isWithinBar(this); } }) .each(function () { var _this = d3.select(this); if (! _this.classed(CLASS.EXPANDED)) { _this.classed(CLASS.EXPANDED, true); if (this.nodeName === 'circle') { _this.attr('r', __point_select_r); } } svg.select('.' + CLASS.eventRect + '-' + i).style('cursor', 'pointer'); }); }) .on('click', function (_, i) { if (hasArcType(c3.data.targets)) { return; } if (cancelClick) { cancelClick = false; return; } main.selectAll('.' + CLASS.shape + '-' + i).each(function (d) { toggleShape(this, d, i); }); }) .call( d3.behavior.drag().origin(Object) .on('drag', function () { drag(d3.mouse(this)); }) .on('dragstart', function () { dragstart(d3.mouse(this)); }) .on('dragend', function () { dragend(); }) ) .call(zoom).on("dblclick.zoom", null); } function generateEventRectsForMultipleXs(eventRectEnter) { eventRectEnter.append('rect') .attr('x', 0) .attr('y', 0) .attr('width', width) .attr('height', height) .attr('class', CLASS.eventRect) .on('mouseout', function () { if (hasArcType(c3.data.targets)) { return; } hideXGridFocus(); hideTooltip(); unexpandCircles(); }) .on('mousemove', function () { var mouse, closest, selectedData; if (dragging) { return; } // do nothing when dragging if (hasArcType(c3.data.targets)) { return; } mouse = d3.mouse(this); closest = findClosestFromTargets(c3.data.targets, mouse); // show tooltip when cursor is close to some point selectedData = [addName(closest)]; showTooltip(selectedData, mouse); // expand points if (__point_focus_expand_enabled) { unexpandCircles(); expandCircles(closest.index, closest.id); } // Show xgrid focus line showXGridFocus(selectedData); // Show cursor as pointer if point is close to mouse position if (dist(closest, mouse) < 100) { svg.select('.' + CLASS.eventRect).style('cursor', 'pointer'); if (!mouseover) { __data_onenter(closest); mouseover = true; } } else { svg.select('.' + CLASS.eventRect).style('cursor', null); __data_onleave(closest); mouseover = false; } }) .on('click', function () { var mouse, closest; if (hasArcType(c3.data.targets)) { return; } mouse = d3.mouse(this); closest = findClosestFromTargets(c3.data.targets, mouse); // select if selection enabled if (dist(closest, mouse) < 100) { main.select('.' + CLASS.circles + '-' + getTargetSelectorSuffix(closest.id)).select('.' + CLASS.circle + '-' + closest.index).each(function () { toggleShape(this, closest, closest.index); }); } }) .call( d3.behavior.drag().origin(Object) .on('drag', function () { drag(d3.mouse(this)); }) .on('dragstart', function () { dragstart(d3.mouse(this)); }) .on('dragend', function () { dragend(); }) ) .call(zoom).on("dblclick.zoom", null); } function toggleShape(target, d, i) { var shape = d3.select(target), isSelected = shape.classed(CLASS.SELECTED); var isWithin = false, toggle; if (target.nodeName === 'circle') { isWithin = isWithinCircle(target, __point_select_r * 1.5); toggle = togglePoint; } else if (target.nodeName === 'path') { isWithin = isWithinBar(target); toggle = toggleBar; } if (__data_selection_grouped || isWithin) { if (__data_selection_enabled && __data_selection_isselectable(d)) { if (!__data_selection_multiple) { main.selectAll('.' + CLASS.shapes + (__data_selection_grouped ? getTargetSelectorSuffix(d.id) : "")).selectAll('.' + CLASS.shape).each(function (d, i) { var shape = d3.select(this); if (shape.classed(CLASS.SELECTED)) { toggle(false, shape.classed(CLASS.SELECTED, false), d, i); } }); } shape.classed(CLASS.SELECTED, !isSelected); toggle(!isSelected, shape, d, i); } __data_onclick(d, target); } } function drag(mouse) { var sx, sy, mx, my, minX, maxX, minY, maxY; if (hasArcType(c3.data.targets)) { return; } if (! __data_selection_enabled) { return; } // do nothing if not selectable if (__zoom_enabled && ! zoom.altDomain) { return; } // skip if zoomable because of conflict drag dehavior if (!__data_selection_multiple) { return; } // skip when single selection becuase drag is used for multiple selection sx = dragStart[0]; sy = dragStart[1]; mx = mouse[0]; my = mouse[1]; minX = Math.min(sx, mx); maxX = Math.max(sx, mx); minY = (__data_selection_grouped) ? margin.top : Math.min(sy, my); maxY = (__data_selection_grouped) ? height : Math.max(sy, my); main.select('.' + CLASS.dragarea) .attr('x', minX) .attr('y', minY) .attr('width', maxX - minX) .attr('height', maxY - minY); // TODO: binary search when multiple xs main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape) .filter(function (d) { return __data_selection_isselectable(d); }) .each(function (d, i) { var _this = d3.select(this), isSelected = _this.classed(CLASS.SELECTED), isIncluded = _this.classed(CLASS.INCLUDED), _x, _y, _w, _h, toggle, isWithin = false, box; if (this.nodeName === 'circle') { _x = _this.attr("cx") * 1; _y = _this.attr("cy") * 1; toggle = togglePoint; isWithin = minX < _x && _x < maxX && minY < _y && _y < maxY; } else if (this.nodeName === 'path') { box = getPathBox(this); _x = box.x; _y = box.y; _w = box.width; _h = box.height; toggle = toggleBar; isWithin = !(maxX < _x || _x + _w < minX) && !(maxY < _y || _y + _h < minY); } if (isWithin ^ isIncluded) { _this.classed(CLASS.INCLUDED, !isIncluded); // TODO: included/unincluded callback here _this.classed(CLASS.SELECTED, !isSelected); toggle(!isSelected, _this, d, i); } }); } function dragstart(mouse) { if (hasArcType(c3.data.targets)) { return; } if (! __data_selection_enabled) { return; } // do nothing if not selectable dragStart = mouse; main.select('.' + CLASS.chart).append('rect') .attr('class', CLASS.dragarea) .style('opacity', 0.1); dragging = true; __data_ondragstart(); } function dragend() { if (hasArcType(c3.data.targets)) { return; } if (! __data_selection_enabled) { return; } // do nothing if not selectable main.select('.' + CLASS.dragarea) .transition().duration(100) .style('opacity', 0) .remove(); main.selectAll('.' + CLASS.shape) .classed(CLASS.INCLUDED, false); dragging = false; __data_ondragend(); } function redraw(options) { var xgrid, xgridData, xgridLines, xgridLine, ygrid, ygridLines, ygridLine; var mainCircle, mainBar, mainRegion, mainText, contextBar, eventRectUpdate; var barIndices = getBarIndices(), maxDataCountTarget; var rectX, rectW; var withY, withSubchart, withTransition, withTransform, withUpdateXDomain, withUpdateOrgXDomain, withLegend; var hideAxis = hasArcType(c3.data.targets); var drawBar, drawBarOnSub, xForText, yForText; var duration, durationForExit, durationForAxis; var targetsToShow = filterTargetsToShow(c3.data.targets); // abort if no targets to show if (targetsToShow.length === 0) { return; } options = isDefined(options) ? options : {}; withY = isDefined(options.withY) ? options.withY : true; withSubchart = isDefined(options.withSubchart) ? options.withSubchart : true; withTransition = isDefined(options.withTransition) ? options.withTransition : true; withTransform = isDefined(options.withTransform) ? options.withTransform : false; withUpdateXDomain = isDefined(options.withUpdateXDomain) ? options.withUpdateXDomain : false; withUpdateOrgXDomain = isDefined(options.withUpdateOrgXDomain) ? options.withUpdateOrgXDomain : false; withLegend = isDefined(options.withLegend) ? options.withLegend : false; duration = withTransition ? __transition_duration : 0; durationForExit = isDefined(options.durationForExit) ? options.durationForExit : duration; durationForAxis = isDefined(options.durationForAxis) ? options.durationForAxis : duration; // update legend and transform each g if (withLegend && __legend_show) { updateLegend(c3.data.targets, options); } if (withUpdateOrgXDomain) { x.domain(d3.extent(getXDomain(targetsToShow))); orgXDomain = x.domain(); if (__zoom_enabled) { zoom.scale(x).updateScaleExtent(); } subX.domain(x.domain()); brush.scale(subX); } // ATTENTION: call here to update tickOffset if (withUpdateXDomain) { x.domain(brush.empty() ? orgXDomain : brush.extent()); if (__zoom_enabled) { zoom.scale(x).updateScaleExtent(); } } y.domain(getYDomain(targetsToShow, 'y')); y2.domain(getYDomain(targetsToShow, 'y2')); // axis main.select('.' + CLASS.axisX).style("opacity", hideAxis ? 0 : 1).transition().duration(durationForAxis).call(xAxis); main.select('.' + CLASS.axisY).style("opacity", hideAxis ? 0 : 1).transition().duration(durationForAxis).call(yAxis); main.select('.' + CLASS.axisY2).style("opacity", hideAxis ? 0 : 1).transition().duration(durationForAxis).call(yAxis2); // setup drawer - MEMO: these must be called after axis updated drawBar = generateDrawBar(barIndices); xForText = generateXYForText(barIndices, true); yForText = generateXYForText(barIndices, false); // Update axis label main.select('.' + CLASS.axisX + ' .' + CLASS.axisXLabel).attr("x", xForXAxisLabel).text(textForXAxisLabel); main.select('.' + CLASS.axisY + ' .' + CLASS.axisYLabel).attr("x", xForYAxisLabel).attr("dy", dyForYAxisLabel).text(textForYAxisLabel); main.select('.' + CLASS.axisY2 + ' .' + CLASS.axisY2Label).attr("x", xForY2AxisLabel).attr("dy", dyForY2AxisLabel).text(textForY2AxisLabel); // Update sub domain subY.domain(y.domain()); subY2.domain(y2.domain()); // tooltip tooltip.style("display", "none"); // grid main.select('line.' + CLASS.xgridFocus).style("visibility", "hidden"); if (__grid_x_show) { if (__grid_x_type === 'year') { xgridData = []; var xDomain = getXDomain(); var firstYear = xDomain[0].getFullYear(); var lastYear = xDomain[1].getFullYear(); for (var year = firstYear; year <= lastYear; year++) { xgridData.push(new Date(year + '-01-01 00:00:00')); } } else { xgridData = x.ticks(10); } xgrid = main.select('.' + CLASS.xgrids).selectAll('.' + CLASS.xgrid) .data(xgridData); xgrid.enter().append('line').attr("class", CLASS.xgrid); xgrid.attr("x1", __axis_rotated ? 0 : function (d) { return x(d) - xAxis.tickOffset(); }) .attr("x2", __axis_rotated ? width : function (d) { return x(d) - xAxis.tickOffset(); }) .attr("y1", __axis_rotated ? function (d) { return x(d) - xAxis.tickOffset(); } : margin.top) .attr("y2", __axis_rotated ? function (d) { return x(d) - xAxis.tickOffset(); } : height) .style("opacity", function () { return +d3.select(this).attr(__axis_rotated ? 'y1' : 'x1') === (__axis_rotated ? height : 0) ? 0 : 1; }); xgrid.exit().remove(); } if (notEmpty(__grid_x_lines)) { xgridLines = main.select('.' + CLASS.xgridLines).selectAll('.' + CLASS.xgridLine) .data(__grid_x_lines); // enter xgridLine = xgridLines.enter().append('g') .attr("class", function (d) { return CLASS.xgridLine + (d.class ? d.class : ''); }); xgridLine.append('line') .style("opacity", 0); xgridLine.append('text') .attr("text-anchor", "end") .attr("transform", __axis_rotated ? "" : "rotate(-90)") .attr('dx', __axis_rotated ? 0 : -margin.top) .attr('dy', -5) .style("opacity", 0); // udpate xgridLines.select('line') .transition().duration(duration) .attr("x1", __axis_rotated ? 0 : xv) .attr("x2", __axis_rotated ? width : xv) .attr("y1", __axis_rotated ? xv : margin.top) .attr("y2", __axis_rotated ? xv : height) .style("opacity", 1); xgridLines.select('text') .transition().duration(duration) .attr("x", __axis_rotated ? width : 0) .attr("y", xv) .text(function (d) { return d.text; }) .style("opacity", 1); // exit xgridLines.exit().transition().duration(duration) .style("opacity", 0) .remove(); } // Y-Grid if (withY && __grid_y_show) { ygrid = main.select('.' + CLASS.ygrids).selectAll('.' + CLASS.ygrid) .data(y.ticks(__grid_y_ticks)); ygrid.enter().append('line') .attr('class', CLASS.ygrid); ygrid.attr("x1", __axis_rotated ? y : 0) .attr("x2", __axis_rotated ? y : width) .attr("y1", __axis_rotated ? 0 : y) .attr("y2", __axis_rotated ? height : y); ygrid.exit().remove(); } if (withY && notEmpty(__grid_y_lines)) { ygridLines = main.select('.' + CLASS.ygridLines).selectAll('.' + CLASS.ygridLine) .data(__grid_y_lines); // enter ygridLine = ygridLines.enter().append('g') .attr("class", function (d) { return CLASS.ygridLine + (d.class ? d.class : ''); }); ygridLine.append('line') .style("opacity", 0); ygridLine.append('text') .attr("text-anchor", "end") .attr("transform", __axis_rotated ? "rotate(-90)" : "") .attr('dx', __axis_rotated ? 0 : -margin.top) .attr('dy', -5) .style("opacity", 0); // update ygridLines.select('line') .transition().duration(duration) .attr("x1", __axis_rotated ? yv : 0) .attr("x2", __axis_rotated ? yv : width) .attr("y1", __axis_rotated ? 0 : yv) .attr("y2", __axis_rotated ? height : yv) .style("opacity", 1); ygridLines.select('text') .transition().duration(duration) .attr("x", __axis_rotated ? 0 : width) .attr("y", yv) .text(function (d) { return d.text; }) .style("opacity", 1); // exit ygridLines.exit().transition().duration(duration) .style("opacity", 0) .remove(); } // bars mainBar = main.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar) .data(barData); mainBar.enter().append('path') .attr('d', drawBar) .style("stroke", 'none') .style("opacity", 0) .style("fill", function (d) { return color(d.id); }) .attr("class", classBar); mainBar .style("opacity", initialOpacity) .transition().duration(duration) .attr('d', drawBar) .style("opacity", 1); mainBar.exit().transition().duration(durationForExit) .style('opacity', 0) .remove(); mainText = main.selectAll('.' + CLASS.texts).selectAll('.' + CLASS.text) .data(barOrLineData); mainText.enter().append('text') .attr("class", classText) .attr('text-anchor', function (d) { return __axis_rotated ? (d.value < 0 ? 'end' : 'start') : 'middle'; }) .style("stroke", 'none') .style("fill-opacity", 0); mainText .text(function (d) { return formatByAxisId(d.id)(d.value); }) .style("fill-opacity", initialOpacityForText) .transition().duration(duration) .attr('x', xForText) .attr('y', yForText) .style("fill-opacity", opacityForText); mainText.exit() .transition().duration(durationForExit) .style('fill-opacity', 0) .remove(); // lines and cricles main.selectAll('.' + CLASS.line) .style("opacity", initialOpacity) .transition().duration(duration) .attr("d", lineOnMain) .style("opacity", 1); main.selectAll('.' + CLASS.area) .style("opacity", 0) .transition().duration(duration) .attr("d", areaOnMain) .style("opacity", orgAreaOpacity); mainCircle = main.selectAll('.' + CLASS.circles).selectAll('.' + CLASS.circle) .data(lineOrScatterData); mainCircle.enter().append("circle") .attr("class", classCircle) .style('opacity', 0) .attr("r", __point_r); mainCircle .style("opacity", initialOpacity) .transition().duration(duration) .style('opacity', opacityForCircle) .attr("cx", __axis_rotated ? circleY : circleX) .attr("cy", __axis_rotated ? circleX : circleY); mainCircle.exit().remove(); // arc main.selectAll('.' + CLASS.chartArc).select('.' + CLASS.arc) .attr("transform", withTransform ? "scale(0)" : "") .style("opacity", function (d) { return d === this._current ? 0 : 1; }) .transition().duration(duration) .attrTween("d", function (d) { var updated = updateAngle(d), interpolate; if (! updated) { return function () { return "M 0 0"; }; } /* if (this._current === d) { this._current = { startAngle: Math.PI*2, endAngle: Math.PI*2, }; } */ interpolate = d3.interpolate(this._current, updated); this._current = interpolate(0); return function (t) { return getArc(interpolate(t), true); }; }) .attr("transform", withTransform ? "scale(1)" : "") .style("opacity", 1); main.selectAll('.' + CLASS.chartArc).select('text') .attr("transform", transformForArcLabel) .style("opacity", 0) .transition().duration(duration) .text(textForArcLabel) .style("opacity", function (d) { return isTargetToShow(d.data.id) && isArcType(d.data) ? 1 : 0; }); main.select('.' + CLASS.chartArcsTitle) .style("opacity", hasDonutType(c3.data.targets) ? 1 : 0); // subchart if (__subchart_show) { // reflect main chart to extent on subchart if zoomed if (d3.event !== null && d3.event.type === 'zoom') { brush.extent(x.orgDomain()).update(); } // update subchart elements if needed if (withSubchart) { // axes context.select('.' + CLASS.axisX).style("opacity", hideAxis ? 0 : 1).transition().duration(duration).call(subXAxis); // extent rect if (!brush.empty()) { brush.extent(x.orgDomain()).update(); } // setup drawer - MEMO: this must be called after axis updated drawBarOnSub = generateDrawBar(barIndices, true); // bars contextBar = context.selectAll('.' + CLASS.bars).selectAll('.' + CLASS.bar) .data(barData); contextBar.enter().append('path') .attr('d', drawBarOnSub) .style("stroke", 'none') .style("fill", function (d) { return color(d.id); }) .attr("class", classBar); contextBar .style("opacity", initialOpacity) .transition().duration(duration) .attr('d', drawBarOnSub) .style('opacity', 1); contextBar.exit().transition().duration(duration) .style('opacity', 0) .remove(); // lines context.selectAll('.' + CLASS.line) .style("opacity", initialOpacity) .transition().duration(duration) .attr("d", lineOnSub) .style('opacity', 1); } } // circles for select main.selectAll('.' + CLASS.selectedCircles) .filter(function (d) { return isBarType(d); }) .selectAll('circle') .remove(); main.selectAll('.' + CLASS.selectedCircle) .transition().duration(duration) .attr("cx", __axis_rotated ? circleY : circleX) .attr("cy", __axis_rotated ? circleX : circleY); // rect for mouseover if (notEmpty(__data_xs)) { eventRectUpdate = main.select('.' + CLASS.eventRects).selectAll('.' + CLASS.eventRect) .data([0]); // enter : only one rect will be added generateEventRectsForMultipleXs(eventRectUpdate.enter()); // update eventRectUpdate .attr('x', 0) .attr('y', 0) .attr('width', width) .attr('height', height); // exit : not needed becuase always only one rect exists } else { if (isCustomX && !isCategorized) { rectW = function (d, i) { var prevX = getPrevX(i), nextX = getNextX(i), dx = c3.data.x[d.id][i]; return (x(nextX ? nextX : dx + 50) - x(prevX ? prevX : dx - 50)) / 2; }; rectX = function (d, i) { var prevX = getPrevX(i), dx = c3.data.x[d.id][i]; return (x(dx) + x(prevX ? prevX : dx - 50)) / 2; }; } else { rectW = getEventRectWidth(); rectX = function (d) { return x(d.x) - (rectW / 2); }; } // Set data maxDataCountTarget = getMaxDataCountTarget(); main.select('.' + CLASS.eventRects) .datum(maxDataCountTarget ? maxDataCountTarget.values : []); // Update rects eventRectUpdate = main.select('.' + CLASS.eventRects).selectAll('.' + CLASS.eventRect) .data(function (d) { return d; }); // enter generateEventRectsForSingleX(eventRectUpdate.enter()); // update eventRectUpdate .attr('class', classEvent) .attr("x", __axis_rotated ? 0 : rectX) .attr("y", __axis_rotated ? rectX : 0) .attr("width", __axis_rotated ? width : rectW) .attr("height", __axis_rotated ? rectW : height); // exit eventRectUpdate.exit().remove(); } // rect for regions mainRegion = main.select('.' + CLASS.regions).selectAll('rect.' + CLASS.region) .data(__regions); mainRegion.enter().append('rect') .style("fill-opacity", 0); mainRegion .attr('class', classRegion) .attr("x", __axis_rotated ? 0 : regionStart) .attr("y", __axis_rotated ? regionStart : margin.top) .attr("width", __axis_rotated ? width : regionWidth) .attr("height", __axis_rotated ? regionWidth : height) .transition().duration(duration) .style("fill-opacity", function (d) { return isValue(d.opacity) ? d.opacity : 0.1; }); mainRegion.exit().transition().duration(duration) .style("fill-opacity", 0) .remove(); // update fadein condition getTargetIds().forEach(function (id) { withoutFadeIn[id] = true; }); } function redrawForBrush() { redraw({ withTransition: false, withY: false, withSubchart: false, withUpdateXDomain: true }); } function redrawForZoom() { if (d3.event.sourceEvent.type === 'mousemove' && zoom.altDomain) { x.domain(zoom.altDomain); zoom.scale(x).updateScaleExtent(); return; } if (isCategorized && x.orgDomain()[0] === orgXDomain[0]) { x.domain([orgXDomain[0] - 1e-10, x.orgDomain()[1]]); } redraw({ withTransition: false, withY: false, withSubchart: false }); if (d3.event.sourceEvent.type === 'mousemove') { cancelClick = true; } } function generateResize() { var resizeFunctions = []; function callResizeFunctions() { resizeFunctions.forEach(function (f) { f(); }); } callResizeFunctions.add = function (f) { resizeFunctions.push(f); }; return callResizeFunctions; } function updateSvgSize() { svg.attr('width', currentWidth).attr('height', currentHeight); svg.select('#' + clipId).select('rect').attr('width', width).attr('height', height); svg.select('#xaxis-clip').select('rect').attr('width', getXAxisClipWidth); svg.select('#yaxis-clip').select('rect').attr('width', getYAxisClipWidth); svg.select('.' + CLASS.zoomRect).attr('width', width).attr('height', height); } function updateAndRedraw(options) { options = isDefined(options) ? options : {}; options.withTransition = isDefined(options.withTransition) ? options.withTransition : true; options.withTransform = isDefined(options.withTransform) ? options.withTransform : false; options.withLegend = isDefined(options.withLegend) ? options.withLegend : false; options.withUpdateXDomain = true; options.withUpdateOrgXDomain = true; options.durationForExit = 0; // Update sizes and scales updateSizes(); updateScales(); updateSvgSize(); // Update g positions transformAll(options.withTransition); // Draw with new sizes & scales redraw(options); } function updateTargets(targets) { var mainLineEnter, mainLineUpdate, mainBarEnter, mainBarUpdate, mainPieEnter, mainPieUpdate, mainTextUpdate, mainTextEnter; var contextLineEnter, contextLineUpdate, contextBarEnter, contextBarUpdate; /*-- Main --*/ //-- Text --// mainTextUpdate = main.select('.' + CLASS.chartTexts) .selectAll('.' + CLASS.chartText) .data(targets); mainTextEnter = mainTextUpdate.enter().append('g') .attr('class', function (d) { return CLASS.chartText + generateClass(CLASS.target, d.id); }) .style("pointer-events", "none"); mainTextEnter.append('g') .attr('class', classTexts) .style("fill", function (d) { return color(d.id); }); //-- Bar --// mainBarUpdate = main.select('.' + CLASS.chartBars) .selectAll('.' + CLASS.chartBar) .data(targets); mainBarEnter = mainBarUpdate.enter().append('g') .attr('class', function (d) { return CLASS.chartBar + generateClass(CLASS.target, d.id); }) .style("pointer-events", "none"); // Bars for each data mainBarEnter.append('g') .attr("class", classBars) .style("fill", function (d) { return color(d.id); }) .style("stroke", "none") .style("cursor", function (d) { return __data_selection_isselectable(d) ? "pointer" : null; }); //-- Line --// mainLineUpdate = main.select('.' + CLASS.chartLines) .selectAll('.' + CLASS.chartLine) .data(targets); mainLineEnter = mainLineUpdate.enter().append('g') .attr('class', function (d) { return CLASS.chartLine + generateClass(CLASS.target, d.id); }) .style("pointer-events", "none"); // Lines for each data mainLineEnter.append("path") .attr("class", classLine) .style("opacity", 0) .style("stroke", function (d) { return color(d.id); }); // Areas mainLineEnter.append("path") .attr("class", classArea) .style("opacity", function () { orgAreaOpacity = +d3.select(this).style('opacity'); return 0; }) .style("fill", function (d) { return color(d.id); }); // Circles for each data point on lines mainLineEnter.append('g') .attr("class", function (d) { return generateClass(CLASS.selectedCircles, d.id); }); mainLineEnter.append('g') .attr("class", classCircles) .style("fill", function (d) { return color(d.id); }) .style("cursor", function (d) { return __data_selection_isselectable(d) ? "pointer" : null; }); // Update date for selected circles targets.forEach(function (t) { main.selectAll('.' + CLASS.selectedCircles + getTargetSelectorSuffix(t.id)).selectAll('.' + CLASS.selectedCircle).each(function (d, i) { d.value = t.values[i].value; }); }); // MEMO: can not keep same color... //mainLineUpdate.exit().remove(); //-- Pie --// mainPieUpdate = main.select('.' + CLASS.chartArcs) .selectAll('.' + CLASS.chartArc) .data(pie(targets)); mainPieEnter = mainPieUpdate.enter().append("g") .attr("class", function (d) { return CLASS.chartArc + generateClass(CLASS.target, d.data.id); }); mainPieEnter.append("path") .attr("class", classArc) .style("opacity", 0) .style("fill", function (d) { return color(d.data.id); }) .style("cursor", function (d) { return __data_selection_isselectable(d) ? "pointer" : null; }) .each(function (d) { this._current = d; }) .on('mouseover', function (d, i) { var updated = updateAngle(d), arcData = convertToArcData(updated), callback = getArcOnMouseOver(); expandArc(updated.data.id); focusLegend(updated.data.id); callback(arcData, i); }) .on('mousemove', function (d) { var updated = updateAngle(d), selectedData = [convertToArcData(updated)]; showTooltip(selectedData, d3.mouse(this)); }) .on('mouseout', function (d, i) { var updated = updateAngle(d), arcData = convertToArcData(updated), callback = getArcOnMouseOut(); unexpandArc(updated.data.id); revertLegend(); hideTooltip(); callback(arcData, i); }) .on('click', function (d, i) { var updated = updateAngle(d), arcData = convertToArcData(updated), callback = getArcOnClick(); callback(arcData, i); }); mainPieEnter.append("text") .attr("dy", ".35em") .style("opacity", 0) .style("text-anchor", "middle") .style("pointer-events", "none"); // MEMO: can not keep same color..., but not bad to update color in redraw //mainPieUpdate.exit().remove(); /*-- Context --*/ if (__subchart_show) { contextBarUpdate = context.select('.' + CLASS.chartBars) .selectAll('.' + CLASS.chartBar) .data(targets); contextBarEnter = contextBarUpdate.enter().append('g') .attr('class', function (d) { return CLASS.chartBar + generateClass(CLASS.target, d.id); }); // Bars for each data contextBarEnter.append('g') .attr("class", classBars) .style("fill", function (d) { return color(d.id); }); //-- Line --// contextLineUpdate = context.select('.' + CLASS.chartLines) .selectAll('.' + CLASS.chartLine) .data(targets); contextLineEnter = contextLineUpdate.enter().append('g') .attr('class', function (d) { return CLASS.chartLine + generateClass(CLASS.target, d.id); }); // Lines for each data contextLineEnter.append("path") .attr("class", classLine) .style("opacity", 0) .style("stroke", function (d) { return color(d.id); }); } /*-- Show --*/ // Fade-in each chart svg.selectAll('.' + CLASS.target).filter(function (d) { return isTargetToShow(d.id); }) .transition() .style("opacity", 1); } function load(targets, done) { // Update/Add data c3.data.targets.forEach(function (d) { for (var i = 0; i < targets.length; i++) { if (d.id === targets[i].id) { d.values = targets[i].values; targets.splice(i, 1); break; } } }); c3.data.targets = c3.data.targets.concat(targets); // add remained // Set targets updateTargets(c3.data.targets); // Redraw with new targets redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true}); if (typeof done === 'function') { done(); } } function loadFromArgs(args) { // load data if ('data' in args) { load(convertDataToTargets(args.data), args.done); } else if ('url' in args) { d3.csv(args.url, function (error, data) { load(convertDataToTargets(data), args.done); }); } else if ('rows' in args) { load(convertDataToTargets(convertRowsToData(args.rows)), args.done); } else if ('columns' in args) { load(convertDataToTargets(convertColumnsToData(args.columns)), args.done); } else { throw Error('url or rows or columns is required.'); } } function unload(targetIds, done) { if (typeof done !== 'function') { done = function () {}; } if (!targetIds || targetIds.length === 0) { done(); return; } svg.selectAll(targetIds.map(function (id) { return selectorTarget(id); })) .transition() .style('opacity', 0) .remove() .call(endall, done); targetIds.forEach(function (id) { // Reset fadein for future load withoutFadeIn[id] = false; // Remove target's elements if (__legend_show) { legend.selectAll('.' + CLASS.legendItem + getTargetSelectorSuffix(id)).remove(); } // Remove target c3.data.targets = c3.data.targets.filter(function (t) { return t.id !== id; }); }); } /*-- Draw Legend --*/ function toggleFocusLegend(id, focus) { var legendItem, isTarget, notTarget; if (!__legend_show) { return; } legendItem = legend.selectAll('.' + CLASS.legendItem); isTarget = function (d) { return !id || d === id; }; notTarget = function (d) { return !isTarget(d); }; legendItem.filter(notTarget).transition().duration(100).style('opacity', focus ? 0.3 : 1); legendItem.filter(isTarget).transition().duration(100).style('opacity', focus ? 1 : 0.3); } function focusLegend(id) { toggleFocusLegend(id, true); } function defocusLegend(id) { toggleFocusLegend(id, false); } function revertLegend() { if (!__legend_show) { return; } legend.selectAll('.' + CLASS.legendItem) .transition().duration(100) .style('opacity', 1); } function updateLegend(targets, options) { var ids = getTargetIds(targets), l; var xForLegend, xForLegendText, xForLegendRect, yForLegend, yForLegendText, yForLegendRect; var paddingTop = 4, paddingRight = 26, maxWidth = 0, maxHeight = 0, posMin = 10; var totalLength = 0, offsets = {}, widths = {}, heights = {}, margins = {}, steps = {}, step = 0; var withTransition; options = isUndefined(options) ? {} : options; withTransition = isDefined(options.withTransition) ? options.withTransition : true; function updatePositions(textElement, id, reset) { var box = textElement.getBBox(), itemWidth = Math.ceil((box.width + paddingRight) / 10) * 10, itemHeight = Math.ceil((box.height + paddingTop) / 10) * 10, itemLength = isLegendRight ? itemHeight : itemWidth, areaLength = isLegendRight ? legendHeight : legendWidth, margin, maxLength; // MEMO: care about condifion of step, totalLength function updateValues(id, withoutStep) { if (!withoutStep) { margin = (areaLength - totalLength - itemLength) / 2; if (margin < posMin) { margin = (areaLength - itemLength) / 2; totalLength = 0; step++; } } steps[id] = step; margins[step] = margin; offsets[id] = totalLength; totalLength += itemLength; } if (reset) { totalLength = 0; step = 0; maxWidth = 0; maxHeight = 0; } widths[id] = itemWidth; heights[id] = itemHeight; if (!maxWidth || itemWidth >= maxWidth) { maxWidth = itemWidth; } if (!maxHeight || itemHeight >= maxHeight) { maxHeight = itemHeight; } maxLength = isLegendRight ? maxHeight : maxWidth; if (__legend_equally) { Object.keys(widths).forEach(function (id) { widths[id] = maxWidth; }); Object.keys(heights).forEach(function (id) { heights[id] = maxHeight; }); margin = (areaLength - maxLength * ids.length) / 2; if (margin < posMin) { totalLength = 0; step = 0; ids.forEach(function (id) { updateValues(id); }); } else { updateValues(id, true); } } else { updateValues(id); } } if (isLegendRight) { xForLegend = function (id) { return maxWidth * (0.2 + steps[id]); }; yForLegend = function (id) { return margins[steps[id]] + offsets[id]; }; } else { xForLegend = function (id) { return margins[steps[id]] + offsets[id]; }; yForLegend = function (id) { return maxHeight * (0.2 + steps[id]); }; } xForLegendText = function (id, i) { return xForLegend(id, i) + 14; }; yForLegendText = function (id, i) { return yForLegend(id, i) + 9; }; xForLegendRect = function (id, i) { return xForLegend(id, i) - 4; }; yForLegendRect = function (id, i) { return yForLegend(id, i) - 7; }; // Define g for legend area l = legend.selectAll('.' + CLASS.legendItem) .data(ids) .enter().append('g') .attr('class', function (id) { return generateClass(CLASS.legendItem, id); }) .style('cursor', 'pointer') .on('click', function (id) { typeof __legend_item_onclick === 'function' ? __legend_item_onclick(id) : c3.toggle(id); }) .on('mouseover', function (id) { c3.focus(id); }) .on('mouseout', function () { c3.revert(); }); l.append('text') .text(function (id) { return isDefined(__data_names[id]) ? __data_names[id] : id; }) .each(function (id, i) { updatePositions(this, id, i === 0); }) .style("pointer-events", "none") .attr('x', isLegendRight ? xForLegendText : -200) .attr('y', isLegendRight ? -200 : yForLegendText); l.append('rect') .attr("class", CLASS.legendItemEvent) .style('fill-opacity', 0) .attr('x', isLegendRight ? xForLegendRect : -200) .attr('y', isLegendRight ? -200 : yForLegendRect) .attr('width', function (id) { return widths[id]; }) .attr('height', function (id) { return heights[id]; }); l.append('rect') .attr("class", CLASS.legendItemTile) .style("pointer-events", "none") .style('fill', function (id) { return color(id); }) .attr('x', isLegendRight ? xForLegendText : -200) .attr('y', isLegendRight ? -200 : yForLegend) .attr('width', 10) .attr('height', 10); legend.selectAll('text') .data(ids) .text(function (id) { return isDefined(__data_names[id]) ? __data_names[id] : id; }) // MEMO: needed for update .each(function (id, i) { updatePositions(this, id, i === 0); }) .transition().duration(withTransition ? 250 : 0) .attr('x', xForLegendText) .attr('y', yForLegendText); legend.selectAll('rect.' + CLASS.legendItemEvent) .data(ids) .transition().duration(withTransition ? 250 : 0) .attr('x', xForLegendRect) .attr('y', yForLegendRect); legend.selectAll('rect.' + CLASS.legendItemTile) .data(ids) .transition().duration(withTransition ? 250 : 0) .attr('x', xForLegend) .attr('y', yForLegend); // Update all to reflect change of legend updateLegendItemWidth(maxWidth); updateLegendItemHeight(maxHeight); updateLegendStep(step); // Update size and scale updateSizes(); updateScales(); updateSvgSize(); // Update g positions transformAll(false); } /*-- Event Handling --*/ function isNoneArc(d) { return hasTarget(d.id); } function isArc(d) { return 'data' in d && hasTarget(d.data.id); } function getGridFilter(params) { var value = params && params.value ? params.value : null, klass = params && params['class'] ? params['class'] : null; return value ? function (line) { return line.value !== value; } : klass ? function (line) { return line['class'] !== klass; } : function () { return true; }; } c3.focus = function (targetId) { var candidates = svg.selectAll(selectorTarget(targetId)), candidatesForNoneArc = candidates.filter(isNoneArc), candidatesForArc = candidates.filter(isArc); function focus(targets) { filterTargetsToShow(targets).transition().duration(100).style('opacity', 1); } c3.revert(); c3.defocus(); focus(candidatesForNoneArc.classed(CLASS.focused, true)); focus(candidatesForArc); if (hasArcType(c3.data.targets)) { expandArc(targetId, true); } focusLegend(targetId); }; c3.defocus = function (targetId) { var candidates = svg.selectAll(selectorTarget(targetId)), candidatesForNoneArc = candidates.filter(isNoneArc), candidatesForArc = candidates.filter(isArc); function defocus(targets) { filterTargetsToShow(targets).transition().duration(100).style('opacity', 0.3); } c3.revert(); defocus(candidatesForNoneArc.classed(CLASS.focused, false)); defocus(candidatesForArc); if (hasArcType(c3.data.targets)) { unexpandArc(targetId); } defocusLegend(targetId); }; c3.revert = function (targetId) { var candidates = svg.selectAll(selectorTarget(targetId)), candidatesForNoneArc = candidates.filter(isNoneArc), candidatesForArc = candidates.filter(isArc); function revert(targets) { filterTargetsToShow(targets).transition().duration(100).style('opacity', 1); } revert(candidatesForNoneArc.classed(CLASS.focused, false)); revert(candidatesForArc); if (hasArcType(c3.data.targets)) { unexpandArc(targetId); } revertLegend(); }; c3.show = function (targetId) { removeHiddenTargetIds(targetId); svg.selectAll(selectorTarget(targetId)) .transition() .style('opacity', 1); redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: false}); }; c3.hide = function (targetId) { addHiddenTargetIds(targetId); svg.selectAll(selectorTarget(targetId)) .transition() .style('opacity', 0); redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: false}); }; c3.toggle = function (targetId) { isTargetToShow(targetId) ? c3.hide(targetId) : c3.show(targetId); }; c3.unzoom = function () { brush.clear().update(); redraw({withUpdateXDomain: true}); }; c3.load = function (args) { // update xs if exists if (args.xs) { addXs(args.xs); } // update categories if exists if ('categories' in args && isCategorized) { __axis_x_categories = args.categories; xAxis.categories(__axis_x_categories); } // use cache if exists if ('cacheIds' in args && hasCaches(args.cacheIds)) { load(getCaches(args.cacheIds), args.done); return; } // unload if needed if ('unload' in args) { // TODO: do not unload if target will load (included in url/rows/columns) unload(args.unload ? typeof args.unload === 'string' ? [args.unload] : args.unload : [], function () { loadFromArgs(args); }); } else { loadFromArgs(args); } }; c3.unload = function (targetIds) { unload(targetIds ? typeof targetIds === 'string' ? [targetIds] : targetIds : getTargetIds(), function () { redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true, withLegend: true}); }); }; c3.selected = function (targetId) { return d3.merge( main.selectAll('.' + CLASS.shapes + getTargetSelectorSuffix(targetId)).selectAll('.' + CLASS.shape) .filter(function () { return d3.select(this).classed(CLASS.SELECTED); }) .map(function (d) { return d.map(function (_d) { return _d.__data__; }); }) ); }; c3.select = function (ids, indices, resetOther) { if (! __data_selection_enabled) { return; } main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) { var shape = d3.select(this), select = (this.nodeName === 'circle') ? selectPoint : selectBar, unselect = (this.nodeName === 'circle') ? unselectPoint : unselectBar, isTargetId = __data_selection_grouped || !ids || ids.indexOf(d.id) >= 0, isTargetIndex = !indices || indices.indexOf(i) >= 0, isSelected = shape.classed(CLASS.SELECTED); if (isTargetId && isTargetIndex) { if (__data_selection_isselectable(d) && !isSelected) { select(shape.classed(CLASS.SELECTED, true), d, i); } } else if (isDefined(resetOther) && resetOther) { if (isSelected) { unselect(shape.classed(CLASS.SELECTED, false), d, i); } } }); }; c3.unselect = function (ids, indices) { if (! __data_selection_enabled) { return; } main.selectAll('.' + CLASS.shapes).selectAll('.' + CLASS.shape).each(function (d, i) { var shape = d3.select(this), unselect = (this.nodeName === 'circle') ? unselectPoint : unselectBar, isTargetId = __data_selection_grouped || !ids || ids.indexOf(d.id) >= 0, isTargetIndex = !indices || indices.indexOf(i) >= 0, isSelected = shape.classed(CLASS.SELECTED); if (isTargetId && isTargetIndex) { if (__data_selection_isselectable(d)) { if (isSelected) { unselect(shape.classed(CLASS.SELECTED, false), d, i); } } } }); }; c3.toLine = function (targets) { setTargetType(targets, 'line'); updateAndRedraw(); }; c3.toSpline = function (targets) { setTargetType(targets, 'spline'); updateAndRedraw(); }; c3.toBar = function (targets) { setTargetType(targets, 'bar'); updateAndRedraw(); }; c3.toScatter = function (targets) { setTargetType(targets, 'scatter'); updateAndRedraw(); }; c3.toArea = function (targets) { setTargetType(targets, 'area'); updateAndRedraw(); }; c3.toAreaSpline = function (targets) { setTargetType(targets, 'area-spline'); updateAndRedraw(); }; c3.toPie = function (targets) { setTargetType(targets, 'pie'); updateAndRedraw({withTransform: true}); }; c3.toDonut = function (targets) { setTargetType(targets, 'donut'); updateAndRedraw({withTransform: true}); }; c3.groups = function (groups) { if (isUndefined(groups)) { return __data_groups; } __data_groups = groups; redraw(); return __data_groups; }; c3.xgrids = function (grids) { if (! grids) { return __grid_x_lines; } __grid_x_lines = grids; redraw(); return __grid_x_lines; }; c3.xgrids.add = function (grids) { if (! grids) { return; } return c3.xgrids(__grid_x_lines.concat(grids)); }; c3.xgrids.remove = function (params) { // TODO: multiple var filter = getGridFilter(params); return c3.xgrids(__grid_x_lines.filter(filter)); }; c3.ygrids = function (grids) { if (! grids) { return __grid_y_lines; } __grid_y_lines = grids; redraw(); return __grid_y_lines; }; c3.ygrids.add = function (grids) { if (! grids) { return; } return c3.ygrids(__grid_y_lines.concat(grids)); }; c3.ygrids.remove = function (params) { // TODO: multiple var filter = getGridFilter(params); return c3.ygrids(__grid_y_lines.filter(filter)); }; c3.regions = function (regions) { if (isUndefined(regions)) { return __regions; } __regions = regions; redraw(); return __regions; }; c3.regions.add = function (regions) { if (isUndefined(regions)) { return __regions; } __regions = __regions.concat(regions); redraw(); return __regions; }; c3.regions.remove = function (classes, options) { var regionClasses = [].concat(classes); options = isDefined(options) ? options : {}; regionClasses.forEach(function (cls) { var duration = isValue(options.duration) ? options.duration : 0; svg.selectAll('.' + cls) .transition().duration(duration) .style('fill-opacity', 0) .remove(); __regions = __regions.filter(function (region) { return region.classes.indexOf(cls) < 0; }); }); return __regions; }; c3.data.get = function (targetId) { var target = c3.data.getAsTarget(targetId); return isDefined(target) ? target.values.map(function (d) { return d.value; }) : undefined; }; c3.data.getAsTarget = function (targetId) { var targets = getTargets(function (t) { return t.id === targetId; }); return targets.length > 0 ? targets[0] : undefined; }; c3.data.names = function (names) { if (!arguments.length) { return __data_names; } Object.keys(names).forEach(function (id) { __data_names[id] = names[id]; }); updateLegend(c3.data.targets, {withTransition: true}); return __data_names; }; c3.x = function (x) { if (arguments.length) { updateTargetX(c3.data.targets, x); redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true}); } return c3.data.x; }; c3.xs = function (xs) { if (arguments.length) { updateTargetXs(c3.data.targets, xs); redraw({withUpdateOrgXDomain: true, withUpdateXDomain: true}); } return c3.data.x; }; c3.axis.labels = function (labels) { if (arguments.length) { Object.keys(labels).forEach(function (axisId) { setAxisLabelText(axisId, labels[axisId]); }); redraw({withY: false, withSubchart: false, withTransition: false}); } // TODO: return some values? }; c3.resize = function (size) { __size_width = size ? size.width : null; __size_height = size ? size.height : null; updateAndRedraw({withLegend: true, withTransition: false}); }; c3.destroy = function () { c3.data.targets = undefined; c3.data.x = {}; selectChart.html(""); window.onresize = null; }; /*-- Load data and init chart with defined functions --*/ if ('url' in config.data) { d3.csv(config.data.url, function (error, data) { init(data); }); } else if ('rows' in config.data) { init(convertRowsToData(config.data.rows)); } else if ('columns' in config.data) { init(convertColumnsToData(config.data.columns)); } else { throw Error('url or rows or columns is required.'); } return c3; }; function isValue(v) { return v || v === 0; } function isUndefined(v) { return typeof v === 'undefined'; } function isDefined(v) { return typeof v !== 'undefined'; } if (typeof window.define === "function" && window.define.amd) { window.define("c3", ["d3"], c3); } else { window.c3 = c3; } // TODO: module.exports })(window);
// Zepto.js // (c) 2010-2014 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. ;(function($){ var cache = [], timeout $.fn.remove = function(){ return this.each(function(){ if(this.parentNode){ if(this.tagName === 'IMG'){ cache.push(this) this.src = 'data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs=' if (timeout) clearTimeout(timeout) timeout = setTimeout(function(){ cache = [] }, 60000) } this.parentNode.removeChild(this) } }) } })(Zepto)
var forge = require('../js/forge'); var net = require('net'); var socket = new net.Socket(); var client = forge.tls.createConnection({ server: false, verify: function(connection, verified, depth, certs) { // skip verification for testing return true; }, connected: function(connection) { console.log('[tls] connected'); }, tlsDataReady: function(connection) { // encrypted data is ready to be sent to the server var data = connection.tlsData.getBytes(); socket.write(data, 'binary'); }, dataReady: function(connection) { // clear data from the server is ready var data = connection.data.getBytes(); console.log('[tls] received from the server: ' + data); client.close(); }, closed: function() { console.log('[tls] disconnected'); }, error: function(connection, error) { console.log('[tls] error', error); } }); socket.on('connect', function() { console.log('[socket] connected'); client.handshake(); }); socket.on('data', function(data) { client.process(data.toString('binary')); }); socket.on('end', function() { console.log('[socket] disconnected'); }); // connect to gmail's imap server socket.connect(993, 'imap.gmail.com');
/*! Copyright (C) 2013 by WebReflection Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function(window){ /*! (C) WebReflection Mit Style License */ if (document.createEvent) return; var DUNNOABOUTDOMLOADED = true, READYEVENTDISPATCHED = false, ONREADYSTATECHANGE = 'onreadystatechange', DOMCONTENTLOADED = 'DOMContentLoaded', SECRET = '__IE8__' + Math.random(), Object = window.Object, defineProperty = Object.defineProperty || // just in case ... function (object, property, descriptor) { object[property] = descriptor.value; }, defineProperties = Object.defineProperties || // IE8 implemented defineProperty but not the plural... function (object, descriptors) { for(var key in descriptors) { if (hasOwnProperty.call(descriptors, key)) { defineProperty(object, key, descriptors[key]); } } }, hasOwnProperty = Object.prototype.hasOwnProperty, // here IE7 will break like a charm ElementPrototype = window.Element.prototype, EventPrototype = window.Event.prototype, DocumentPrototype = window.HTMLDocument.prototype, WindowPrototype = window.Window.prototype, // none of above native constructors exist/are exposed possiblyNativeEvent = /^[a-z]+$/, // ^ actually could probably be just /^[a-z]+$/ readyStateOK = /loaded|complete/, types = {}, div = document.createElement('div') ; function commonEventLoop(currentTarget, e, $handlers, synthetic) { for(var continuePropagation, handlers = $handlers.slice(), evt = enrich(e, currentTarget), i = 0, length = handlers.length; i < length; i++ ) { handler = handlers[i]; if ( typeof handler === 'object' && typeof handler.handleEvent === 'function' ) { handler.handleEvent(evt); } else { handler.call(currentTarget, evt); } if (evt.stoppedImmediatePropagation) break; } continuePropagation = !evt.stoppedPropagation; /* if (continuePropagation && !synthetic && !live(currentTarget)) { evt.cancelBubble = true; } */ return ( synthetic && continuePropagation && currentTarget.parentNode ) ? currentTarget.parentNode.dispatchEvent(evt) : !evt.defaultPrevented ; } function enrich(e, currentTarget) { e.currentTarget = currentTarget; e.eventPhase = ( // AT_TARGET : BUBBLING_PHASE e.target === e.currentTarget ? 2 : 3 ); return e; } function find(array, value) { var i = array.length; while(i-- && array[i] !== value); return i; } function live(self) { return self.nodeType !== 9 && document.documentElement.contains(self); } function onReadyState(e) { if (!READYEVENTDISPATCHED && readyStateOK.test( document.readyState )) { READYEVENTDISPATCHED = !READYEVENTDISPATCHED; document.detachEvent(ONREADYSTATECHANGE, onReadyState); e = document.createEvent('Event'); e.initEvent(DOMCONTENTLOADED, true, true); document.dispatchEvent(e); } } function verify(self, e) { if (!e) { e = window.event; } if (!e.target) { e.target = e.srcElement || e.fromElement || document; } if (!e.timeStamp) { e.timeStamp = (new Date).getTime(); } return e; } defineProperties( ElementPrototype, { // bonus textContent: { get: function () { return this.innerText; }, set: function (innerText) { // TODO: maybe this one is safer/better or ... both? // this.innerText = ''; // this.appendChild(document.createTextNode(innerText)); this.innerText = innerText; } }, // DOM Level 2 events addEventListener: {value: function (type, handler, capture) { var self = this, ontype = 'on' + type, temple = self[SECRET] || defineProperty( self, SECRET, {value: {}} )[SECRET], currentType = temple[ontype] || (temple[ontype] = {}), handlers = currentType.h || (currentType.h = []), e ; if (!hasOwnProperty.call(currentType, 'w')) { currentType.w = function (e) { // e[SECRET] is a silent notification needed to avoid // fired events during live test return e[SECRET] || commonEventLoop(self, verify(self, e), handlers, false); }; // if not detected yet if (!hasOwnProperty.call(types, ontype)) { // and potentially a native event if(possiblyNativeEvent.test(type)) { // do this heavy thing try { // TODO: should I consider tagName too so that // INPUT[ontype] could be different ? e = document.createEventObject(); // do not clone ever a node // specially a document one ... // use the secret to ignore them all e[SECRET] = true; // document a part if a node has never been // added to any other node, fireEvent might // behave very weirdly (read: trigger unspecified errors) if (self.nodeType != 9 && self.parentNode == null) { div.appendChild(self); } self.fireEvent(ontype, e); types[ontype] = true; } catch(e) { types[ontype] = false; while (div.hasChildNodes()) { div.removeChild(div.firstChild); } } } else { // no need to bother since // 'x-event' ain't native for sure types[ontype] = false; } } if (currentType.n = types[ontype]) { self.attachEvent(ontype, currentType.w); } } if (find(handlers, handler) < 0) { handlers[capture ? 'unshift' : 'push'](handler); } }}, dispatchEvent: {value: function (e) { var self = this, ontype = 'on' + e.type, temple = self[SECRET], currentType = temple && temple[ontype], valid = !!currentType, parentNode ; if (!e.target) e.target = self; return (valid ? ( currentType.n /* && live(self) */ ? self.fireEvent(ontype, e) : commonEventLoop( self, e, currentType.h, true ) ) : ( (parentNode = self.parentNode) /* && live(self) */ ? parentNode.dispatchEvent(e) : true )), !e.defaultPrevented; }}, removeEventListener: {value: function (type, handler, capture) { var self = this, ontype = 'on' + type, temple = self[SECRET], currentType = temple && temple[ontype], handlers = currentType && currentType.h, i = handlers ? find(handlers, handler) : -1 ; if (-1 < i) handlers.splice(i, 1); }} } ); defineProperties( EventPrototype, { bubbles: {value: true, writable: true}, cancelable: {value: true, writable: true}, preventDefault: {value: function () { if (this.cancelable) { this.defaultPrevented = true; this.returnValue = false; } }}, stopPropagation: {value: function () { this.stoppedPropagation = true; this.cancelBubble = true; }}, stopImmediatePropagation: {value: function () { this.stoppedImmediatePropagation = true; this.stopPropagation(); }}, initEvent: {value: function(type, bubbles, cancelable){ this.type = type; this.bubbles = !!bubbles; this.cancelable = !!cancelable; if (!this.bubbles) { this.stopPropagation(); } }} } ); defineProperties( DocumentPrototype, { addEventListener: {value: function(type, handler, capture) { var self = this; ElementPrototype.addEventListener.call(self, type, handler, capture); // NOTE: it won't fire if already loaded, this is NOT a $.ready() shim! // this behaves just like standard browsers if ( DUNNOABOUTDOMLOADED && type === DOMCONTENTLOADED && !readyStateOK.test( self.readyState ) ) { DUNNOABOUTDOMLOADED = false; self.attachEvent(ONREADYSTATECHANGE, onReadyState); if (window == top) { (function gonna(e){try{ self.documentElement.doScroll('left'); onReadyState(); }catch(o_O){ setTimeout(gonna, 50); }}()); } } }}, dispatchEvent: {value: ElementPrototype.dispatchEvent}, removeEventListener: {value: ElementPrototype.removeEventListener}, createEvent: {value: function(Class){ var e; if (Class !== 'Event') throw new Error('unsupported ' + Class); e = document.createEventObject(); e.timeStamp = (new Date).getTime(); return e; }} } ); defineProperties( WindowPrototype, { addEventListener: {value: function (type, handler, capture) { var self = window, ontype = 'on' + type, handlers ; if (!self[ontype]) { self[ontype] = function(e) { return commonEventLoop(self, verify(self, e), handlers, false); }; } handlers = self[ontype][SECRET] || ( self[ontype][SECRET] = [] ); if (find(handlers, handler) < 0) { handlers[capture ? 'unshift' : 'push'](handler); } }}, dispatchEvent: {value: function (e) { var method = window['on' + e.type]; return method ? method.call(window, e) !== false && !e.defaultPrevented : true; }}, removeEventListener: {value: function (type, handler, capture) { var ontype = 'on' + type, handlers = (window[ontype] || Object)[SECRET], i = handlers ? find(handlers, handler) : -1 ; if (-1 < i) handlers.splice(i, 1); }} } ); }(this));
// Copyright 2011 Software Freedom Conservancy. All Rights Reserved. // // 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. /** * @fileoverview Bootstrap file that loads all of the WebDriver scripts in the * correct order. Once loaded, pages can use {@code goog.require} statements * from Google Closure to load additional files as needed. * * Example Usage: * * <html> * <head> * <script src="test_bootstrap.js"></script> * <script> * goog.require('goog.debug.Logger'); * </script> * <script> * window.onload = function() { * goog.debug.Logger.getLogger('').info( * 'The page has finished loading'); * }; * </script> * </head> * <body></body> * </html> */ (function() { var scripts = document.getElementsByTagName('script'); var directoryPath = './'; var thisFile = 'test_bootstrap.js'; for (var i = 0; i < scripts.length; i++) { var src = scripts[i].src; var len = src.length; if (src.substr(len - thisFile.length) == thisFile) { directoryPath = src.substr(0, len - thisFile.length); break; } } // All of the files to load. Files are specified in the order they must be // loaded, NOT alphabetical order. var files = [ '../../../third_party/closure/goog/base.js', '../../deps.js' ]; for (var j = 0; j < files.length; j++) { document.write('<script type="text/javascript" src="' + directoryPath + files[j] + '"></script>'); } })();
'use strict'; exports.type = 'perItem'; exports.active = true; exports.description = 'removes useless stroke and fill attributes'; exports.params = { stroke: true, fill: true }; var shape = require('./_collections').elemsGroups.shape, regStrokeProps = /^stroke/, regFillProps = /^fill-/, styleOrScript = ['style', 'script'], hasStyleOrScript = false; /** * Remove useless stroke and fill attrs. * * @param {Object} item current iteration item * @param {Object} params plugin params * @return {Boolean} if false, item will be filtered out * * @author Kir Belevich */ exports.fn = function(item, params) { if (item.isElem(styleOrScript)) { hasStyleOrScript = true; } if (!hasStyleOrScript && item.isElem(shape) && !item.computedAttr('id')) { var stroke = params.stroke && item.computedAttr('stroke'), fill = params.fill && !item.computedAttr('fill', 'none'); // remove stroke* if ( params.stroke && (!stroke || stroke == 'none' || item.computedAttr('stroke-opacity', '0') || item.computedAttr('stroke-width', '0') ) ) { var parentStroke = item.parentNode.computedAttr('stroke'), declineStroke = parentStroke && parentStroke != 'none'; item.eachAttr(function(attr) { if (regStrokeProps.test(attr.name)) { item.removeAttr(attr.name); } }); if (declineStroke) item.addAttr({ name: 'stroke', value: 'none', prefix: '', local: 'stroke' }); } // remove fill* if ( params.fill && (!fill || item.computedAttr('fill-opacity', '0')) ) { item.eachAttr(function(attr) { if (regFillProps.test(attr.name)) { item.removeAttr(attr.name); } }); if (fill) { if (item.hasAttr('fill')) item.attr('fill').value = 'none'; else item.addAttr({ name: 'fill', value: 'none', prefix: '', local: 'fill' }); } } } };
tinyMCE.addI18n('ct.searchreplace_dlg',{findwhat:"Trobi el",replacewith:"Substituir per",direction:"Direcci\u00f3",up:"A munt",down:"A baix",mcase:"Coincidir maj\u00fascules i min\u00fascules",findnext:"Trobar seg\u00fcent",allreplaced:"Totes les aparicions de la cadena de recerca van ser reempla\u00e7ats.","searchnext_desc":"Buscar un altre cop",notfound:"La cerca s\'ha completat. La cadena de cerca no s\'ha pogut trobar.","search_title":"Buscar","replace_title":"Buscar/substituir",replaceall:"Substituir tot",replace:"Substituir"});
/*! * @overview Ember - JavaScript Application Framework * @copyright Copyright 2011-2015 Tilde Inc. and contributors * Portions Copyright 2006-2011 Strobe Inc. * Portions Copyright 2008-2011 Apple Inc. All rights reserved. * @license Licensed under MIT license * See https://raw.github.com/emberjs/ember.js/master/LICENSE * @version 1.11.0-beta.2 */ (function() { var enifed, requireModule, eriuqer, requirejs, Ember; var mainContext = this; (function() { Ember = this.Ember = this.Ember || {}; if (typeof Ember === 'undefined') { Ember = {}; }; function UNDEFINED() { } if (typeof Ember.__loader === 'undefined') { var registry = {}; var seen = {}; enifed = function(name, deps, callback) { var value = { }; if (!callback) { value.deps = []; value.callback = deps; } else { value.deps = deps; value.callback = callback; } registry[name] = value; }; requirejs = eriuqer = requireModule = function(name) { var s = seen[name]; if (s !== undefined) { return seen[name]; } if (s === UNDEFINED) { return undefined; } seen[name] = {}; if (!registry[name]) { throw new Error('Could not find module ' + name); } var mod = registry[name]; var deps = mod.deps; var callback = mod.callback; var reified = []; var exports; var length = deps.length; for (var i=0; i<length; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i], name))); } } var value = length === 0 ? callback.call(this) : callback.apply(this, reified); return seen[name] = exports || (value === undefined ? UNDEFINED : value); }; function resolve(child, name) { 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('/'); } requirejs._eak_seen = registry; Ember.__loader = { define: enifed, require: eriuqer, registry: registry }; } else { enifed = Ember.__loader.define; requirejs = eriuqer = requireModule = Ember.__loader.require; } })(); enifed('ember-debug', ['exports', 'ember-metal/core', 'ember-metal/error', 'ember-metal/logger', 'ember-metal/environment'], function (exports, Ember, EmberError, Logger, environment) { 'use strict'; exports._warnIfUsingStrippedFeatureFlags = _warnIfUsingStrippedFeatureFlags; /*global __fail__*/ Ember['default'].assert = function(desc, test) { var throwAssertion; if (Ember['default'].typeOf(test) === 'function') { throwAssertion = !test(); } else { throwAssertion = !test; } if (throwAssertion) { throw new EmberError['default']("Assertion Failed: " + desc); } }; /** Display a warning with the provided message. Ember build tools will remove any calls to `Ember.warn()` when doing a production build. @method warn @param {String} message A warning to display. @param {Boolean} test An optional boolean. If falsy, the warning will be displayed. */ Ember['default'].warn = function(message, test) { if (!test) { Logger['default'].warn("WARNING: "+message); if ('trace' in Logger['default']) { Logger['default'].trace(); } } }; /** Display a debug notice. Ember build tools will remove any calls to `Ember.debug()` when doing a production build. ```javascript Ember.debug('I\'m a debug notice!'); ``` @method debug @param {String} message A debug message to display. */ Ember['default'].debug = function(message) { Logger['default'].debug("DEBUG: "+message); }; /** Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only). Ember build tools will remove any calls to `Ember.deprecate()` when doing a production build. @method deprecate @param {String} message A description of the deprecation. @param {Boolean} test An optional boolean. If falsy, the deprecation will be displayed. @param {Object} options An optional object that can be used to pass in a `url` to the transition guide on the emberjs.com website. */ Ember['default'].deprecate = function(message, test, options) { var noDeprecation; if (typeof test === 'function') { noDeprecation = test(); } else { noDeprecation = test; } if (noDeprecation) { return; } if (Ember['default'].ENV.RAISE_ON_DEPRECATION) { throw new EmberError['default'](message); } var error; // When using new Error, we can't do the arguments check for Chrome. Alternatives are welcome try { __fail__.fail(); } catch (e) { error = e; } if (arguments.length === 3) { Ember['default'].assert('options argument to Ember.deprecate should be an object', options && typeof options === 'object'); if (options.url) { message += ' See ' + options.url + ' for more details.'; } } if (Ember['default'].LOG_STACKTRACE_ON_DEPRECATION && error.stack) { var stack; var stackStr = ''; if (error['arguments']) { // Chrome stack = error.stack.replace(/^\s+at\s+/gm, ''). replace(/^([^\(]+?)([\n$])/gm, '{anonymous}($1)$2'). replace(/^Object.<anonymous>\s*\(([^\)]+)\)/gm, '{anonymous}($1)').split('\n'); stack.shift(); } else { // Firefox stack = error.stack.replace(/(?:\n@:0)?\s+$/m, ''). replace(/^\(/gm, '{anonymous}(').split('\n'); } stackStr = "\n " + stack.slice(2).join("\n "); message = message + stackStr; } Logger['default'].warn("DEPRECATION: "+message); }; /** Alias an old, deprecated method with its new counterpart. Display a deprecation warning with the provided message and a stack trace (Chrome and Firefox only) when the assigned method is called. Ember build tools will not remove calls to `Ember.deprecateFunc()`, though no warnings will be shown in production. ```javascript Ember.oldMethod = Ember.deprecateFunc('Please use the new, updated method', Ember.newMethod); ``` @method deprecateFunc @param {String} message A description of the deprecation. @param {Function} func The new function called to replace its deprecated counterpart. @return {Function} a new function that wrapped the original function with a deprecation warning */ Ember['default'].deprecateFunc = function(message, func) { return function() { Ember['default'].deprecate(message); return func.apply(this, arguments); }; }; /** Run a function meant for debugging. Ember build tools will remove any calls to `Ember.runInDebug()` when doing a production build. ```javascript Ember.runInDebug(function() { Ember.Handlebars.EachView.reopen({ didInsertElement: function() { console.log('I\'m happy'); } }); }); ``` @method runInDebug @param {Function} func The function to be executed. @since 1.5.0 */ Ember['default'].runInDebug = function(func) { func(); }; /** Will call `Ember.warn()` if ENABLE_ALL_FEATURES, ENABLE_OPTIONAL_FEATURES, or any specific FEATURES flag is truthy. This method is called automatically in debug canary builds. @private @method _warnIfUsingStrippedFeatureFlags @return {void} */ function _warnIfUsingStrippedFeatureFlags(FEATURES, featuresWereStripped) { if (featuresWereStripped) { Ember['default'].warn('Ember.ENV.ENABLE_ALL_FEATURES is only available in canary builds.', !Ember['default'].ENV.ENABLE_ALL_FEATURES); Ember['default'].warn('Ember.ENV.ENABLE_OPTIONAL_FEATURES is only available in canary builds.', !Ember['default'].ENV.ENABLE_OPTIONAL_FEATURES); for (var key in FEATURES) { if (FEATURES.hasOwnProperty(key) && key !== 'isEnabled') { Ember['default'].warn('FEATURE["' + key + '"] is set as enabled, but FEATURE flags are only available in canary builds.', !FEATURES[key]); } } } } if (!Ember['default'].testing) { // Complain if they're using FEATURE flags in builds other than canary Ember['default'].FEATURES['features-stripped-test'] = true; var featuresWereStripped = true; delete Ember['default'].FEATURES['features-stripped-test']; _warnIfUsingStrippedFeatureFlags(Ember['default'].ENV.FEATURES, featuresWereStripped); // Inform the developer about the Ember Inspector if not installed. var isFirefox = typeof InstallTrigger !== 'undefined'; var isChrome = environment['default'].isChrome; if (typeof window !== 'undefined' && (isFirefox || isChrome) && window.addEventListener) { window.addEventListener("load", function() { if (document.documentElement && document.documentElement.dataset && !document.documentElement.dataset.emberExtension) { var downloadURL; if (isChrome) { downloadURL = 'https://chrome.google.com/webstore/detail/ember-inspector/bmdblncegkenkacieihfhpjfppoconhi'; } else if (isFirefox) { downloadURL = 'https://addons.mozilla.org/en-US/firefox/addon/ember-inspector/'; } Ember['default'].debug('For more advanced debugging, install the Ember Inspector from ' + downloadURL); } }, false); } } /* We are transitioning away from `ember.js` to `ember.debug.js` to make it much clearer that it is only for local development purposes. This flag value is changed by the tooling (by a simple string replacement) so that if `ember.js` (which must be output for backwards compat reasons) is used a nice helpful warning message will be printed out. */ var runningNonEmberDebugJS = false; if (runningNonEmberDebugJS) { Ember['default'].warn('Please use `ember.debug.js` instead of `ember.js` for development and debugging.'); } exports.runningNonEmberDebugJS = runningNonEmberDebugJS; }); enifed('ember-testing', ['ember-metal/core', 'ember-testing/initializers', 'ember-testing/support', 'ember-testing/setup_for_testing', 'ember-testing/test', 'ember-testing/adapters/adapter', 'ember-testing/adapters/qunit', 'ember-testing/helpers'], function (Ember, __dep1__, __dep2__, setupForTesting, Test, Adapter, QUnitAdapter) { 'use strict'; Ember['default'].Test = Test['default']; Ember['default'].Test.Adapter = Adapter['default']; Ember['default'].Test.QUnitAdapter = QUnitAdapter['default']; Ember['default'].setupForTesting = setupForTesting['default']; }); enifed('ember-testing/adapters/adapter', ['exports', 'ember-runtime/system/object'], function (exports, EmberObject) { 'use strict'; function K() { return this; } /** @module ember @submodule ember-testing */ /** The primary purpose of this class is to create hooks that can be implemented by an adapter for various test frameworks. @class Adapter @namespace Ember.Test */ var Adapter = EmberObject['default'].extend({ /** This callback will be called whenever an async operation is about to start. Override this to call your framework's methods that handle async operations. @public @method asyncStart */ asyncStart: K, /** This callback will be called whenever an async operation has completed. @public @method asyncEnd */ asyncEnd: K, /** Override this method with your testing framework's false assertion. This function is called whenever an exception occurs causing the testing promise to fail. QUnit example: ```javascript exception: function(error) { ok(false, error); }; ``` @public @method exception @param {String} error The exception to be raised. */ exception: function(error) { throw error; } }); exports['default'] = Adapter; }); enifed('ember-testing/adapters/qunit', ['exports', 'ember-testing/adapters/adapter', 'ember-metal/utils'], function (exports, Adapter, utils) { 'use strict'; exports['default'] = Adapter['default'].extend({ asyncStart: function() { QUnit.stop(); }, asyncEnd: function() { QUnit.start(); }, exception: function(error) { ok(false, utils.inspect(error)); } }); }); enifed('ember-testing/helpers', ['ember-metal/core', 'ember-metal/property_get', 'ember-metal/error', 'ember-metal/run_loop', 'ember-views/system/jquery', 'ember-testing/test'], function (Ember, property_get, EmberError, run, jQuery, Test) { 'use strict'; var helper = Test['default'].registerHelper; var asyncHelper = Test['default'].registerAsyncHelper; var countAsync = 0; function currentRouteName(app) { var appController = app.__container__.lookup('controller:application'); return property_get.get(appController, 'currentRouteName'); } function currentPath(app) { var appController = app.__container__.lookup('controller:application'); return property_get.get(appController, 'currentPath'); } function currentURL(app) { var router = app.__container__.lookup('router:main'); return property_get.get(router, 'location').getURL(); } function pauseTest() { Test['default'].adapter.asyncStart(); return new Ember['default'].RSVP.Promise(function() { }, 'TestAdapter paused promise'); } function focus(el) { if (el && el.is(':input, [contenteditable=true]')) { var type = el.prop('type'); if (type !== 'checkbox' && type !== 'radio' && type !== 'hidden') { run['default'](el, function() { // Firefox does not trigger the `focusin` event if the window // does not have focus. If the document doesn't have focus just // use trigger('focusin') instead. if (!document.hasFocus || document.hasFocus()) { this.focus(); } else { this.trigger('focusin'); } }); } } } function visit(app, url) { var router = app.__container__.lookup('router:main'); router.location.setURL(url); if (app._readinessDeferrals > 0) { router['initialURL'] = url; run['default'](app, 'advanceReadiness'); delete router['initialURL']; } else { run['default'](app.__deprecatedInstance__, 'handleURL', url); } return app.testHelpers.wait(); } function click(app, selector, context) { var $el = app.testHelpers.findWithAssert(selector, context); run['default']($el, 'mousedown'); focus($el); run['default']($el, 'mouseup'); run['default']($el, 'click'); return app.testHelpers.wait(); } function check(app, selector, context) { var $el = app.testHelpers.findWithAssert(selector, context); var type = $el.prop('type'); Ember['default'].assert('To check \'' + selector + '\', the input must be a checkbox', type === 'checkbox'); if (!$el.prop('checked')) { app.testHelpers.click(selector, context); } return app.testHelpers.wait(); } function uncheck(app, selector, context) { var $el = app.testHelpers.findWithAssert(selector, context); var type = $el.prop('type'); Ember['default'].assert('To uncheck \'' + selector + '\', the input must be a checkbox', type === 'checkbox'); if ($el.prop('checked')) { app.testHelpers.click(selector, context); } return app.testHelpers.wait(); } function triggerEvent(app, selector, contextOrType, typeOrOptions, possibleOptions) { var arity = arguments.length; var context, type, options; if (arity === 3) { // context and options are optional, so this is // app, selector, type context = null; type = contextOrType; options = {}; } else if (arity === 4) { // context and options are optional, so this is if (typeof typeOrOptions === "object") { // either // app, selector, type, options context = null; type = contextOrType; options = typeOrOptions; } else { // or // app, selector, context, type context = contextOrType; type = typeOrOptions; options = {}; } } else { context = contextOrType; type = typeOrOptions; options = possibleOptions; } var $el = app.testHelpers.findWithAssert(selector, context); var event = jQuery['default'].Event(type, options); run['default']($el, 'trigger', event); return app.testHelpers.wait(); } function keyEvent(app, selector, contextOrType, typeOrKeyCode, keyCode) { var context, type; if (typeof keyCode === 'undefined') { context = null; keyCode = typeOrKeyCode; type = contextOrType; } else { context = contextOrType; type = typeOrKeyCode; } return app.testHelpers.triggerEvent(selector, context, type, { keyCode: keyCode, which: keyCode }); } function fillIn(app, selector, contextOrText, text) { var $el, context; if (typeof text === 'undefined') { text = contextOrText; } else { context = contextOrText; } $el = app.testHelpers.findWithAssert(selector, context); focus($el); run['default'](function() { $el.val(text).change(); }); return app.testHelpers.wait(); } function findWithAssert(app, selector, context) { var $el = app.testHelpers.find(selector, context); if ($el.length === 0) { throw new EmberError['default']("Element " + selector + " not found."); } return $el; } function find(app, selector, context) { var $el; context = context || property_get.get(app, 'rootElement'); $el = app.$(selector, context); return $el; } function andThen(app, callback) { return app.testHelpers.wait(callback(app)); } function wait(app, value) { return Test['default'].promise(function(resolve) { // If this is the first async promise, kick off the async test if (++countAsync === 1) { Test['default'].adapter.asyncStart(); } // Every 10ms, poll for the async thing to have finished var watcher = setInterval(function() { var router = app.__container__.lookup('router:main'); // 1. If the router is loading, keep polling var routerIsLoading = router.router && !!router.router.activeTransition; if (routerIsLoading) { return; } // 2. If there are pending Ajax requests, keep polling if (Test['default'].pendingAjaxRequests) { return; } // 3. If there are scheduled timers or we are inside of a run loop, keep polling if (run['default'].hasScheduledTimers() || run['default'].currentRunLoop) { return; } if (Test['default'].waiters && Test['default'].waiters.any(function(waiter) { var context = waiter[0]; var callback = waiter[1]; return !callback.call(context); })) { return; } // Stop polling clearInterval(watcher); // If this is the last async promise, end the async test if (--countAsync === 0) { Test['default'].adapter.asyncEnd(); } // Synchronously resolve the promise run['default'](null, resolve, value); }, 10); }); } /** * Loads a route, sets up any controllers, and renders any templates associated * with the route as though a real user had triggered the route change while * using your app. * * Example: * * ```javascript * visit('posts/index').then(function() { * // assert something * }); * ``` * * @method visit * @param {String} url the name of the route * @return {RSVP.Promise} */ asyncHelper('visit', visit); /** * Clicks an element and triggers any actions triggered by the element's `click` * event. * * Example: * * ```javascript * click('.some-jQuery-selector').then(function() { * // assert something * }); * ``` * * @method click * @param {String} selector jQuery selector for finding element on the DOM * @return {RSVP.Promise} */ asyncHelper('click', click); /** * Simulates a key event, e.g. `keypress`, `keydown`, `keyup` with the desired keyCode * * Example: * * ```javascript * keyEvent('.some-jQuery-selector', 'keypress', 13).then(function() { * // assert something * }); * ``` * * @method keyEvent * @param {String} selector jQuery selector for finding element on the DOM * @param {String} type the type of key event, e.g. `keypress`, `keydown`, `keyup` * @param {Number} keyCode the keyCode of the simulated key event * @return {RSVP.Promise} * @since 1.5.0 */ asyncHelper('keyEvent', keyEvent); /** * Fills in an input element with some text. * * Example: * * ```javascript * fillIn('#email', 'you@example.com').then(function() { * // assert something * }); * ``` * * @method fillIn * @param {String} selector jQuery selector finding an input element on the DOM * to fill text with * @param {String} text text to place inside the input element * @return {RSVP.Promise} */ asyncHelper('fillIn', fillIn); /** * Finds an element in the context of the app's container element. A simple alias * for `app.$(selector)`. * * Example: * * ```javascript * var $el = find('.my-selector'); * ``` * * @method find * @param {String} selector jQuery string selector for element lookup * @return {Object} jQuery object representing the results of the query */ helper('find', find); /** * Like `find`, but throws an error if the element selector returns no results. * * Example: * * ```javascript * var $el = findWithAssert('.doesnt-exist'); // throws error * ``` * * @method findWithAssert * @param {String} selector jQuery selector string for finding an element within * the DOM * @return {Object} jQuery object representing the results of the query * @throws {Error} throws error if jQuery object returned has a length of 0 */ helper('findWithAssert', findWithAssert); /** Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed. This is most often used as the return value for the helper functions (see 'click', 'fillIn','visit',etc). Example: ```javascript Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit') return app.testHelpers.wait(); }); @method wait @param {Object} value The value to be returned. @return {RSVP.Promise} */ asyncHelper('wait', wait); asyncHelper('andThen', andThen); /** Returns the currently active route name. Example: ```javascript function validateRouteName(){ equal(currentRouteName(), 'some.path', "correct route was transitioned into."); } visit('/some/path').then(validateRouteName) ``` @method currentRouteName @return {Object} The name of the currently active route. @since 1.5.0 */ helper('currentRouteName', currentRouteName); /** Returns the current path. Example: ```javascript function validateURL(){ equal(currentPath(), 'some.path.index', "correct path was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentPath @return {Object} The currently active path. @since 1.5.0 */ helper('currentPath', currentPath); /** Returns the current URL. Example: ```javascript function validateURL(){ equal(currentURL(), '/some/path', "correct URL was transitioned into."); } click('#some-link-id').then(validateURL); ``` @method currentURL @return {Object} The currently active URL. @since 1.5.0 */ helper('currentURL', currentURL); /** Pauses the current test - this is useful for debugging while testing or for test-driving. It allows you to inspect the state of your application at any point. Example (The test will pause before clicking the button): ```javascript visit('/') return pauseTest(); click('.btn'); ``` @since 1.9.0 @method pauseTest @return {Object} A promise that will never resolve */ helper('pauseTest', pauseTest); /** Triggers the given DOM event on the element identified by the provided selector. Example: ```javascript triggerEvent('#some-elem-id', 'blur'); ``` This is actually used internally by the `keyEvent` helper like so: ```javascript triggerEvent('#some-elem-id', 'keypress', { keyCode: 13 }); ``` @method triggerEvent @param {String} selector jQuery selector for finding element on the DOM @param {String} [context] jQuery selector that will limit the selector argument to find only within the context's children @param {String} type The event type to be triggered. @param {Object} [options] The options to be passed to jQuery.Event. @return {RSVP.Promise} @since 1.5.0 */ asyncHelper('triggerEvent', triggerEvent); }); enifed('ember-testing/initializers', ['ember-runtime/system/lazy_load'], function (lazy_load) { 'use strict'; var name = 'deferReadiness in `testing` mode'; lazy_load.onLoad('Ember.Application', function(Application) { if (!Application.initializers[name]) { Application.initializer({ name: name, initialize: function(registry, application) { if (application.testing) { application.deferReadiness(); } } }); } }); }); enifed('ember-testing/setup_for_testing', ['exports', 'ember-metal/core', 'ember-testing/adapters/qunit', 'ember-views/system/jquery'], function (exports, Ember, QUnitAdapter, jQuery) { 'use strict'; var Test, requests; function incrementAjaxPendingRequests(_, xhr) { requests.push(xhr); Test.pendingAjaxRequests = requests.length; } function decrementAjaxPendingRequests(_, xhr) { for (var i=0;i<requests.length;i++) { if (xhr === requests[i]) { requests.splice(i, 1); } } Test.pendingAjaxRequests = requests.length; } /** Sets Ember up for testing. This is useful to perform basic setup steps in order to unit test. Use `App.setupForTesting` to perform integration tests (full application testing). @method setupForTesting @namespace Ember @since 1.5.0 */ function setupForTesting() { if (!Test) { Test = requireModule('ember-testing/test')['default']; } Ember['default'].testing = true; // if adapter is not manually set default to QUnit if (!Test.adapter) { Test.adapter = QUnitAdapter['default'].create(); } requests = []; Test.pendingAjaxRequests = requests.length; jQuery['default'](document).off('ajaxSend', incrementAjaxPendingRequests); jQuery['default'](document).off('ajaxComplete', decrementAjaxPendingRequests); jQuery['default'](document).on('ajaxSend', incrementAjaxPendingRequests); jQuery['default'](document).on('ajaxComplete', decrementAjaxPendingRequests); } exports['default'] = setupForTesting; }); enifed('ember-testing/support', ['ember-metal/core', 'ember-views/system/jquery', 'ember-metal/environment'], function (Ember, jQuery, environment) { 'use strict'; var $ = jQuery['default']; /** This method creates a checkbox and triggers the click event to fire the passed in handler. It is used to correct for a bug in older versions of jQuery (e.g 1.8.3). @private @method testCheckboxClick */ function testCheckboxClick(handler) { $('<input type="checkbox">') .css({ position: 'absolute', left: '-1000px', top: '-1000px' }) .appendTo('body') .on('click', handler) .trigger('click') .remove(); } if (environment['default'].hasDOM) { $(function() { /* Determine whether a checkbox checked using jQuery's "click" method will have the correct value for its checked property. If we determine that the current jQuery version exhibits this behavior, patch it to work correctly as in the commit for the actual fix: https://github.com/jquery/jquery/commit/1fb2f92. */ testCheckboxClick(function() { if (!this.checked && !$.event.special.click) { $.event.special.click = { // For checkbox, fire native event so checked state will be right trigger: function() { if ($.nodeName(this, "input") && this.type === "checkbox" && this.click) { this.click(); return false; } } }; } }); // Try again to verify that the patch took effect or blow up. testCheckboxClick(function() { Ember['default'].warn("clicked checkboxes should be checked! the jQuery patch didn't work", this.checked); }); }); } }); enifed('ember-testing/test', ['exports', 'ember-metal/core', 'ember-metal/run_loop', 'ember-metal/platform/create', 'ember-runtime/ext/rsvp', 'ember-testing/setup_for_testing', 'ember-application/system/application'], function (exports, Ember, emberRun, create, RSVP, setupForTesting, EmberApplication) { 'use strict'; var slice = [].slice; var helpers = {}; var injectHelpersCallbacks = []; /** This is a container for an assortment of testing related functionality: * Choose your default test adapter (for your framework of choice). * Register/Unregister additional test helpers. * Setup callbacks to be fired when the test helpers are injected into your application. @class Test @namespace Ember */ var Test = { /** Hash containing all known test helpers. @property _helpers @private @since 1.7.0 */ _helpers: helpers, /** `registerHelper` is used to register a test helper that will be injected when `App.injectTestHelpers` is called. The helper method will always be called with the current Application as the first parameter. For example: ```javascript Ember.Test.registerHelper('boot', function(app) { Ember.run(app, app.advanceReadiness); }); ``` This helper can later be called without arguments because it will be called with `app` as the first parameter. ```javascript App = Ember.Application.create(); App.injectTestHelpers(); boot(); ``` @public @method registerHelper @param {String} name The name of the helper method to add. @param {Function} helperMethod @param options {Object} */ registerHelper: function(name, helperMethod) { helpers[name] = { method: helperMethod, meta: { wait: false } }; }, /** `registerAsyncHelper` is used to register an async test helper that will be injected when `App.injectTestHelpers` is called. The helper method will always be called with the current Application as the first parameter. For example: ```javascript Ember.Test.registerAsyncHelper('boot', function(app) { Ember.run(app, app.advanceReadiness); }); ``` The advantage of an async helper is that it will not run until the last async helper has completed. All async helpers after it will wait for it complete before running. For example: ```javascript Ember.Test.registerAsyncHelper('deletePost', function(app, postId) { click('.delete-' + postId); }); // ... in your test visit('/post/2'); deletePost(2); visit('/post/3'); deletePost(3); ``` @public @method registerAsyncHelper @param {String} name The name of the helper method to add. @param {Function} helperMethod @since 1.2.0 */ registerAsyncHelper: function(name, helperMethod) { helpers[name] = { method: helperMethod, meta: { wait: true } }; }, /** Remove a previously added helper method. Example: ```javascript Ember.Test.unregisterHelper('wait'); ``` @public @method unregisterHelper @param {String} name The helper to remove. */ unregisterHelper: function(name) { delete helpers[name]; delete Test.Promise.prototype[name]; }, /** Used to register callbacks to be fired whenever `App.injectTestHelpers` is called. The callback will receive the current application as an argument. Example: ```javascript Ember.Test.onInjectHelpers(function() { Ember.$(document).ajaxSend(function() { Test.pendingAjaxRequests++; }); Ember.$(document).ajaxComplete(function() { Test.pendingAjaxRequests--; }); }); ``` @public @method onInjectHelpers @param {Function} callback The function to be called. */ onInjectHelpers: function(callback) { injectHelpersCallbacks.push(callback); }, /** This returns a thenable tailored for testing. It catches failed `onSuccess` callbacks and invokes the `Ember.Test.adapter.exception` callback in the last chained then. This method should be returned by async helpers such as `wait`. @public @method promise @param {Function} resolver The function used to resolve the promise. */ promise: function(resolver) { return new Test.Promise(resolver); }, /** Used to allow ember-testing to communicate with a specific testing framework. You can manually set it before calling `App.setupForTesting()`. Example: ```javascript Ember.Test.adapter = MyCustomAdapter.create() ``` If you do not set it, ember-testing will default to `Ember.Test.QUnitAdapter`. @public @property adapter @type {Class} The adapter to be used. @default Ember.Test.QUnitAdapter */ adapter: null, /** Replacement for `Ember.RSVP.resolve` The only difference is this uses an instance of `Ember.Test.Promise` @public @method resolve @param {Mixed} The value to resolve @since 1.2.0 */ resolve: function(val) { return Test.promise(function(resolve) { return resolve(val); }); }, /** This allows ember-testing to play nicely with other asynchronous events, such as an application that is waiting for a CSS3 transition or an IndexDB transaction. For example: ```javascript Ember.Test.registerWaiter(function() { return myPendingTransactions() == 0; }); ``` The `context` argument allows you to optionally specify the `this` with which your callback will be invoked. For example: ```javascript Ember.Test.registerWaiter(MyDB, MyDB.hasPendingTransactions); ``` @public @method registerWaiter @param {Object} context (optional) @param {Function} callback @since 1.2.0 */ registerWaiter: function(context, callback) { if (arguments.length === 1) { callback = context; context = null; } if (!this.waiters) { this.waiters = Ember['default'].A(); } this.waiters.push([context, callback]); }, /** `unregisterWaiter` is used to unregister a callback that was registered with `registerWaiter`. @public @method unregisterWaiter @param {Object} context (optional) @param {Function} callback @since 1.2.0 */ unregisterWaiter: function(context, callback) { if (!this.waiters) { return; } if (arguments.length === 1) { callback = context; context = null; } this.waiters = Ember['default'].A(this.waiters.filter(function(elt) { return !(elt[0] === context && elt[1] === callback); })); } }; function helper(app, name) { var fn = helpers[name].method; var meta = helpers[name].meta; return function() { var args = slice.call(arguments); var lastPromise = Test.lastPromise; args.unshift(app); // some helpers are not async and // need to return a value immediately. // example: `find` if (!meta.wait) { return fn.apply(app, args); } if (!lastPromise) { // It's the first async helper in current context lastPromise = fn.apply(app, args); } else { // wait for last helper's promise to resolve and then // execute. To be safe, we need to tell the adapter we're going // asynchronous here, because fn may not be invoked before we // return. Test.adapter.asyncStart(); run(function() { lastPromise = Test.resolve(lastPromise).then(function() { try { return fn.apply(app, args); } finally { Test.adapter.asyncEnd(); } }); }); } return lastPromise; }; } function run(fn) { if (!emberRun['default'].currentRunLoop) { emberRun['default'](fn); } else { fn(); } } EmberApplication['default'].reopen({ /** This property contains the testing helpers for the current application. These are created once you call `injectTestHelpers` on your `Ember.Application` instance. The included helpers are also available on the `window` object by default, but can be used from this object on the individual application also. @property testHelpers @type {Object} @default {} */ testHelpers: {}, /** This property will contain the original methods that were registered on the `helperContainer` before `injectTestHelpers` is called. When `removeTestHelpers` is called, these methods are restored to the `helperContainer`. @property originalMethods @type {Object} @default {} @private @since 1.3.0 */ originalMethods: {}, /** This property indicates whether or not this application is currently in testing mode. This is set when `setupForTesting` is called on the current application. @property testing @type {Boolean} @default false @since 1.3.0 */ testing: false, /** This hook defers the readiness of the application, so that you can start the app when your tests are ready to run. It also sets the router's location to 'none', so that the window's location will not be modified (preventing both accidental leaking of state between tests and interference with your testing framework). Example: ``` App.setupForTesting(); ``` @method setupForTesting */ setupForTesting: function() { setupForTesting['default'](); this.testing = true; this.Router.reopen({ location: 'none' }); }, /** This will be used as the container to inject the test helpers into. By default the helpers are injected into `window`. @property helperContainer @type {Object} The object to be used for test helpers. @default window @since 1.2.0 */ helperContainer: null, /** This injects the test helpers into the `helperContainer` object. If an object is provided it will be used as the helperContainer. If `helperContainer` is not set it will default to `window`. If a function of the same name has already been defined it will be cached (so that it can be reset if the helper is removed with `unregisterHelper` or `removeTestHelpers`). Any callbacks registered with `onInjectHelpers` will be called once the helpers have been injected. Example: ``` App.injectTestHelpers(); ``` @method injectTestHelpers */ injectTestHelpers: function(helperContainer) { if (helperContainer) { this.helperContainer = helperContainer; } else { this.helperContainer = window; } this.testHelpers = {}; for (var name in helpers) { this.originalMethods[name] = this.helperContainer[name]; this.testHelpers[name] = this.helperContainer[name] = helper(this, name); protoWrap(Test.Promise.prototype, name, helper(this, name), helpers[name].meta.wait); } for (var i = 0, l = injectHelpersCallbacks.length; i < l; i++) { injectHelpersCallbacks[i](this); } }, /** This removes all helpers that have been registered, and resets and functions that were overridden by the helpers. Example: ```javascript App.removeTestHelpers(); ``` @public @method removeTestHelpers */ removeTestHelpers: function() { if (!this.helperContainer) { return; } for (var name in helpers) { this.helperContainer[name] = this.originalMethods[name]; delete this.testHelpers[name]; delete this.originalMethods[name]; } } }); // This method is no longer needed // But still here for backwards compatibility // of helper chaining function protoWrap(proto, name, callback, isAsync) { proto[name] = function() { var args = arguments; if (isAsync) { return callback.apply(this, args); } else { return this.then(function() { return callback.apply(this, args); }); } }; } Test.Promise = function() { RSVP['default'].Promise.apply(this, arguments); Test.lastPromise = this; }; Test.Promise.prototype = create['default'](RSVP['default'].Promise.prototype); Test.Promise.prototype.constructor = Test.Promise; // Patch `then` to isolate async methods // specifically `Ember.Test.lastPromise` var originalThen = RSVP['default'].Promise.prototype.then; Test.Promise.prototype.then = function(onSuccess, onFailure) { return originalThen.call(this, function(val) { return isolate(onSuccess, val); }, onFailure); }; // This method isolates nested async methods // so that they don't conflict with other last promises. // // 1. Set `Ember.Test.lastPromise` to null // 2. Invoke method // 3. Return the last promise created during method // 4. Restore `Ember.Test.lastPromise` to original value function isolate(fn, val) { var value, lastPromise; // Reset lastPromise for nested helpers Test.lastPromise = null; value = fn(val); lastPromise = Test.lastPromise; // If the method returned a promise // return that promise. If not, // return the last async helper's promise if ((value && (value instanceof Test.Promise)) || !lastPromise) { return value; } else { run(function() { lastPromise = Test.resolve(lastPromise).then(function() { return value; }); }); return lastPromise; } } exports['default'] = Test; }); enifed("htmlbars-test-helpers", ["exports"], function(__exports__) { "use strict"; function equalInnerHTML(fragment, html) { var actualHTML = normalizeInnerHTML(fragment.innerHTML); QUnit.push(actualHTML === html, actualHTML, html); } __exports__.equalInnerHTML = equalInnerHTML;function equalHTML(node, html) { var fragment; if (!node.nodeType && node.length) { fragment = document.createDocumentFragment(); while (node[0]) { fragment.appendChild(node[0]); } } else { fragment = node; } var div = document.createElement("div"); div.appendChild(fragment.cloneNode(true)); equalInnerHTML(div, html); } __exports__.equalHTML = equalHTML;// detect weird IE8 html strings var ie8InnerHTMLTestElement = document.createElement('div'); ie8InnerHTMLTestElement.setAttribute('id', 'womp'); var ie8InnerHTML = (ie8InnerHTMLTestElement.outerHTML.indexOf('id=womp') > -1); // detect side-effects of cloning svg elements in IE9-11 var ieSVGInnerHTML = (function () { if (!document.createElementNS) { return false; } var div = document.createElement('div'); var node = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); div.appendChild(node); var clone = div.cloneNode(true); return clone.innerHTML === '<svg xmlns="http://www.w3.org/2000/svg" />'; })(); function normalizeInnerHTML(actualHTML) { if (ie8InnerHTML) { // drop newlines in IE8 actualHTML = actualHTML.replace(/\r\n/gm, ''); // downcase ALLCAPS tags in IE8 actualHTML = actualHTML.replace(/<\/?[A-Z\-]+/gi, function(tag){ return tag.toLowerCase(); }); // quote ids in IE8 actualHTML = actualHTML.replace(/id=([^ >]+)/gi, function(match, id){ return 'id="'+id+'"'; }); // IE8 adds ':' to some tags // <keygen> becomes <:keygen> actualHTML = actualHTML.replace(/<(\/?):([^ >]+)/gi, function(match, slash, tag){ return '<'+slash+tag; }); // Normalize the style attribute actualHTML = actualHTML.replace(/style="(.+?)"/gi, function(match, val){ return 'style="'+val.toLowerCase()+';"'; }); } if (ieSVGInnerHTML) { // Replace `<svg xmlns="http://www.w3.org/2000/svg" height="50%" />` with `<svg height="50%"></svg>`, etc. // drop namespace attribute actualHTML = actualHTML.replace(/ xmlns="[^"]+"/, ''); // replace self-closing elements actualHTML = actualHTML.replace(/<([^ >]+) [^\/>]*\/>/gi, function(tag, tagName) { return tag.slice(0, tag.length - 3) + '></' + tagName + '>'; }); } return actualHTML; } __exports__.normalizeInnerHTML = normalizeInnerHTML;// detect weird IE8 checked element string var checkedInput = document.createElement('input'); checkedInput.setAttribute('checked', 'checked'); var checkedInputString = checkedInput.outerHTML; function isCheckedInputHTML(element) { equal(element.outerHTML, checkedInputString); } __exports__.isCheckedInputHTML = isCheckedInputHTML;// check which property has the node's text content var textProperty = document.createElement('div').textContent === undefined ? 'innerText' : 'textContent'; function getTextContent(el) { // textNode if (el.nodeType === 3) { return el.nodeValue; } else { return el[textProperty]; } } __exports__.getTextContent = getTextContent;// IE8 does not have Object.create, so use a polyfill if needed. // Polyfill based on Mozilla's (MDN) function createObject(obj) { if (typeof Object.create === 'function') { return Object.create(obj); } else { var Temp = function() {}; Temp.prototype = obj; return new Temp(); } } __exports__.createObject = createObject; }); requireModule("ember-testing"); })();
var isSpace = require('./isSpace'); /** * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace * character of `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the index of the last non-whitespace character. */ function trimmedRightIndex(string) { var index = string.length; while (index-- && isSpace(string.charCodeAt(index))) {} return index; } module.exports = trimmedRightIndex;
var HTTP = require('http'); function testDuplicateRoutesError(test) { var router = new HTTP_Router_Server(); router.get('/pokemon/:id/abilities', function handler() { }); try { router.get('/pokemon/:whatever/abilities', function handler() { }); test.ok(false, 'This should have thrown an error'); test.done(); } catch (error) { test.ok( error.toString().contains( 'Duplicate route defined for uri pattern' ) ); test.done(); } } function testRouteSpecificity(test) { var router = new HTTP_Router_Server(), server = HTTP.createServer(router.serve); server.listen(Network_Mapper.createAPIMapping().http_port); var complete_count = 0, expected = 4; function incrementCompleteCount() { complete_count++; if (complete_count === expected) { server.close(); test.done(); } } router.get('/foo/:id', function handler(... response) { test.ok(false, 'We should not be here'); response.send({ }); test.done(); }); router.get('/foo/specific', function handler(request, response) { test.equals(request.url, '/foo/specific'); response.send({ }); incrementCompleteCount(); }); Querier.get('/api/foo/specific', { }, function finisher() { }); router.get('/bar/:id', function handler(request, response) { test.equals(request.url, '/bar/123'); response.send({ }); incrementCompleteCount(); }); router.get('/bar/specific', function handler(... response) { test.ok(false, 'We should not be here'); response.send({ }); test.done(); }); Querier.get('/api/bar/123', { }, function finisher() { }); router.get('/baz/specific', function handler(request, response) { test.equals(request.url, '/baz/specific'); response.send({ }); incrementCompleteCount(); }); router.get('/baz/:id', function handler(... response) { test.ok(false, 'We should not be here'); response.send({ }); test.done(); }); Querier.get('/api/baz/specific', { }, function finisher() { }); router.get('/wat/specific', function handler(... response) { test.ok(false, 'We should not be here'); response.send({ }); server.close(function handler() { Network_Mapper.deleteAPIMapping(); test.done(); }); }); router.get('/wat/:id', function handler(request, response) { test.equals(request.url, '/wat/123'); response.send({ }); incrementCompleteCount(); }); Querier.get('/api/wat/123', { } , function finisher() { }); } function serve(test) { // The router should trigger a response error // if an invalid HTTP method was specified: WithInvalidHTTPMethod: { let mock_headers = { }; let mock_native_request = { headers: mock_headers, url: '/', method: 'nonexistent_method' }; let mock_request = (new HTTP_Request()) .setNativeRequest(mock_native_request); let mock_response = (new HTTP_Response()) .setUrl('/'); mock_response.error = function handleError(error) { test.ok(error instanceof Error_InvalidHttpMethod); }; let router = new HTTP_Router_Server(); router.serve(mock_request, mock_response); } test.done(); } module.exports = { testDuplicateRoutesError, testRouteSpecificity, serve };
import { select as d3_select } from 'd3-selection'; import { presetManager } from '../../presets'; import { t, localizer } from '../../core/localizer'; import { actionAddEntity } from '../../actions/add_entity'; import { actionAddMember } from '../../actions/add_member'; import { actionChangeMember } from '../../actions/change_member'; import { actionDeleteMembers } from '../../actions/delete_members'; import { modeSelect } from '../../modes/select'; import { osmEntity, osmRelation } from '../../osm'; import { services } from '../../services'; import { svgIcon } from '../../svg/icon'; import { uiCombobox } from '../combobox'; import { uiSection } from '../section'; import { uiTooltip } from '../tooltip'; import { utilArrayGroupBy, utilArrayIntersection } from '../../util/array'; import { utilDisplayName, utilNoAuto, utilHighlightEntities, utilUniqueDomId } from '../../util'; export function uiSectionRawMembershipEditor(context) { var section = uiSection('raw-membership-editor', context) .shouldDisplay(function() { return _entityIDs && _entityIDs.length; }) .label(function() { var parents = getSharedParentRelations(); var gt = parents.length > _maxMemberships ? '>' : ''; var count = gt + parents.slice(0, _maxMemberships).length; return t.html('inspector.title_count', { title: { html: t.html('inspector.relations') }, count: count }); }) .disclosureContent(renderDisclosureContent); var taginfo = services.taginfo; var nearbyCombo = uiCombobox(context, 'parent-relation') .minItems(1) .fetcher(fetchNearbyRelations) .itemsMouseEnter(function(d3_event, d) { if (d.relation) utilHighlightEntities([d.relation.id], true, context); }) .itemsMouseLeave(function(d3_event, d) { if (d.relation) utilHighlightEntities([d.relation.id], false, context); }); var _inChange = false; var _entityIDs = []; var _showBlank; var _maxMemberships = 1000; function getSharedParentRelations() { var parents = []; for (var i = 0; i < _entityIDs.length; i++) { var entity = context.graph().hasEntity(_entityIDs[i]); if (!entity) continue; if (i === 0) { parents = context.graph().parentRelations(entity); } else { parents = utilArrayIntersection(parents, context.graph().parentRelations(entity)); } if (!parents.length) break; } return parents; } function getMemberships() { var memberships = []; var relations = getSharedParentRelations().slice(0, _maxMemberships); var isMultiselect = _entityIDs.length > 1; var i, relation, membership, index, member, indexedMember; for (i = 0; i < relations.length; i++) { relation = relations[i]; membership = { relation: relation, members: [], hash: osmEntity.key(relation) }; for (index = 0; index < relation.members.length; index++) { member = relation.members[index]; if (_entityIDs.indexOf(member.id) !== -1) { indexedMember = Object.assign({}, member, { index: index }); membership.members.push(indexedMember); membership.hash += ',' + index.toString(); if (!isMultiselect) { // For single selections, list one entry per membership per relation. // For multiselections, list one entry per relation. memberships.push(membership); membership = { relation: relation, members: [], hash: osmEntity.key(relation) }; } } } if (membership.members.length) memberships.push(membership); } memberships.forEach(function(membership) { membership.domId = utilUniqueDomId('membership-' + membership.relation.id); var roles = []; membership.members.forEach(function(member) { if (roles.indexOf(member.role) === -1) roles.push(member.role); }); membership.role = roles.length === 1 ? roles[0] : roles; }); return memberships; } function selectRelation(d3_event, d) { d3_event.preventDefault(); // remove the hover-highlight styling utilHighlightEntities([d.relation.id], false, context); context.enter(modeSelect(context, [d.relation.id])); } function zoomToRelation(d3_event, d) { d3_event.preventDefault(); var entity = context.entity(d.relation.id); context.map().zoomToEase(entity); // highlight the relation in case it wasn't previously on-screen utilHighlightEntities([d.relation.id], true, context); } function changeRole(d3_event, d) { if (d === 0) return; // called on newrow (shouldn't happen) if (_inChange) return; // avoid accidental recursive call #5731 var newRole = context.cleanRelationRole(d3_select(this).property('value')); if (!newRole.trim() && typeof d.role !== 'string') return; var membersToUpdate = d.members.filter(function(member) { return member.role !== newRole; }); if (membersToUpdate.length) { _inChange = true; context.perform( function actionChangeMemberRoles(graph) { membersToUpdate.forEach(function(member) { var newMember = Object.assign({}, member, { role: newRole }); delete newMember.index; graph = actionChangeMember(d.relation.id, newMember, member.index)(graph); }); return graph; }, t('operations.change_role.annotation', { n: membersToUpdate.length }) ); context.validator().validate(); } _inChange = false; } function addMembership(d, role) { this.blur(); // avoid keeping focus on the button _showBlank = false; function actionAddMembers(relationId, ids, role) { return function(graph) { for (var i in ids) { var member = { id: ids[i], type: graph.entity(ids[i]).type, role: role }; graph = actionAddMember(relationId, member)(graph); } return graph; }; } if (d.relation) { context.perform( actionAddMembers(d.relation.id, _entityIDs, role), t('operations.add_member.annotation', { n: _entityIDs.length }) ); context.validator().validate(); } else { var relation = osmRelation(); context.perform( actionAddEntity(relation), actionAddMembers(relation.id, _entityIDs, role), t('operations.add.annotation.relation') ); // changing the mode also runs `validate` context.enter(modeSelect(context, [relation.id]).newFeature(true)); } } function deleteMembership(d3_event, d) { this.blur(); // avoid keeping focus on the button if (d === 0) return; // called on newrow (shouldn't happen) // remove the hover-highlight styling utilHighlightEntities([d.relation.id], false, context); var indexes = d.members.map(function(member) { return member.index; }); context.perform( actionDeleteMembers(d.relation.id, indexes), t('operations.delete_member.annotation', { n: _entityIDs.length }) ); context.validator().validate(); } function fetchNearbyRelations(q, callback) { var newRelation = { relation: null, value: t('inspector.new_relation'), display: t.html('inspector.new_relation') }; var entityID = _entityIDs[0]; var result = []; var graph = context.graph(); function baseDisplayLabel(entity) { var matched = presetManager.match(entity, graph); var presetName = (matched && matched.name()) || t('inspector.relation'); var entityName = utilDisplayName(entity) || ''; return presetName + ' ' + entityName; } var explicitRelation = q && context.hasEntity(q.toLowerCase()); if (explicitRelation && explicitRelation.type === 'relation' && explicitRelation.id !== entityID) { // loaded relation is specified explicitly, only show that result.push({ relation: explicitRelation, value: baseDisplayLabel(explicitRelation) + ' ' + explicitRelation.id }); } else { context.history().intersects(context.map().extent()).forEach(function(entity) { if (entity.type !== 'relation' || entity.id === entityID) return; var value = baseDisplayLabel(entity); if (q && (value + ' ' + entity.id).toLowerCase().indexOf(q.toLowerCase()) === -1) return; result.push({ relation: entity, value: value }); }); result.sort(function(a, b) { return osmRelation.creationOrder(a.relation, b.relation); }); // Dedupe identical names by appending relation id - see #2891 var dupeGroups = Object.values(utilArrayGroupBy(result, 'value')) .filter(function(v) { return v.length > 1; }); dupeGroups.forEach(function(group) { group.forEach(function(obj) { obj.value += ' ' + obj.relation.id; }); }); } result.forEach(function(obj) { obj.title = obj.value; }); result.unshift(newRelation); callback(result); } function renderDisclosureContent(selection) { var memberships = getMemberships(); var list = selection.selectAll('.member-list') .data([0]); list = list.enter() .append('ul') .attr('class', 'member-list') .merge(list); var items = list.selectAll('li.member-row-normal') .data(memberships, function(d) { return d.hash; }); items.exit() .each(unbind) .remove(); // Enter var itemsEnter = items.enter() .append('li') .attr('class', 'member-row member-row-normal form-field'); // highlight the relation in the map while hovering on the list item itemsEnter.on('mouseover', function(d3_event, d) { utilHighlightEntities([d.relation.id], true, context); }) .on('mouseout', function(d3_event, d) { utilHighlightEntities([d.relation.id], false, context); }); var labelEnter = itemsEnter .append('label') .attr('class', 'field-label') .attr('for', function(d) { return d.domId; }); var labelLink = labelEnter .append('span') .attr('class', 'label-text') .append('a') .attr('href', '#') .on('click', selectRelation); labelLink .append('span') .attr('class', 'member-entity-type') .text(function(d) { var matched = presetManager.match(d.relation, context.graph()); return (matched && matched.name()) || t.html('inspector.relation'); }); labelLink .append('span') .attr('class', 'member-entity-name') .text(function(d) { return utilDisplayName(d.relation); }); labelEnter .append('button') .attr('class', 'remove member-delete') .attr('title', t('icons.remove')) .call(svgIcon('#iD-operation-delete')) .on('click', deleteMembership); labelEnter .append('button') .attr('class', 'member-zoom') .attr('title', t('icons.zoom_to')) .call(svgIcon('#iD-icon-framed-dot', 'monochrome')) .on('click', zoomToRelation); var wrapEnter = itemsEnter .append('div') .attr('class', 'form-field-input-wrap form-field-input-member'); wrapEnter .append('input') .attr('class', 'member-role') .attr('id', function(d) { return d.domId; }) .property('type', 'text') .property('value', function(d) { return typeof d.role === 'string' ? d.role : ''; }) .attr('title', function(d) { return Array.isArray(d.role) ? d.role.filter(Boolean).join('\n') : d.role; }) .attr('placeholder', function(d) { return Array.isArray(d.role) ? t('inspector.multiple_roles') : t('inspector.role'); }) .classed('mixed', function(d) { return Array.isArray(d.role); }) .call(utilNoAuto) .on('blur', changeRole) .on('change', changeRole); if (taginfo) { wrapEnter.each(bindTypeahead); } var newMembership = list.selectAll('.member-row-new') .data(_showBlank ? [0] : []); // Exit newMembership.exit() .remove(); // Enter var newMembershipEnter = newMembership.enter() .append('li') .attr('class', 'member-row member-row-new form-field'); var newLabelEnter = newMembershipEnter .append('label') .attr('class', 'field-label'); newLabelEnter .append('input') .attr('placeholder', t('inspector.choose_relation')) .attr('type', 'text') .attr('class', 'member-entity-input') .call(utilNoAuto); newLabelEnter .append('button') .attr('class', 'remove member-delete') .attr('title', t('icons.remove')) .call(svgIcon('#iD-operation-delete')) .on('click', function() { list.selectAll('.member-row-new') .remove(); }); var newWrapEnter = newMembershipEnter .append('div') .attr('class', 'form-field-input-wrap form-field-input-member'); newWrapEnter .append('input') .attr('class', 'member-role') .property('type', 'text') .attr('placeholder', t('inspector.role')) .call(utilNoAuto); // Update newMembership = newMembership .merge(newMembershipEnter); newMembership.selectAll('.member-entity-input') .on('blur', cancelEntity) // if it wasn't accepted normally, cancel it .call(nearbyCombo .on('accept', acceptEntity) .on('cancel', cancelEntity) ); // Container for the Add button var addRow = selection.selectAll('.add-row') .data([0]); // enter var addRowEnter = addRow.enter() .append('div') .attr('class', 'add-row'); var addRelationButton = addRowEnter .append('button') .attr('class', 'add-relation') .attr('aria-label', t('inspector.add_to_relation')); addRelationButton .call(svgIcon('#iD-icon-plus', 'light')); addRelationButton .call(uiTooltip().title(t.html('inspector.add_to_relation')).placement(localizer.textDirection() === 'ltr' ? 'right' : 'left')); addRowEnter .append('div') .attr('class', 'space-value'); // preserve space addRowEnter .append('div') .attr('class', 'space-buttons'); // preserve space // update addRow = addRow .merge(addRowEnter); addRow.select('.add-relation') .on('click', function() { _showBlank = true; section.reRender(); list.selectAll('.member-entity-input').node().focus(); }); function acceptEntity(d) { if (!d) { cancelEntity(); return; } // remove hover-higlighting if (d.relation) utilHighlightEntities([d.relation.id], false, context); var role = context.cleanRelationRole(list.selectAll('.member-row-new .member-role').property('value')); addMembership(d, role); } function cancelEntity() { var input = newMembership.selectAll('.member-entity-input'); input.property('value', ''); // remove hover-higlighting context.surface().selectAll('.highlighted') .classed('highlighted', false); } function bindTypeahead(d) { var row = d3_select(this); var role = row.selectAll('input.member-role'); var origValue = role.property('value'); function sort(value, data) { var sameletter = []; var other = []; for (var i = 0; i < data.length; i++) { if (data[i].value.substring(0, value.length) === value) { sameletter.push(data[i]); } else { other.push(data[i]); } } return sameletter.concat(other); } role.call(uiCombobox(context, 'member-role') .fetcher(function(role, callback) { var rtype = d.relation.tags.type; taginfo.roles({ debounce: true, rtype: rtype || '', geometry: context.graph().geometry(_entityIDs[0]), query: role }, function(err, data) { if (!err) callback(sort(role, data)); }); }) .on('cancel', function() { role.property('value', origValue); }) ); } function unbind() { var row = d3_select(this); row.selectAll('input.member-role') .call(uiCombobox.off, context); } } section.entityIDs = function(val) { if (!arguments.length) return _entityIDs; _entityIDs = val; _showBlank = false; return section; }; return section; }
"use strict"; module.exports = { };
var Minimist = require('minimist'); class ArgHelper { getArgs() { if (this.args === null) { this.args = Minimist(process.argv.slice(2)); } return this.args; } setAliases(aliases) { this.aliases = aliases; this.reverse_aliases = ObjectHelper.invert(aliases); } getValue(flag) { var args = this.getArgs(); if (args[flag] !== undefined) { return args[flag]; } var alias = this.getAliasForFlag(flag); if (alias) { return args[alias]; } return undefined; } getOrDefault(flag, default_value) { if (!this.hasValue(flag)) { return default_value; } return this.getValue(flag); } hasValue(flag) { return this.getValue(flag) !== undefined; } getValueOfType(flag, type) { if (this.isOmitted(flag)) { this.throwOmittedValueError(flag); } var value = this.getValue(flag); if (!TypeHelper.isType(value, type)) { this.throwIncorrectTypeError(value, type); } return value; } getFlagLabel(flag) { var alias = this.getAliasForFlag(flag); if (alias && alias.length === 1) { return this.getFlagLabel(alias); } var label = '-' + flag; if (alias) { label += ' (--' + alias + ')'; } return label; } getAliasForFlag(flag) { if (!this.aliases) { return null; } if (this.aliases[flag]) { return this.aliases[flag]; } if (this.reverse_aliases[flag]) { return this.reverse_aliases[flag]; } return null; } getNumber(flag) { return this.getValueOfType(flag, Enum_DataTypes.NUMBER); } getString(flag) { return this.getValueOfType(flag, Enum_DataTypes.STRING); } isOmitted(flag) { return this.getValue(flag) === undefined; } throwOmittedValueError(flag) { var flag_label = this.getFlagLabel(flag); Logger.errorAndExit(` Must specify a value for flag ${flag_label} `); } throwIncorrectTypeError(flag, type) { var flag_label = this.getFlagLabel(flag); Logger.errorAndExit(` Value for flag ${flag_label} must be of type ${type} `); } } ObjectHelper.extend(ArgHelper.prototype, { args: null, aliases: null }); module.exports = new ArgHelper();
var slice = require('../array/slice') // the base implementation of mout.js "timeout" without a given context // delay(displayToConsoleLog, 1000, 'hello', 'world') // function displayToConsoleLog(text1, text2) {console.log(text1, text2)} function delay (fn, wait, args) { args = slice(arguments, 2) return setTimeout(function () { fn.apply(undefined, args) }, wait) } module.exports = delay
"use strict"; var Download = require('download'), finalhandler = require('finalhandler'), http = require('http'), router = require('router')(), url = require('url'); router.post('/download', function (req, res) { var download, query = url.parse(req.url, true).query, validateQuery = function () { return query && query.get && query.get.match(/^http[s]?:\/\/.+$/) && query.dest && query.dest.match(/^.+$/); }; if (!validateQuery()) res.writeHead(400); else { download = new Download() .get(query.get) .dest(query.dest); if (query.rename && query.rename.match(/^.+$/)) download.rename(query.rename); download.run(function (err, files) { if (err) console.error(err); else console.log('Download successful.'); }); } res.end(); }); module.exports = { listen: function (port) { http.createServer(function (req, res) { router(req, res, finalhandler(req, res)) }).listen(port); } };
$( document ).ready(function() { $('.dropdown-toggle').dropdown(); });
"use strict"; import I from "immutable"; import assert from "assert"; import React from "react/addons"; let { TestUtils } = React.addons; import FilterInput from "../../../src/js/components/filter/FilterInput"; import MultiSelect from "../../../src/js/components/filter/MultiSelect"; import Preset from "../../../src/js/components/filter/Preset"; import Filter from "../../../src/js/components/filter/Filter"; describe("Filter", () => { const setFilter = () => {}; const setStartDate = () => {}; const setEndDate = () => {}; const restrictTo = () => {}; const onSelect = () => {}; const filters = I.fromJS({ filterBy: "hi", startDate: "2015-01-01", endDate: "2016-01-01", restrictions: { name: { key: "name", options: ["jim", "tim"] } } }); const selections = I.fromJS({ name: ["jim"] }); const presetConfig = [ {description: "preset", onSelect: []} ]; const ShallowRenderer = TestUtils.createRenderer(); ShallowRenderer.render( <Filter filters={filters} selections={selections} setFilter={setFilter} setStartDate={setStartDate} setEndDate={setEndDate} restrictTo={restrictTo} presetConfig={presetConfig} currentPage={1} totalPages={4} /> ); const renderedOutput = ShallowRenderer.getRenderOutput(); const youngers = renderedOutput.props.children.filter(el => el.type === "div"); const columns = youngers.filter(el => el.props.className.indexOf("table-manip-col") !== -1); it("#renders a preset row and 2 columns if passed no children", () => { assert.equal(columns.length, 2); }); it("#renders a FilterInput in the first row of the first column", () => { const row = columns[0].props.children.filter(el => el.props.className && el.props.className.indexOf("table-manip-row") !== -1 ).pop(); assert.equal(row.props.children.filter(el => el.type === FilterInput).length, 1); }); it("#renders a MultiSelect for each element in filters.restrictions", () => { const kids = columns[1].props.children; assert.equal( kids.filter(el => el.type === MultiSelect).length, filters.get("restrictions").size ); }); it("#renders a Preset component for each element in presetConfig, with description and onSelect props", () => { const kids = youngers.filter(el => el.props.className.indexOf("table-manip-presets") !== -1); const presets = kids[0].props.children.filter(el => el.type === Preset); assert.equal( presets.length, Object.keys(presetConfig).length ); assert.equal(presets[0].props.description, presetConfig[0].description); assert.deepEqual(presets[0].props.onSelect, presetConfig[0].onSelect); }); });
class Page_MannequinList_Collection_Personal extends Collection_Mannequins { } module.exports = Page_MannequinList_Collection_Personal;
var _slice = Array.prototype.slice module.exports = slice function slice (arr, start, end) { return _slice.call(arr, start, end) }
'use strict' const t = require('../') const oty = require('../lib/obj-to-yaml.js') t.match(oty({ todo: true }), '') t.match(oty({ foo: 1 }), ' ---\n foo: 1\n ...')
const defaultRendererState = { frame: 0, width: 800, height: 600, state: 'run', // 'pause', 'off' foreground: [255, 255, 255, 255], background: [0, 0, 0, 255], clearColour: [0, 0, 0, 0], invert: false }; const validStates = { run: true, pause: true, off: true }; const rendererState = (state = defaultRendererState, action) => { switch (action.type) { case '/renderer/STATE': // console.log('**** /renderer/STATE', action); return (action.payload in validStates) ? { ...state, state: action.payload } : state; case '/renderer/FRAME_BOUNDS': return { ...state, width: action.payload.width, height: action.payload.height }; case '/renderer/FRAME_ADVANCE': return { ...state, frame: state.frame + 1 }; case '/renderer/FOREGROUND': return { ...state, foreground: action.payload }; case '/renderer/BACKGROUND': return { ...state, background: action.payload }; case '/renderer/CLEAR_COLOUR': return { ...state, clearColour: action.payload }; case '/renderer/INVERT': return { ...state, invert: action.payload }; case '/renderer/REQUEST': return { ...state, [`req_${action.payload}`]: state.frame }; default: return state; } }; export default rendererState;
// ==UserScript== // @name news.ycombinator.com transform // @namespace https://github.com/yandavid/user.js // @version 1.1.0 // @description Transforms Hacker News. // @match https://news.ycombinator.com/* // @run-at document-start // ==/UserScript== const style = document.createElement('style'); const scale = devicePixelRatio * document.documentElement.offsetWidth / 1920; const rule = ` :root { transform-origin: top; transform: scale(${scale}); } `; document.head.appendChild(style); style.sheet.insertRule(rule, 0);
var gdal = require('gdal'); module.exports = kmlLayers; function kmlLayers(infile) { var ds_kml = {}; var lyr_cnt = 0; var msg = []; function layername_count(ds) { var lyr_name_cnt = {}; var dupes = {}; ds.layers.forEach(function(lyr) { var lyr_name = lyr.name; if (lyr_name in lyr_name_cnt) { lyr_name_cnt[lyr_name]++; dupes[lyr_name] = lyr_name_cnt[lyr_name]; } else { lyr_name_cnt[lyr_name] = 1; } }); return dupes; } try { ds_kml = gdal.open(infile); lyr_cnt = ds_kml.layers.count(); } catch (err) { return err.message; } if (lyr_cnt < 1) { ds_kml.close(); return 'KML does not contain any layers.'; } if (lyr_cnt > module.exports.max_layer_count) { ds_kml.close(); return lyr_cnt + ' layers found. Maximum of ' + module.exports.max_layer_count + ' layers allowed.'; } var duplicate_lyr_msg = layername_count(ds_kml); if (Object.keys(duplicate_lyr_msg).length > 0) { ds_kml.close(); for(var key in duplicate_lyr_msg) { msg += ' ' + key + ' (' + duplicate_lyr_msg[key] + ')'; } return 'Duplicate layer names:' + msg; } return true; } module.exports.max_layer_count = 15;
var nodemailer = require('nodemailer'); module.exports = function emailProvider(mailObject, callback) { //from email: var fromEmail = process.env.APP_EMAIL; // 'email-address' //emailserver token: var smtpToken = process.env.APP_EMAILPW; // 'smtpassword'; var transporter = nodemailer.createTransport({ service: 'Zoho', auth: { user: fromEmail, pass: smtpToken } }); mailObject.from = "'EncoreLink' <" + fromEmail + ">"; return transporter.sendMail(mailObject, callback); }
import m from 'mithril'; function controller(attrs) { let { sendMessage } = attrs; return { message: m.prop(''), send(e) { const { message } = this; e.preventDefault(); if(message()) { sendMessage(message()); message(''); } }, }; } function view(ctrl) { return ( ); } const Entry = { controller, view }; export default Entry;
'use strict' /* globals commands describe beforeEach it */ const cli = require('heroku-cli-util') const nock = require('nock') const cmd = commands.find((c) => c.topic === 'dashboard') const expect = require('unexpected') const time = require('../../src/time') describe('dashboard', () => { beforeEach(() => cli.mockConsole()) const yesterday = new Date(new Date().getTime() - (24 * 60 * 60 * 1000)) const now = new Date() const formation = [ { command: 'rails s -p $PORT', quantity: 1, size: 'Standard-1X', type: 'web' }, { command: 'npm start', quantity: 0, size: 'Standard-1X', type: 'node' } ] const router = { latency: { start_time: '2016-04-17T20:00:00Z', end_time: '2016-04-18T20:00:00Z', step: '1h0m0s', data: { 'latency.ms.p50': [ 46.924528301886795, 56.10526315789474, 41.19642857142857, 60.388888888888886, 54.94642857142857, 59.160714285714285, 45.24528301886792, 54.592592592592595, 43.51851851851852, 55, 44.160714285714285, 31.181818181818183, 36.089285714285715, 43.98275862068966, 49.74545454545454, 41.73684210526316, 46.70909090909091, 29.616666666666667, 40.610169491525426, 39.610169491525426, 47.35, 63.833333333333336, 51.1, 44.68333333333333, 32 ], 'latency.ms.p95': [ 148.58490566037736, 157.1578947368421, 139.75, 145.75925925925927, 209.30357142857142, 312.80357142857144, 119.56603773584905, 179.05555555555554, 171.62962962962962, 354.55357142857144, 181.17857142857142, 156.52727272727273, 172.89285714285714, 185.6206896551724, 141.96363636363637, 157.94736842105263, 177.0909090909091, 196.51666666666668, 227.25423728813558, 223.15254237288136, 329.8333333333333, 221.33333333333334, 189.7, 159.93333333333334, 238 ] } }, status: { start_time: '2016-04-17T20:00:00Z', end_time: '2016-04-18T20:00:00Z', step: '1h0m0s', data: { '200': [ null, null, null, null, null, null, null, 1, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null ], '201': [ 192, 197, 157, 143, 155, 178, 130, 178, 130, 146, 147, 522, 195, 198, 166, 187, 225, 330, 291, 328, 268, 283, 284, 285, 10 ] } }, errors: { start_time: '2016-04-17T19:00:00Z', end_time: '2016-04-18T19:00:00Z', step: '1h0m0s', data: { H12: [ null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 1, null, null, 1, null, null, null ], H25: [ null, null, null, null, 1, null, null, 1, null, null, null, null, 1, null, null, null, null, null, null, null, null, null, null, null, null ], H27: [ null, null, null, null, null, null, null, null, null, 1, 1, null, null, null, null, null, null, null, null, 4, null, null, null, 3, null ] } } } describe('with no favorites', () => { it('shows the dashboard', () => { let longboard = nock('https://longboard.heroku.com:443') .get('/favorites?type=app').reply(200, []) let heroku = nock('https://api.heroku.com:443') .get('/organizations').reply(200, []) let telex = nock('https://telex.heroku.com:443') .get('/user/notifications').reply(200, []) return cmd.run({}) .then(() => expect(cli.stdout, 'to be', `See all add-ons with heroku addons See all apps with heroku apps --all See other CLI commands with heroku help `)) .then(() => expect(cli.stderr, 'to be', 'Loading... done\n ▸ Add apps to this dashboard by favoriting them with heroku\n ▸ apps:favorites:add\n')) .then(() => longboard.done()) .then(() => telex.done()) .then(() => heroku.done()) }) }) describe('with no telex', () => { it('shows the dashboard', () => { let longboard = nock('https://longboard.heroku.com:443') .get('/favorites?type=app').reply(200, []) let heroku = nock('https://api.heroku.com:443') .get('/organizations').reply(200, []) let telex = nock('https://telex.heroku.com:443') .get('/user/notifications').reply(401, []) return cmd.run({}) .then(() => expect(cli.stdout, 'to be', `See all add-ons with heroku addons See all apps with heroku apps --all See other CLI commands with heroku help `)) .then(() => expect(cli.stderr, 'to be', 'Loading... done\n ▸ Add apps to this dashboard by favoriting them with heroku\n ▸ apps:favorites:add\n')) .then(() => longboard.done()) .then(() => telex.done()) .then(() => heroku.done()) }) }) describe('with a favorite app', () => { it('shows the dashboard', () => { let longboard = nock('https://longboard.heroku.com:443') .get('/favorites?type=app').reply(200, [{app_name: 'myapp'}]) let heroku = nock('https://api.heroku.com:443') .get('/organizations').reply(200, []) .get('/apps/myapp').reply(200, {name: 'myapp', owner: {email: 'foo@bar.com'}, released_at: now.toString()}) .get('/apps/myapp/formation').reply(200, formation) let telex = nock('https://telex.heroku.com:443') .get('/user/notifications').reply(200, []) let metrics = nock('https://api.metrics.herokai.com:443') .get(`/apps/myapp/router-metrics/status?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h&process_type=web`) .reply(200, router.status) .get(`/apps/myapp/router-metrics/latency?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h&process_type=web`) .reply(200, router.latency) .get(`/apps/myapp/router-metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h&process_type=web`) .reply(200, router.errors) .get(`/apps/myapp/formation/node/metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h`) .reply(200, {data: {}}) .get(`/apps/myapp/formation/web/metrics/errors?start_time=${yesterday.toISOString()}&end_time=${now.toISOString()}&step=1h`) .reply(200, {data: {}}) return cmd.run({}) .then(() => expect(cli.stdout, 'to be', `myapp Owner: foo@bar.com Dynos: 1 | Standard-1X Last release: ${time.ago(now)} Metrics: 46 ms 4 rpm ▂▁▁▆▂▅█▇ last 24 hours rpm Errors: 2 H12, 3 H25, 9 H27 (see details with heroku apps:errors) See all add-ons with heroku addons See all apps with heroku apps --all See other CLI commands with heroku help `)) .then(() => expect(cli.stderr, 'to be', 'Loading... done\n')) .then(() => metrics.done()) .then(() => longboard.done()) .then(() => telex.done()) .then(() => heroku.done()) }) }) })
import { describe, test } from 'mocha' import { cloneMock, assetWithFilesMock } from '../../../mocks/entities' import { wrapAsset } from '../../../../../lib/entities/asset' import { expect } from 'chai' import setupRestAdapter from '../helpers/setupRestAdapter' function setup(promise, params = {}) { return { ...setupRestAdapter(promise, params), entityMock: cloneMock('asset'), } } describe('Rest Asset', async () => { test('Asset processing for multiple locales succeeds', async () => { const responseMock = cloneMock('asset') responseMock.fields = { file: { 'en-US': { fileName: 'filename.jpg', url: 'http://server/filename.jpg', }, 'de-DE': { fileName: 'filename.jpg', url: 'http://server/filename.jpg', }, }, } const { httpMock, adapterMock, entityMock } = setup(Promise.resolve({ data: responseMock })) entityMock.fields = { file: { 'en-US': { fileName: 'filename.jpg', upload: 'http://server/filename.jpg', }, 'de-DE': { fileName: 'filename.jpg', upload: 'http://server/filename.jpg', }, }, } entityMock.sys.version = 2 const entity = wrapAsset((...args) => adapterMock.makeRequest(...args), entityMock) return entity.processForAllLocales().then(() => { expect(httpMock.put.args[0][0]).equals( '/spaces/space-id/environments/environment-id/assets/id/files/en-US/process', 'en-US locale is sent' ) expect(httpMock.put.args[1][0]).equals( '/spaces/space-id/environments/environment-id/assets/id/files/de-DE/process', 'de-DE locale is sent' ) expect(httpMock.put.args[0][2].headers['X-Contentful-Version']).equals( 2, 'version header is sent for first locale' ) expect(httpMock.put.args[1][2].headers['X-Contentful-Version']).equals( 2, 'version header is sent for second locale' ) expect(httpMock.get.args[0][0]).equals( '/spaces/space-id/environments/environment-id/assets/id', 'asset was checked after processing for first locale' ) expect(httpMock.get.args[1][0]).equals( '/spaces/space-id/environments/environment-id/assets/id', 'asset was checked after processing for second locale' ) }) }) test('Asset processing for one locale succeeds', async () => { const responseMock = cloneMock('asset') responseMock.fields = { file: { 'en-US': { fileName: 'filename.jpg', url: 'http://server/filename.jpg', }, }, } const { httpMock, entityMock, adapterMock } = setup(Promise.resolve({ data: responseMock })) entityMock.sys.version = 2 const entity = wrapAsset((...args) => adapterMock.makeRequest(...args), entityMock) return entity.processForLocale('en-US').then(() => { expect(httpMock.put.args[0][0]).equals( '/spaces/space-id/environments/environment-id/assets/id/files/en-US/process', 'correct locale is sent' ) expect(httpMock.put.args[0][2].headers['X-Contentful-Version']).equals( 2, 'version header is sent' ) expect(httpMock.get.args[0][0]).equals( '/spaces/space-id/environments/environment-id/assets/id', 'asset was checked after processing' ) }) }) /* - Test is failing - it also causes a memory leak in watch mode */ test.skip('Asset processing for one locale fails due to timeout', async () => { const responseMock = cloneMock('asset') responseMock.fields = { file: { 'en-US': { fileName: 'filename.jpg' } }, // url property never sent in response } const { httpMock, entityMock, adapterMock } = setup(Promise.resolve({ data: responseMock })) entityMock.sys.version = 2 const entity = wrapAsset((...args) => adapterMock.makeRequest(...args), entityMock) try { await entity.processForLocale('en-US') } catch (error) { expect(httpMock.get.callCount > 1, 'asset is checked multiple times').to.be.ok expect(error.name).equals('AssetProcessingTimeout', 'timeout is thrown') } }) test('Asset processing for multiple locales succeeds', async () => { const responseMock = cloneMock('asset') responseMock.fields = { file: { 'en-US': { fileName: 'filename.jpg', url: 'http://server/filename.jpg', }, 'de-DE': { fileName: 'filename.jpg', url: 'http://server/filename.jpg', }, }, } const { httpMock, entityMock, adapterMock } = setup(Promise.resolve({ data: responseMock })) entityMock.fields = { file: { 'en-US': { fileName: 'filename.jpg', upload: 'http://server/filename.jpg', }, 'de-DE': { fileName: 'filename.jpg', upload: 'http://server/filename.jpg', }, }, } entityMock.sys.version = 2 const entity = wrapAsset((...args) => adapterMock.makeRequest(...args), entityMock) return entity.processForAllLocales().then(() => { expect(httpMock.put.args[0][0]).equals( '/spaces/space-id/environments/environment-id/assets/id/files/en-US/process', 'en-US locale is sent' ) expect(httpMock.put.args[1][0]).equals( '/spaces/space-id/environments/environment-id/assets/id/files/de-DE/process', 'de-DE locale is sent' ) expect(httpMock.put.args[0][2].headers['X-Contentful-Version']).equals( 2, 'version header is sent for first locale' ) expect(httpMock.put.args[1][2].headers['X-Contentful-Version']).equals( 2, 'version header is sent for second locale' ) expect(httpMock.get.args[0][0]).equals( '/spaces/space-id/environments/environment-id/assets/id', 'asset was checked after processing for first locale' ) expect(httpMock.get.args[1][0]).equals( '/spaces/space-id/environments/environment-id/assets/id', 'asset was checked after processing for second locale' ) }) }) test('Asset processing for multiple locales fails due to timeout', async () => { const responseMock = cloneMock('asset') responseMock.fields = { file: { 'en-US': { fileName: 'filename.jpg' }, // url property never sent 'de-DE': { fileName: 'filename.jpg' }, // url property never sent }, } const { httpMock, adapterMock, entityMock } = setup(Promise.resolve({ data: responseMock })) entityMock.fields = { file: { 'en-US': { fileName: 'filename.jpg', upload: 'http://server/filename.jpg', }, 'de-DE': { fileName: 'filename.jpg', upload: 'http://server/filename.jpg', }, }, } entityMock.sys.version = 2 const entity = wrapAsset((...args) => adapterMock.makeRequest(...args), entityMock) return entity.processForAllLocales().catch((error) => { expect(httpMock.get.callCount > 1, 'asset is checked multiple times').to.be.ok expect(error.name).equals('AssetProcessingTimeout', 'timeout is thrown') }) }) test('Asset update with tags works', async () => { const { adapterMock, httpMock } = setup() const entityMock = cloneMock('assetWithTags') entityMock.sys.version = 2 const entity = wrapAsset((...args) => adapterMock.makeRequest(...args), entityMock) entity.metadata.tags[0] = { name: 'newname', sys: entityMock.metadata.tags[0].sys, } return entity.update().then((response) => { expect(response.toPlainObject, 'response is wrapped').to.be.ok expect(httpMock.put.args[0][1].metadata.tags[0].name).equals('newname', 'metadata is sent') expect(httpMock.put.args[0][2].headers['X-Contentful-Version']).equals( 2, 'version header is sent' ) return { httpMock, entityMock, response, } }) }) test('API call createAssetFromFiles', async () => { const { httpMock, adapterMock } = setup(Promise.resolve({})) httpMock.post.onFirstCall().returns( Promise.resolve({ data: { sys: { id: 'some_random_id', }, }, }) ) httpMock.post.onSecondCall().returns( Promise.resolve({ data: { sys: { id: 'some_random_id', }, }, }) ) httpMock.post.onThirdCall().returns( Promise.resolve({ data: assetWithFilesMock, }) ) return adapterMock .makeRequest({ entityType: 'Asset', action: 'createFromFiles', params: { spaceId: 'id' }, payload: { fields: { file: { locale: { contentType: 'image/svg+xml', fileName: 'filename.svg', file: '<svg xmlns="http://www.w3.org/2000/svg"><path fill="red" d="M50 50h150v50H50z"/></svg>', }, locale2: { contentType: 'image/svg+xml', fileName: 'filename.svg', file: '<svg xmlns="http://www.w3.org/2000/svg"><path fill="blue" d="M50 50h150v50H50z"/></svg>', }, }, }, }, }) .then(() => { expect(httpMock.post.args[0][1]).equals( '<svg xmlns="http://www.w3.org/2000/svg"><path fill="red" d="M50 50h150v50H50z"/></svg>', 'uploads file #1 to upload endpoint' ) expect(httpMock.post.args[1][1]).equals( '<svg xmlns="http://www.w3.org/2000/svg"><path fill="blue" d="M50 50h150v50H50z"/></svg>', 'uploads file #2 to upload endpoint' ) }) }) })
import * as types from '../constants/actionTypes'; export function saveSearchResults(settings) { return function (dispatch) { return dispatch({ type: types.SAVE_SEARCH_RESULTS, settings }); }; } export function saveArtistResults(settings) { return function (dispatch) { return dispatch({ type: types.SAVE_ARTIST_RESULTS, settings }); }; } export function saveTitleResults(settings) { return function (dispatch) { return dispatch({ type: types.SAVE_TITLE_RESULTS, settings }); }; } export function invalidateCache(settings) { return function (dispatch) { return dispatch({ type: types.INVALIDATE_CACHE, settings }); }; }
import { createSelector } from 'reselect'; import baseSelector from './baseSelector'; // eslint-disable-next-line import/prefer-default-export export const currentViewSelector = createSelector( baseSelector, base => base.view, );
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/app'; ReactDOM.render( <App /> , document.querySelector('.projects-container'));
export const chat = {"viewBox":"0 0 20 20","children":[{"name":"path","attribs":{"d":"M5.8,12.2V6H2C0.9,6,0,6.9,0,8v6c0,1.1,0.9,2,2,2h1v3l3-3h5c1.1,0,2-0.9,2-2v-1.82c-0.064,0.014-0.132,0.021-0.2,0.021h-7\r\n\tV12.2z M18,1H9C7.9,1,7,1.9,7,3v8h7l3,3v-3h1c1.1,0,2-0.899,2-2V3C20,1.9,19.1,1,18,1z"}}]};
var router = require('koa-router')(); var role_controller = require('../../app/controllers/role'); router.get('/list',role_controller.list); router.get('/delete/:id',role_controller.delete); router.post('/add',role_controller.add); router.get('/:id',role_controller.get); router.post('/edit',role_controller.edit); module.exports = router;
// Auto-generated. Do not edit! // (in-package crazyflie_driver.msg) "use strict"; let _serializer = require('../base_serialize.js'); let _deserializer = require('../base_deserialize.js'); let _finder = require('../find.js'); //----------------------------------------------------------- class LogBlock { constructor() { this.topic_name = ''; this.frequency = 0; this.variables = []; } static serialize(obj, bufferInfo) { // Serializes a message object of type LogBlock // Serialize message field [topic_name] bufferInfo = _serializer.string(obj.topic_name, bufferInfo); // Serialize message field [frequency] bufferInfo = _serializer.int16(obj.frequency, bufferInfo); // Serialize the length for message field [variables] bufferInfo = _serializer.uint32(obj.variables.length, bufferInfo); // Serialize message field [variables] obj.variables.forEach((val) => { bufferInfo = _serializer.string(val, bufferInfo); }); return bufferInfo; } static deserialize(buffer) { //deserializes a message object of type LogBlock let tmp; let len; let data = new LogBlock(); // Deserialize message field [topic_name] tmp = _deserializer.string(buffer); data.topic_name = tmp.data; buffer = tmp.buffer; // Deserialize message field [frequency] tmp = _deserializer.int16(buffer); data.frequency = tmp.data; buffer = tmp.buffer; // Deserialize array length for message field [variables] tmp = _deserializer.uint32(buffer); len = tmp.data; buffer = tmp.buffer; // Deserialize message field [variables] data.variables = new Array(len); for (let i = 0; i < len; ++i) { tmp = _deserializer.string(buffer); data.variables[i] = tmp.data; buffer = tmp.buffer; } return { data: data, buffer: buffer } } static datatype() { // Returns string type for a message object return 'crazyflie_driver/LogBlock'; } static md5sum() { //Returns md5sum for a message object return 'd9325f33ff3a1ffc6b6c0323a9f9b181'; } static messageDefinition() { // Returns full string definition for message return ` string topic_name int16 frequency string[] variables `; } }; module.exports = LogBlock;
import size from 'lodash/size'; import map from 'lodash/map'; import React from 'react'; import PropTypes from 'prop-types'; import validateURL from 'react-proptypes-url-validator'; import { Link } from 'react-router'; import FontAwesome from 'react-fontawesome'; import Button from 'react-bootstrap/lib/Button'; import Row from 'react-bootstrap/lib/Row'; import Col from 'react-bootstrap/lib/Col'; import { browserHistory } from 'react-router'; import CSSModules from 'react-css-modules'; import FromNow from '../utilities/from-now.js'; import SocialShare from '../article-box/social-share.js'; import entryPropType from '../article-box/entry-prop-type.js'; import ArticleBoxSm from '../article-box/article-box-sm.js'; import ArticleBoxMd from '../article-box/article-box-md.js'; import CategoryTag from '../category/tag.js'; import ProviderTag from '../rss-provider/tag.js'; import tr from '../localization/localization.js'; import { createLink } from '../utilities/text-utilities.js'; import styles from './article.less'; import mongooseIcon from '../../assets/img/logo-170-nologo.png'; @CSSModules(styles, { allowMultiple: true, }) export default class Article extends React.Component { static propTypes = { article: PropTypes.shape({ content: PropTypes.string, contentEl: PropTypes.any, contentLength: PropTypes.number, title: PropTypes.string, byline: PropTypes.string, error: PropTypes.shape({ code: PropTypes.number, msg: PropTypes.string }), link: validateURL, entryId: PropTypes.shape(entryPropType), createdAt: PropTypes.instanceOf(Date) }), isLoading: PropTypes.bool, relatedEntries: PropTypes.arrayOf( PropTypes.shape(entryPropType) ), nextRelatedEntry: PropTypes.shape(entryPropType) } articleContentEl = undefined setArticleContentEl = (el) => { if (!this.articleContentEl) { this.articleContentEl = el; const {contentEl} = this.props.article; this.createAdvertiseIfIsPossible(contentEl); el.appendChild(contentEl); } } createAdvertiseIfIsPossible = (content) => { const pEls = content.getElementsByTagName('p'); const totalP = pEls.length; if (totalP > 2 && !window.wgLazyAddBlockerDetected) { const targetEl = pEls[Math.round(totalP * 0.7)]; const pAdvEl = document.createElement('div'); pAdvEl.style.padding = '10px 0'; pAdvEl.innerHTML = this.getParagraphAdv(); targetEl.parentElement.insertBefore(pAdvEl, targetEl); //setTimeout(() => { (adsbygoogle = window.adsbygoogle || []).push({}); //}, 200); } } goBack = () => { const pathname = browserHistory.getCurrentLocation().pathname; setTimeout(() => { const nextPathname = browserHistory.getCurrentLocation().pathname; if (pathname === nextPathname) { browserHistory.replace('/'); } }, 0); browserHistory.goBack(); } getParagraphAdv = () => { return ( `<ins class="adsbygoogle" style="display:block; text-align:center;" data-ad-layout="in-article" data-ad-format="fluid" data-ad-client="ca-pub-3571483150053473" data-ad-slot="9172176420"> </ins>` ); } render() { const { isLoading } = this.props; if (isLoading) { return this.renderLoading(); } return ( <Row> <Col lg={10} lgOffset={1}> <article styleName="article" > { this.renderHeader() } { this.renderError() } { this.renderArticle() } { this.renderRelatedArticles() } { this.renderFooter() } </article> </Col> </Row> ); } renderHeader = () => { const { article } = this.props; const entry = article.entryId; const title = article.title || article.entryId.title; return ( <header styleName="header" > {this.renderHeaderToolbar()} <h1>{title}</h1> <div className="w-mt-14" > <CategoryTag name={entry.category} /> <ProviderTag name={entry.provider} className="w-ml-7" /> <FromNow className="text-muted pull-right" date={entry.published} /> </div> { size(article.byline) > 2 && <div className="w-mt-14 text-muted" > {tr.by} {article.byline} </div> } </header> ); } renderHeaderToolbar = () => { const { nextRelatedEntry, article } = this.props; return ( <div styleName="header-toolbar" > <div styleName="header-toolbar-actions" > {this.renderBackButton()} <SocialShare entryId={article.entryId._id} styleName="header-social-share social-share" link={location.href} overlayPlacement={"bottom"} /> </div> <div styleName="header-toolbar-related-entry" > <ArticleBoxSm entry={nextRelatedEntry} /> </div> </div> ); } renderBackButton = () => { return ( <Button bsStyle="link" className="blind-link" onClick={this.goBack}> <FontAwesome name="chevron-left" /> {tr.goBack} </Button> ); } renderArticle = () => { if (this.props.article && this.props.article.error) { return; } const { article } = this.props; return ( <div> <div className="article-body" > <div className="article-container font-size5 content-width4 line-height4"> <section className="article-reader-content" ref={ this.setArticleContentEl }> </section> </div> </div> <div className="text-center w-mb-7"> <a href={article.link} title={article.title} className="btn btn-default" role="button" aria-label={tr.articleReadFromWebsite} target="_blank" styleName="article-control-btn" > <FontAwesome name="external-link" /> {' '} {tr.articleReadFromWebsite} </a> </div> </div> ); } renderRelatedArticles = () => { const {relatedEntries} = this.props; return ( <Row styleName="related-articles" > {map(relatedEntries, entry => ( <Col sm={4} key={entry._id}> <ArticleBoxMd entry={entry}/> </Col> ))} </Row> ); } renderFooter = () => { const {article} = this.props; return ( <footer styleName="footer"> <div> <div className="pull-left" > {this.renderBackButton()} </div> <div className="text-right"> <SocialShare entryId={article.entryId._id} styleName="social-share" link={location.href} overlayPlacement={"top"} /> </div> </div> </footer> ); } renderLoading = () => { return ( <div className="text-center"> <img className="w-is-logo-loading" src={mongooseIcon} styleName="logo-loading" alt="Wiregoose" /> <h4 className="w-text-loading" data-text={tr.loadingArticle}> {tr.loadingArticle} </h4> </div> ); } renderError = () => { if (this.props.article && !this.props.article.error) { return; } const { article } = this.props; return ( <div className="text-center" styleName="error"> <h1> <FontAwesome name="newspaper-o" /> </h1> <p className="lead">{tr.articleRedirectTitle}</p> <a href={article.link} title={article.title} className="btn btn-default" role="button" aria-label={tr.articleReadFromWebsite} target="_blank" styleName="article-control-btn" > <FontAwesome name="external-link" /> {' '} {tr.articleReadFromWebsite} </a> </div> ); } }
'use strict'; define([ 'angular', 'angularRoute', 'angularUiBootstrap', 'angularResource', 'common/bootstrap', 'common/ga', 'angularLocalStorage', 'bootstrapDatepicker', 'angularNvd3' ], function(angular, angularRoute, angularUiBootstrap, angularResource, bootstrap, ga, bootstrapDatepicker, angularNvd3) { // Declare app level module which depends on views, and components var app = angular.module('myApp', [ 'ngRoute', 'ui.bootstrap', 'ngResource', 'angularCSS', 'LocalStorageModule', 'nvd3' ]). config([ '$routeProvider', '$locationProvider', '$httpProvider', '$controllerProvider', '$compileProvider', '$filterProvider', '$provide', '$injector', 'localStorageServiceProvider', '$resourceProvider', function ($routeProvider, $locationProvider, $httpProvider, $controllerProvider, $compileProvider, $filterProvider, $provide, $injector, localStorageServiceProvider, $resourceProvider) { app.controller = $controllerProvider.register; app.directive = $compileProvider.directive; app.filter = $filterProvider.register; app.factory = $provide.factory; app.service = $provide.service; //$httpProvider.interceptors.push('tmsInterceptor'); $routeProvider.otherwise({redirectTo: '/dashboard'}); $resourceProvider.defaults.stripTrailingSlashes = false; $httpProvider.interceptors.push(function($q) { return { 'responseError': function(rejection){ var defer = $q.defer(); if(rejection.status == 401){ console.dir(rejection); $routeProvider.otherwise({redirectTo: '/login'}); } defer.reject(rejection); return defer.promise; } }; }); // $locationProvider.hashPrefix('!'); //$locationProvider.html5Mode(true); // $locationProvider.html5Mode({ // enabled: true, // requireBase: false // }); //Lazy loading config var providers = { '$controllerProvider': $controllerProvider, '$compileProvider': $compileProvider, '$filterProvider': $filterProvider, '$provide': $provide, '$injector': $injector, }; angular.forEach(bootstrap, function (module) { angular.forEach(module._invokeQueue, function (invokeArgs) { var provider = providers[invokeArgs[0]]; provider[invokeArgs[1]].apply(provider, invokeArgs[2]); }); angular.forEach(module._configBlocks, function (invokeArgs) { var provider = providers[invokeArgs[0]]; provider[invokeArgs[1]].apply(provider, invokeArgs[2]); }); angular.forEach(module._runBlocks, function (invokeArgs) { var provider = providers[invokeArgs[0]]; provider[invokeArgs[1]].apply(provider, invokeArgs[2]); }); }); }]) .run(function ($rootScope, $templateCache, $http, $location, appConstants) { if (appConstants.isAuthenticated()) { $http.defaults.headers.common['X-Auth-Token'] = appConstants.getItem('token'); } $rootScope.$on('$viewContentLoaded', function() { $templateCache.removeAll(); }); ga.sendPageView('testUser', 'testPage'); // redirect to login page if not logged in and trying to access a restricted page $rootScope.$on('$locationChangeStart', function (event, next, current) { if (typeof(current) !== 'undefined'){ $templateCache.remove(current.templateUrl); } var publicPages = ['/login']; var restrictedPage = publicPages.indexOf($location.path()) === -1; if (restrictedPage && !appConstants.isAuthenticated()) { $location.path('/login'); } }); }); return app; });
$(document).ready(function() { $('#testClick').on('click', function(e) { e.preventDefault(); // avoiding normal redirect behaviour $("#messageContainer2").html("<div id='error'>bonjour</div>"); }); }); $(document).ready(function() { $('#pname').on('change keyup paste', function(e) { e.preventDefault(); // avoiding normal redirect behaviour var elem = $(this); // get current title value // TODO here: process value to replace spaces with "-" and delete special characters var url = elem.val().replace(/\ /g,'-'); //url.replace(' ', '-'); url = url.replace(/[^-a-zA-Z0-9]/g,''); $("#url").val(url.toLowerCase()); }); }); $(document).ready(function() { $('#pageForm').on('submit', function(e) { e.preventDefault(); // avoiding normal redirect behaviour var $this = $(this); // form jQuery object // Retrieve variables var pname = $('#pname').val(); var url = $('#url').val(); // menu options var content = $('#content').val(); // Check if variables are not empty before sending request if(pname === '' || url === '') { $("#messageContainer").html("<div id='error'>Empty mandatory fields detected.</div>"); } else { // send HTTP request asynchronously $.ajax({ url: $this.attr('action'), // type: $this.attr('method'), // data: $this.serialize(), // dataType: 'json', // JSON success: function(json) { // if(json.error === 0) { // no error $("#pageForm").html(""); // deactivate form $("#messageContainer").html("<div id='success'>" + json.message + "</div>"); // redirecting window.setTimeout(function() { window.location.href = '/adm/pages'; }, 1500); } else { $("#messageContainer").html("<div id='error'>" + json.message + "</div>"); } } }); } }); });
import merge from 'lodash/object/merge.js'; const ANNOTATION = { TYPEDEF : '@typedef', PARAM : '@param', TYPE : '@type', RETURN : '@return' }; const acceptedAnnotation = ['@typedef', '@param', '@type', '@return']; const STATE = { NONE : 0, READING_ANNOTATION : 1, READING_PARAM1 : 2, READING_PARAM2 : 3, END_READING : 4 }; export default class ClosureAnnotationTokenizer { constructor(){ this.importedTypes = {}; this.ANNOTATION = ANNOTATION; this.groupAnnotation = {}; } tokenize(js, previousToken) { this.groupAnnotation = {}; // '*\n * @param {string} a \n * @param {string} b \n * let lineToken = js.split('\n'); // Split each new line -> ['*',' * @param {string} a', ' * @param {string} b', '*'] lineToken = lineToken.map(this._stripComment); // Remove * from start of every line -> ['', '@param {string} a', '@param {string} b', ''] let flatLine = lineToken.join(' ').trim(); // Join back each new line, separate by whitespace -> '@param {string} a @param {string} b' let section = this._splitSection(flatLine); // Split each @ occurrence -> ['@param {string} a', '@param {string} b'] let tokens = []; //Parse each line to get it's {annotation, param1, param2} for (let i = 0; i < section.length; i++) { let token = this._partExtractor(section[i]); if(token){ tokens.push(token); } } // Remove/Replace character to ensure standardisation tokens = this._normalize(tokens); // Format result to desired format this._classifiedAnnotation(tokens); let result = {token : tokens, classifiedAnnotation: this.groupAnnotation}; // Combine with previous result if provided if(previousToken){ merge(previousToken, result); } return result; } _classifiedAnnotation(token){ for (let i = 0; i < token.length; i++) { let tokenObject = token[i]; if(!this.groupAnnotation.hasOwnProperty(tokenObject.annotation)){ this.groupAnnotation[tokenObject.annotation] = {}; } let id = 'param1', value = tokenObject.param1; if(tokenObject.annotation === '@param' ){ if(tokenObject.param2 === ''){ id = tokenObject.param1; value = 'any'; }else{ id = tokenObject.param2; } } this.groupAnnotation[tokenObject.annotation][id] = value; } } _stripComment(line) { let res = line.trim(); if (res.indexOf('*') === 0) { res = res.substr(1, res.length); } return res.trim(); } _splitSection(flatLine) { let indices = [], result = []; for (let i = 0; i < flatLine.length; i++) { if (flatLine[i] === '@') { indices.push(i); } } for (let i = 0; i < indices.length; i++) { let lastIndex = (i + 1 < indices.length) ? indices[i + 1] : flatLine.length; result[i] = flatLine.substring(indices[i], lastIndex).trim(); } return result; } _partExtractor(section) { let pos = 0; let curState = STATE.NONE; let part = {annotation: '', param1: '', param2: ''}; let bracketMemory = 0; while (pos < section.length && curState !== STATE.END_READING) { switch (section[pos]) { case '@' : part.annotation = section[pos]; curState = STATE.READING_ANNOTATION; break; case ' ' : if (curState === STATE.READING_ANNOTATION) { part.param1 = ''; curState = STATE.READING_PARAM1; } else if (curState === STATE.READING_PARAM1 && part.param1 !== '' && bracketMemory === 0) { part.param2 = ''; curState = STATE.READING_PARAM2; } else if (curState === STATE.READING_PARAM2 && part.param2 !== '' && bracketMemory === 0) { curState = STATE.END_READING; } break; default : if (section[pos] === '{' || section[pos] === '<' || section[pos] === '(') { bracketMemory++; } else if (section[pos] === '}' || section[pos] === '>' || section[pos] === ')') { bracketMemory--; } if (curState === STATE.READING_ANNOTATION) { part.annotation += section[pos]; } else if (curState === STATE.READING_PARAM1) { part.param1 += section[pos]; } else if (curState === STATE.READING_PARAM2) { part.param2 += section[pos]; } break; } pos++; } // Make sure only pass accepted annotation if(acceptedAnnotation.indexOf(part.annotation) === -1){ return null; }else{ return part; } } _normalize(tokens){ let _tokens = tokens; for(let i=0; i<_tokens.length; i++){ _tokens[i].param1 = this._normalizeStr(_tokens[i].param1); } return _tokens; } _normalizeStr(str){ let self = this; function _typeToken(type){ type = self._replaceWithAny(type); type = self._removeNameSpace(type); return type; } let result = str; result = self._removeUnusedChar(result); result = self._removeWrapBracket(result); result = self._replaceEqualToQuestionMark(result); result = self._removeGenericDot(result); result = self._replaceFunctionType(result); let regExp = new RegExp(/([^{}|\s:,<>()]*)/g); result = result.replace(regExp, _typeToken); result = self._handleMap(result); result = self._containNull(result); // TODO : improve contain null, considered hacky result = self._specialCaseHandler(result); // TODO : hacky return result; } _specialCaseHandler(result){ let regExpAny = new RegExp(/any\([a-z0-9]*\)/ig); // any(...) result = result.replace(regExpAny, (match, type) => '?' + type); let regExpTypedFunction = new RegExp(/(function)[\s]*:[\s]*[a-zA-Z0-9]*/ig); //function:boolean result = result.replace(regExpTypedFunction, (match, type) => type); let regExpAnyWraping = new RegExp(/any({[a-z:,<>()\s\|]*})/ig); //any{...} result = result.replace(regExpAnyWraping, (match, type) => '?' + type); let regExpBackQMark = new RegExp(/([a-z0-9]*)\?/ig); // ...? result = result.replace(regExpBackQMark, (match, type) => '?' + type); let regExpTypeGroup = new RegExp(/\([a-z,\s]*\)/ig); // (..., ..., ...) result = result.replace(regExpTypeGroup, () => 'any'); let regExpComplexObject = new RegExp(/Object<[a-z0-9{}\[\],<>:\s]*>/ig); // Object<string,Object<string,Object<string,Array<string>>>> result = result.replace(regExpComplexObject, () => 'Object'); if(result === ''){ result = 'any'; } return result; } _removeUnusedChar(str){ let result = str.replace(/\!/g,''); return result; } _handleMap(type){ let self = this; function replacerMap(match, open, key, separator, value, close){ open = '{ '; close = ' }'; key = self._containNull(key); value = self._containNull(value); key = '[key : ' + key + ']'; separator = ': '; return [open, key, separator, value, close].join(''); } let regExp = new RegExp(/[a-zA-Z0-9]*[\s]*(<)[\s]*([\|a-zA-Z0-9_\?]*)[\s]*(,)[\s]*([\|a-zA-Z0-9_\?]*)[\s]*(>)/g); return type.replace(regExp, replacerMap); } _replaceEqualToQuestionMark(type){ let result = type; if(type.indexOf('=') !== -1){ if(type !== '' && type.indexOf('?') === -1){ result = '?'+result; } return result.replace(/=/g,''); } return result; } _replaceFunctionType(type){ var keyword = 'function'; var functionPos = type.indexOf(keyword); var lastIndex = type.length; var resultType = type; while(functionPos !== -1){ var nextId = functionPos+keyword.length; var token = type.substring(functionPos, nextId); var bracketCount = 0; while(nextId < lastIndex){ var w = type[nextId]; token += w; if(w === '(' || w === '<' || w === '{'){ bracketCount++; }else if(w === ')' || w === '>' || w === '}'){ bracketCount--; } if((w === ',' || w === ' ' || w === ')' ) && bracketCount === 0 && token.trim() !== keyword){ break; } nextId++; } resultType = resultType.replace(token, 'Function'); functionPos = type.indexOf(keyword, nextId); } return resultType; } _removeGenericDot(type){ return type.replace(/\.</g, '<'); } _removeWrapBracket(type){ if(type[0] === '{' && type[type.length-1] === '}'){ return type.substring(1, type.length-1); } return type; } _replaceWithAny(type){ if(type === '?' || type === '*'){ return 'any'; }else if(type === '?*'){ return '?any'; } return type; } _removeNameSpace(type){ let hadQuestionMark = type.indexOf('?') !== -1; let cleanType = type.replace(/\?/g,''); let splitStr = cleanType.split('.'); let result = type; if(splitStr.length > 1){ this.importedTypes[cleanType] = 1; result = ((hadQuestionMark)?'?':'') + splitStr[splitStr.length-1]; } return result; } _containNull(str){ //TODO : Error if(str.indexOf('null') !== -1){ let regExp = new RegExp(/([^ \s:,{}<>()\[\]]*)/g); return str.replace(regExp, this._replaceNull); } return str; } _replaceNull(type){ let alt = type.split('|'); let result = []; let containNull = alt.indexOf('null') !== -1; result = alt.filter((s) => s !== 'null'); if(containNull){ result = result.map(function(s){ if(s.indexOf('?') === -1){ return '?'+s; } return s; }); } return result.join('|'); } }
export default text => { const count = text.replace(/[^\w\s]/g, '').split(/\s+/).reduce((map, word) => { map[word] = (map[word] || 0) + 1; return map; }, Object.create(null)); return Object.keys(count).reduce((res, key) => res.concat(`${key} (${count[key]})`), []); };
/*! fossil repository: http://www.ksana.tw/cgi-bin/ksanadb.cgi */ if(typeof String.prototype.trim !== 'function') { //IE sucks String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); } } requirejs.config( { paths: { jquery: './jquery', underscore: './underscore', backbone: './backbone', //backbone_epoxy: './backbone.epoxy', requirelib:'./require', text:'./requiretext', bootstrap:'./bootstrap', bootbox:'./bootbox', eventemitter:'./eventemitter2', socketio:'./socket.io', //aura aura:'./aura/aura', base:'./aura/base', platform:'./aura/platform', "aura.extensions":'./aura/aura.extensions', auraextensions:'./aura/aura.extensions', logger:'./aura/logger', components:'./aura/ext/components', mediator:'./aura/ext/mediator', debug:'./aura/ext/debug', // cjkutil:'./cjk/cjkutil', // strokecount:'./cjk/strokecount', // glyphemesearch:'./cjk/glyphemesearch', // radicalvariants:'./cjk/radicalvariants', // pinyin:'./cjk/pinyin', // rangy:'./rangy/rangy-core', aem:'./refinery/aem' // howler:'./howler', } }); requirejs(['jquery','underscore','backbone','requirelib','socketio','aem' ,'text','eventemitter','aura','debug','mediator','components' ],function() { window.jQuery=$; requirejs(['bootstrap','bootbox']); Backbone.$=$; // backbone.js is not working occasionally 2013/8/7 // this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); var href=window.location.href; var hash=href.lastIndexOf('#'); if (hash>0) href=href.substring(0,hash); var i=href.lastIndexOf('/'); requirejs.config({baseUrl: href.substring(0,i)}) var index=href.substr(i+1); index=index.replace('.html',''); index=index.replace('.htm',''); index=index.trim(); if (!index) index='index'; // when user didn't type index.html console.log('trying to load module:'+index); // requirejs([index],function(entry) { console.log('main module loaded',index); if (entry && entry.initialize) entry.initialize(); }); });
module.exports.register = function(Handlebars, options) { 'use strict'; Handlebars.registerHelper('author', function(author) { // var iniparser = require('iniparser'), var fs = require('fs'), gravatar = require('gravatar'), // homeDir = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE, // configFile = homeDir + '/.gitconfig', // gitconfig, user, gravatarOptions = options.site.gravatar, templateName = options.themeTemplates + '/partials/person.hbs', template; // if (fs.existsSync(configFile)) { // gitconfig = iniparser.parseSync(configFile); user = options.users[author]; user.gravatar = gravatar.url(user.email, gravatarOptions); // } template = Handlebars.compile(fs.readFileSync(templateName, 'utf8')); return new Handlebars.SafeString(template(user)); }); };
var d = new Date(); //timestamp var da = d.getDate(); //day var mon = d.getMonth() + 1; //month var yr = d.getFullYear(); //year var today = yr + onedigi(mon) + onedigi(da); function cursor_on() { time=setInterval(function(){ clearInterval(time); $('#icon').html('QnA:\\>_'); cursor_off(); //your code },900); } function cursor_off() { time=setInterval(function(){ clearInterval(time); $('#icon').html('QnA:\\><font color="black">_</font>'); cursor_on(); //your code },900); } function onedigi (num) { if (num < 10) { num = "0"+num; } return num; } function loadXMLDoc(dname) { if (window.XMLHttpRequest) { xhttp=new XMLHttpRequest(); } else { xhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",dname,false); xhttp.send(""); return xhttp.responseXML; } function list (target,xml_call,xsl_call) { var resultDocument; // code for IE if (window.ActiveXObject) { var xslt = new ActiveXObject("Msxml2.XSLTemplate.6.0"); var xsldoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument.6.0"); var xslproc; xsldoc.async = false; xsldoc.load(xsl_call); if (xsldoc.parseError.errorCode != 0) { var myErr = xsldoc.parseError; //WScript.Echo("You have error " + myErr.reason); } else { xslt.stylesheet = xsldoc; var xmldoc = new ActiveXObject("Msxml2.DOMDocument.6.0"); xmldoc.async = false; xmldoc.load(xml_call); if (xmldoc.parseError.errorCode != 0) { var myErr = xmldoc.parseError; //WScript.Echo("You have error " + myErr.reason); resultDocument = "You have error " + myErr.reason ; } else { xslproc = xslt.createProcessor(); xslproc.input = xmldoc; xslproc.addParameter("today", today); // add parameter xslproc.transform(); resultDocument = xslproc.output; } } } // code for Mozilla, Firefox, Opera, etc. else if (document.implementation && document.implementation.createDocument) { xml=loadXMLDoc(xml_call); xsl=loadXMLDoc(xsl_call); xsltProcessor=new XSLTProcessor(); // add parameter xsltProcessor.getParameter(null, "today"); xsltProcessor.setParameter(null, "today", today); xsltProcessor.importStylesheet(xsl); resultDocument = xsltProcessor.transformToFragment(xml,document); } //document.getElementById(target).innerHTML = resultDocument; $('#'+target).html(resultDocument) }
/* angular-file-upload v2.6.0 https://github.com/nervgh/angular-file-upload */ (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["angular-file-upload"] = factory(); else root["angular-file-upload"] = 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'; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); var _options = __webpack_require__(2); var _options2 = _interopRequireDefault(_options); var _FileUploader = __webpack_require__(3); var _FileUploader2 = _interopRequireDefault(_FileUploader); var _FileLikeObject = __webpack_require__(4); var _FileLikeObject2 = _interopRequireDefault(_FileLikeObject); var _FileItem = __webpack_require__(5); var _FileItem2 = _interopRequireDefault(_FileItem); var _FileDirective = __webpack_require__(6); var _FileDirective2 = _interopRequireDefault(_FileDirective); var _FileSelect = __webpack_require__(7); var _FileSelect2 = _interopRequireDefault(_FileSelect); var _Pipeline = __webpack_require__(8); var _Pipeline2 = _interopRequireDefault(_Pipeline); var _FileDrop = __webpack_require__(9); var _FileDrop2 = _interopRequireDefault(_FileDrop); var _FileOver = __webpack_require__(10); var _FileOver2 = _interopRequireDefault(_FileOver); var _FileSelect3 = __webpack_require__(11); var _FileSelect4 = _interopRequireDefault(_FileSelect3); var _FileDrop3 = __webpack_require__(12); var _FileDrop4 = _interopRequireDefault(_FileDrop3); var _FileOver3 = __webpack_require__(13); var _FileOver4 = _interopRequireDefault(_FileOver3); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } angular.module(_config2.default.name, []).value('fileUploaderOptions', _options2.default).factory('FileUploader', _FileUploader2.default).factory('FileLikeObject', _FileLikeObject2.default).factory('FileItem', _FileItem2.default).factory('FileDirective', _FileDirective2.default).factory('FileSelect', _FileSelect2.default).factory('FileDrop', _FileDrop2.default).factory('FileOver', _FileOver2.default).factory('Pipeline', _Pipeline2.default).directive('nvFileSelect', _FileSelect4.default).directive('nvFileDrop', _FileDrop4.default).directive('nvFileOver', _FileOver4.default).run(['FileUploader', 'FileLikeObject', 'FileItem', 'FileDirective', 'FileSelect', 'FileDrop', 'FileOver', 'Pipeline', function (FileUploader, FileLikeObject, FileItem, FileDirective, FileSelect, FileDrop, FileOver, Pipeline) { // only for compatibility FileUploader.FileLikeObject = FileLikeObject; FileUploader.FileItem = FileItem; FileUploader.FileDirective = FileDirective; FileUploader.FileSelect = FileSelect; FileUploader.FileDrop = FileDrop; FileUploader.FileOver = FileOver; FileUploader.Pipeline = Pipeline; }]); /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = {"name":"angularFileUpload"} /***/ }), /* 2 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { url: '/', alias: 'file', headers: {}, queue: [], progress: 0, autoUpload: false, removeAfterUpload: false, method: 'POST', filters: [], formData: [], queueLimit: Number.MAX_VALUE, withCredentials: false, disableMultipart: false }; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _angular = angular, bind = _angular.bind, copy = _angular.copy, extend = _angular.extend, forEach = _angular.forEach, isObject = _angular.isObject, isNumber = _angular.isNumber, isDefined = _angular.isDefined, isArray = _angular.isArray, isUndefined = _angular.isUndefined, element = _angular.element; function __identity(fileUploaderOptions, $rootScope, $http, $window, $timeout, FileLikeObject, FileItem, Pipeline) { var File = $window.File, FormData = $window.FormData; var FileUploader = function () { /********************** * PUBLIC **********************/ /** * Creates an instance of FileUploader * @param {Object} [options] * @constructor */ function FileUploader(options) { _classCallCheck(this, FileUploader); var settings = copy(fileUploaderOptions); extend(this, settings, options, { isUploading: false, _nextIndex: 0, _directives: { select: [], drop: [], over: [] } }); // add default filters this.filters.unshift({ name: 'queueLimit', fn: this._queueLimitFilter }); this.filters.unshift({ name: 'folder', fn: this._folderFilter }); } /** * Adds items to the queue * @param {File|HTMLInputElement|Object|FileList|Array<Object>} files * @param {Object} [options] * @param {Array<Function>|String} filters */ FileUploader.prototype.addToQueue = function addToQueue(files, options, filters) { var _this = this; var incomingQueue = this.isArrayLikeObject(files) ? Array.prototype.slice.call(files) : [files]; var arrayOfFilters = this._getFilters(filters); var count = this.queue.length; var addedFileItems = []; var next = function next() { var something = incomingQueue.shift(); if (isUndefined(something)) { return done(); } var fileLikeObject = _this.isFile(something) ? something : new FileLikeObject(something); var pipes = _this._convertFiltersToPipes(arrayOfFilters); var pipeline = new Pipeline(pipes); var onThrown = function onThrown(err) { var originalFilter = err.pipe.originalFilter; var _err$args = _slicedToArray(err.args, 2), fileLikeObject = _err$args[0], options = _err$args[1]; _this._onWhenAddingFileFailed(fileLikeObject, originalFilter, options); next(); }; var onSuccessful = function onSuccessful(fileLikeObject, options) { var fileItem = new FileItem(_this, fileLikeObject, options); addedFileItems.push(fileItem); _this.queue.push(fileItem); _this._onAfterAddingFile(fileItem); next(); }; pipeline.onThrown = onThrown; pipeline.onSuccessful = onSuccessful; pipeline.exec(fileLikeObject, options); }; var done = function done() { if (_this.queue.length !== count) { _this._onAfterAddingAll(addedFileItems); _this.progress = _this._getTotalProgress(); } _this._render(); if (_this.autoUpload) _this.uploadAll(); }; next(); }; /** * Remove items from the queue. Remove last: index = -1 * @param {FileItem|Number} value */ FileUploader.prototype.removeFromQueue = function removeFromQueue(value) { var index = this.getIndexOfItem(value); var item = this.queue[index]; if (item.isUploading) item.cancel(); this.queue.splice(index, 1); item._destroy(); this.progress = this._getTotalProgress(); }; /** * Clears the queue */ FileUploader.prototype.clearQueue = function clearQueue() { while (this.queue.length) { this.queue[0].remove(); } this.progress = 0; }; /** * Uploads a item from the queue * @param {FileItem|Number} value */ FileUploader.prototype.uploadItem = function uploadItem(value) { var index = this.getIndexOfItem(value); var item = this.queue[index]; var transport = this.isHTML5 ? '_xhrTransport' : '_iframeTransport'; item._prepareToUploading(); if (this.isUploading) return; this._onBeforeUploadItem(item); if (item.isCancel) return; item.isUploading = true; this.isUploading = true; this[transport](item); this._render(); }; /** * Cancels uploading of item from the queue * @param {FileItem|Number} value */ FileUploader.prototype.cancelItem = function cancelItem(value) { var _this2 = this; var index = this.getIndexOfItem(value); var item = this.queue[index]; var prop = this.isHTML5 ? '_xhr' : '_form'; if (!item) return; item.isCancel = true; if (item.isUploading) { // It will call this._onCancelItem() & this._onCompleteItem() asynchronously item[prop].abort(); } else { var dummy = [undefined, 0, {}]; var onNextTick = function onNextTick() { _this2._onCancelItem.apply(_this2, [item].concat(dummy)); _this2._onCompleteItem.apply(_this2, [item].concat(dummy)); }; $timeout(onNextTick); // Trigger callbacks asynchronously (setImmediate emulation) } }; /** * Uploads all not uploaded items of queue */ FileUploader.prototype.uploadAll = function uploadAll() { var items = this.getNotUploadedItems().filter(function (item) { return !item.isUploading; }); if (!items.length) return; forEach(items, function (item) { return item._prepareToUploading(); }); items[0].upload(); }; /** * Cancels all uploads */ FileUploader.prototype.cancelAll = function cancelAll() { var items = this.getNotUploadedItems(); forEach(items, function (item) { return item.cancel(); }); }; /** * Returns "true" if value an instance of File * @param {*} value * @returns {Boolean} * @private */ FileUploader.prototype.isFile = function isFile(value) { return this.constructor.isFile(value); }; /** * Returns "true" if value an instance of FileLikeObject * @param {*} value * @returns {Boolean} * @private */ FileUploader.prototype.isFileLikeObject = function isFileLikeObject(value) { return this.constructor.isFileLikeObject(value); }; /** * Returns "true" if value is array like object * @param {*} value * @returns {Boolean} */ FileUploader.prototype.isArrayLikeObject = function isArrayLikeObject(value) { return this.constructor.isArrayLikeObject(value); }; /** * Returns a index of item from the queue * @param {Item|Number} value * @returns {Number} */ FileUploader.prototype.getIndexOfItem = function getIndexOfItem(value) { return isNumber(value) ? value : this.queue.indexOf(value); }; /** * Returns not uploaded items * @returns {Array} */ FileUploader.prototype.getNotUploadedItems = function getNotUploadedItems() { return this.queue.filter(function (item) { return !item.isUploaded; }); }; /** * Returns items ready for upload * @returns {Array} */ FileUploader.prototype.getReadyItems = function getReadyItems() { return this.queue.filter(function (item) { return item.isReady && !item.isUploading; }).sort(function (item1, item2) { return item1.index - item2.index; }); }; /** * Destroys instance of FileUploader */ FileUploader.prototype.destroy = function destroy() { var _this3 = this; forEach(this._directives, function (key) { forEach(_this3._directives[key], function (object) { object.destroy(); }); }); }; /** * Callback * @param {Array} fileItems */ FileUploader.prototype.onAfterAddingAll = function onAfterAddingAll(fileItems) {}; /** * Callback * @param {FileItem} fileItem */ FileUploader.prototype.onAfterAddingFile = function onAfterAddingFile(fileItem) {}; /** * Callback * @param {File|Object} item * @param {Object} filter * @param {Object} options */ FileUploader.prototype.onWhenAddingFileFailed = function onWhenAddingFileFailed(item, filter, options) {}; /** * Callback * @param {FileItem} fileItem */ FileUploader.prototype.onBeforeUploadItem = function onBeforeUploadItem(fileItem) {}; /** * Callback * @param {FileItem} fileItem * @param {Number} progress */ FileUploader.prototype.onProgressItem = function onProgressItem(fileItem, progress) {}; /** * Callback * @param {Number} progress */ FileUploader.prototype.onProgressAll = function onProgressAll(progress) {}; /** * Callback * @param {FileItem} item * @param {*} response * @param {Number} status * @param {Object} headers */ FileUploader.prototype.onSuccessItem = function onSuccessItem(item, response, status, headers) {}; /** * Callback * @param {FileItem} item * @param {*} response * @param {Number} status * @param {Object} headers */ FileUploader.prototype.onErrorItem = function onErrorItem(item, response, status, headers) {}; /** * Callback * @param {FileItem} item * @param {*} response * @param {Number} status * @param {Object} headers */ FileUploader.prototype.onCancelItem = function onCancelItem(item, response, status, headers) {}; /** * Callback * @param {FileItem} item * @param {*} response * @param {Number} status * @param {Object} headers */ FileUploader.prototype.onCompleteItem = function onCompleteItem(item, response, status, headers) {}; /** * Callback * @param {FileItem} item */ FileUploader.prototype.onTimeoutItem = function onTimeoutItem(item) {}; /** * Callback */ FileUploader.prototype.onCompleteAll = function onCompleteAll() {}; /********************** * PRIVATE **********************/ /** * Returns the total progress * @param {Number} [value] * @returns {Number} * @private */ FileUploader.prototype._getTotalProgress = function _getTotalProgress(value) { if (this.removeAfterUpload) return value || 0; var notUploaded = this.getNotUploadedItems().length; var uploaded = notUploaded ? this.queue.length - notUploaded : this.queue.length; var ratio = 100 / this.queue.length; var current = (value || 0) * ratio / 100; return Math.round(uploaded * ratio + current); }; /** * Returns array of filters * @param {Array<Function>|String} filters * @returns {Array<Function>} * @private */ FileUploader.prototype._getFilters = function _getFilters(filters) { if (!filters) return this.filters; if (isArray(filters)) return filters; var names = filters.match(/[^\s,]+/g); return this.filters.filter(function (filter) { return names.indexOf(filter.name) !== -1; }); }; /** * @param {Array<Function>} filters * @returns {Array<Function>} * @private */ FileUploader.prototype._convertFiltersToPipes = function _convertFiltersToPipes(filters) { var _this4 = this; return filters.map(function (filter) { var fn = bind(_this4, filter.fn); fn.isAsync = filter.fn.length === 3; fn.originalFilter = filter; return fn; }); }; /** * Updates html * @private */ FileUploader.prototype._render = function _render() { if (!$rootScope.$$phase) $rootScope.$apply(); }; /** * Returns "true" if item is a file (not folder) * @param {File|FileLikeObject} item * @returns {Boolean} * @private */ FileUploader.prototype._folderFilter = function _folderFilter(item) { return !!(item.size || item.type); }; /** * Returns "true" if the limit has not been reached * @returns {Boolean} * @private */ FileUploader.prototype._queueLimitFilter = function _queueLimitFilter() { return this.queue.length < this.queueLimit; }; /** * Checks whether upload successful * @param {Number} status * @returns {Boolean} * @private */ FileUploader.prototype._isSuccessCode = function _isSuccessCode(status) { return status >= 200 && status < 300 || status === 304; }; /** * Transforms the server response * @param {*} response * @param {Object} headers * @returns {*} * @private */ FileUploader.prototype._transformResponse = function _transformResponse(response, headers) { var headersGetter = this._headersGetter(headers); forEach($http.defaults.transformResponse, function (transformFn) { response = transformFn(response, headersGetter); }); return response; }; /** * Parsed response headers * @param headers * @returns {Object} * @see https://github.com/angular/angular.js/blob/master/src/ng/http.js * @private */ FileUploader.prototype._parseHeaders = function _parseHeaders(headers) { var parsed = {}, key, val, i; if (!headers) return parsed; forEach(headers.split('\n'), function (line) { i = line.indexOf(':'); key = line.slice(0, i).trim().toLowerCase(); val = line.slice(i + 1).trim(); if (key) { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } }); return parsed; }; /** * Returns function that returns headers * @param {Object} parsedHeaders * @returns {Function} * @private */ FileUploader.prototype._headersGetter = function _headersGetter(parsedHeaders) { return function (name) { if (name) { return parsedHeaders[name.toLowerCase()] || null; } return parsedHeaders; }; }; /** * The XMLHttpRequest transport * @param {FileItem} item * @private */ FileUploader.prototype._xhrTransport = function _xhrTransport(item) { var _this5 = this; var xhr = item._xhr = new XMLHttpRequest(); var sendable; if (!item.disableMultipart) { sendable = new FormData(); forEach(item.formData, function (obj) { forEach(obj, function (value, key) { sendable.append(key, value); }); }); sendable.append(item.alias, item._file, item.file.name); } else { sendable = item._file; } if (typeof item._file.size != 'number') { throw new TypeError('The file specified is no longer valid'); } xhr.upload.onprogress = function (event) { var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0); _this5._onProgressItem(item, progress); }; xhr.onload = function () { var headers = _this5._parseHeaders(xhr.getAllResponseHeaders()); var response = _this5._transformResponse(xhr.response, headers); var gist = _this5._isSuccessCode(xhr.status) ? 'Success' : 'Error'; var method = '_on' + gist + 'Item'; _this5[method](item, response, xhr.status, headers); _this5._onCompleteItem(item, response, xhr.status, headers); }; xhr.onerror = function () { var headers = _this5._parseHeaders(xhr.getAllResponseHeaders()); var response = _this5._transformResponse(xhr.response, headers); _this5._onErrorItem(item, response, xhr.status, headers); _this5._onCompleteItem(item, response, xhr.status, headers); }; xhr.onabort = function () { var headers = _this5._parseHeaders(xhr.getAllResponseHeaders()); var response = _this5._transformResponse(xhr.response, headers); _this5._onCancelItem(item, response, xhr.status, headers); _this5._onCompleteItem(item, response, xhr.status, headers); }; xhr.timeout = item.timeout || 0; xhr.ontimeout = function (e) { var headers = _this5._parseHeaders(xhr.getAllResponseHeaders()); var response = "Request Timeout."; _this5._onTimeoutItem(item); _this5._onCompleteItem(item, response, 408, headers); }; xhr.open(item.method, item.url, true); xhr.withCredentials = item.withCredentials; forEach(item.headers, function (value, name) { xhr.setRequestHeader(name, value); }); xhr.send(sendable); }; /** * The IFrame transport * @param {FileItem} item * @private */ FileUploader.prototype._iframeTransport = function _iframeTransport(item) { var _this6 = this; var form = element('<form style="display: none;" />'); var iframe = element('<iframe name="iframeTransport' + Date.now() + '">'); var input = item._input; var timeout = 0; var timer = null; var isTimedOut = false; if (item._form) item._form.replaceWith(input); // remove old form item._form = form; // save link to new form input.prop('name', item.alias); forEach(item.formData, function (obj) { forEach(obj, function (value, key) { var element_ = element('<input type="hidden" name="' + key + '" />'); element_.val(value); form.append(element_); }); }); form.prop({ action: item.url, method: 'POST', target: iframe.prop('name'), enctype: 'multipart/form-data', encoding: 'multipart/form-data' // old IE }); iframe.bind('load', function () { var html = ''; var status = 200; try { // Fix for legacy IE browsers that loads internal error page // when failed WS response received. In consequence iframe // content access denied error is thrown becouse trying to // access cross domain page. When such thing occurs notifying // with empty response object. See more info at: // http://stackoverflow.com/questions/151362/access-is-denied-error-on-accessing-iframe-document-object // Note that if non standard 4xx or 5xx error code returned // from WS then response content can be accessed without error // but 'XHR' status becomes 200. In order to avoid confusion // returning response via same 'success' event handler. // fixed angular.contents() for iframes html = iframe[0].contentDocument.body.innerHTML; } catch (e) { // in case we run into the access-is-denied error or we have another error on the server side // (intentional 500,40... errors), we at least say 'something went wrong' -> 500 status = 500; } if (timer) { clearTimeout(timer); } timer = null; if (isTimedOut) { return false; //throw 'Request Timeout' } var xhr = { response: html, status: status, dummy: true }; var headers = {}; var response = _this6._transformResponse(xhr.response, headers); _this6._onSuccessItem(item, response, xhr.status, headers); _this6._onCompleteItem(item, response, xhr.status, headers); }); form.abort = function () { var xhr = { status: 0, dummy: true }; var headers = {}; var response; iframe.unbind('load').prop('src', 'javascript:false;'); form.replaceWith(input); _this6._onCancelItem(item, response, xhr.status, headers); _this6._onCompleteItem(item, response, xhr.status, headers); }; input.after(form); form.append(input).append(iframe); timeout = item.timeout || 0; timer = null; if (timeout) { timer = setTimeout(function () { isTimedOut = true; item.isCancel = true; if (item.isUploading) { iframe.unbind('load').prop('src', 'javascript:false;'); form.replaceWith(input); } var headers = {}; var response = "Request Timeout."; _this6._onTimeoutItem(item); _this6._onCompleteItem(item, response, 408, headers); }, timeout); } form[0].submit(); }; /** * Inner callback * @param {File|Object} item * @param {Object} filter * @param {Object} options * @private */ FileUploader.prototype._onWhenAddingFileFailed = function _onWhenAddingFileFailed(item, filter, options) { this.onWhenAddingFileFailed(item, filter, options); }; /** * Inner callback * @param {FileItem} item */ FileUploader.prototype._onAfterAddingFile = function _onAfterAddingFile(item) { this.onAfterAddingFile(item); }; /** * Inner callback * @param {Array<FileItem>} items */ FileUploader.prototype._onAfterAddingAll = function _onAfterAddingAll(items) { this.onAfterAddingAll(items); }; /** * Inner callback * @param {FileItem} item * @private */ FileUploader.prototype._onBeforeUploadItem = function _onBeforeUploadItem(item) { item._onBeforeUpload(); this.onBeforeUploadItem(item); }; /** * Inner callback * @param {FileItem} item * @param {Number} progress * @private */ FileUploader.prototype._onProgressItem = function _onProgressItem(item, progress) { var total = this._getTotalProgress(progress); this.progress = total; item._onProgress(progress); this.onProgressItem(item, progress); this.onProgressAll(total); this._render(); }; /** * Inner callback * @param {FileItem} item * @param {*} response * @param {Number} status * @param {Object} headers * @private */ FileUploader.prototype._onSuccessItem = function _onSuccessItem(item, response, status, headers) { item._onSuccess(response, status, headers); this.onSuccessItem(item, response, status, headers); }; /** * Inner callback * @param {FileItem} item * @param {*} response * @param {Number} status * @param {Object} headers * @private */ FileUploader.prototype._onErrorItem = function _onErrorItem(item, response, status, headers) { item._onError(response, status, headers); this.onErrorItem(item, response, status, headers); }; /** * Inner callback * @param {FileItem} item * @param {*} response * @param {Number} status * @param {Object} headers * @private */ FileUploader.prototype._onCancelItem = function _onCancelItem(item, response, status, headers) { item._onCancel(response, status, headers); this.onCancelItem(item, response, status, headers); }; /** * Inner callback * @param {FileItem} item * @param {*} response * @param {Number} status * @param {Object} headers * @private */ FileUploader.prototype._onCompleteItem = function _onCompleteItem(item, response, status, headers) { item._onComplete(response, status, headers); this.onCompleteItem(item, response, status, headers); var nextItem = this.getReadyItems()[0]; this.isUploading = false; if (isDefined(nextItem)) { nextItem.upload(); return; } this.onCompleteAll(); this.progress = this._getTotalProgress(); this._render(); }; /** * Inner callback * @param {FileItem} item * @private */ FileUploader.prototype._onTimeoutItem = function _onTimeoutItem(item) { item._onTimeout(); this.onTimeoutItem(item); }; /********************** * STATIC **********************/ /** * Returns "true" if value an instance of File * @param {*} value * @returns {Boolean} * @private */ FileUploader.isFile = function isFile(value) { return File && value instanceof File; }; /** * Returns "true" if value an instance of FileLikeObject * @param {*} value * @returns {Boolean} * @private */ FileUploader.isFileLikeObject = function isFileLikeObject(value) { return value instanceof FileLikeObject; }; /** * Returns "true" if value is array like object * @param {*} value * @returns {Boolean} */ FileUploader.isArrayLikeObject = function isArrayLikeObject(value) { return isObject(value) && 'length' in value; }; /** * Inherits a target (Class_1) by a source (Class_2) * @param {Function} target * @param {Function} source */ FileUploader.inherit = function inherit(target, source) { target.prototype = Object.create(source.prototype); target.prototype.constructor = target; target.super_ = source; }; return FileUploader; }(); /********************** * PUBLIC **********************/ /** * Checks a support the html5 uploader * @returns {Boolean} * @readonly */ FileUploader.prototype.isHTML5 = !!(File && FormData); /********************** * STATIC **********************/ /** * @borrows FileUploader.prototype.isHTML5 */ FileUploader.isHTML5 = FileUploader.prototype.isHTML5; return FileUploader; } __identity.$inject = ['fileUploaderOptions', '$rootScope', '$http', '$window', '$timeout', 'FileLikeObject', 'FileItem', 'Pipeline']; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _angular = angular, copy = _angular.copy, isElement = _angular.isElement, isString = _angular.isString; function __identity() { return function () { /** * Creates an instance of FileLikeObject * @param {File|HTMLInputElement|Object} fileOrInput * @constructor */ function FileLikeObject(fileOrInput) { _classCallCheck(this, FileLikeObject); var isInput = isElement(fileOrInput); var fakePathOrObject = isInput ? fileOrInput.value : fileOrInput; var postfix = isString(fakePathOrObject) ? 'FakePath' : 'Object'; var method = '_createFrom' + postfix; this[method](fakePathOrObject, fileOrInput); } /** * Creates file like object from fake path string * @param {String} path * @private */ FileLikeObject.prototype._createFromFakePath = function _createFromFakePath(path, input) { this.lastModifiedDate = null; this.size = null; this.type = 'like/' + path.slice(path.lastIndexOf('.') + 1).toLowerCase(); this.name = path.slice(path.lastIndexOf('/') + path.lastIndexOf('\\') + 2); this.input = input; }; /** * Creates file like object from object * @param {File|FileLikeObject} object * @private */ FileLikeObject.prototype._createFromObject = function _createFromObject(object) { this.lastModifiedDate = copy(object.lastModifiedDate); this.size = object.size; this.type = object.type; this.name = object.name; this.input = object.input; }; return FileLikeObject; }(); } /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _angular = angular, copy = _angular.copy, extend = _angular.extend, element = _angular.element, isElement = _angular.isElement; function __identity($compile, FileLikeObject) { return function () { /** * Creates an instance of FileItem * @param {FileUploader} uploader * @param {File|HTMLInputElement|Object} some * @param {Object} options * @constructor */ function FileItem(uploader, some, options) { _classCallCheck(this, FileItem); var isInput = !!some.input; var input = isInput ? element(some.input) : null; var file = !isInput ? some : null; extend(this, { url: uploader.url, alias: uploader.alias, headers: copy(uploader.headers), formData: copy(uploader.formData), removeAfterUpload: uploader.removeAfterUpload, withCredentials: uploader.withCredentials, disableMultipart: uploader.disableMultipart, method: uploader.method, timeout: uploader.timeout }, options, { uploader: uploader, file: new FileLikeObject(some), isReady: false, isUploading: false, isUploaded: false, isSuccess: false, isCancel: false, isError: false, progress: 0, index: null, _file: file, _input: input }); if (input) this._replaceNode(input); } /********************** * PUBLIC **********************/ /** * Uploads a FileItem */ FileItem.prototype.upload = function upload() { try { this.uploader.uploadItem(this); } catch (e) { var message = e.name + ':' + e.message; this.uploader._onCompleteItem(this, message, e.code, []); this.uploader._onErrorItem(this, message, e.code, []); } }; /** * Cancels uploading of FileItem */ FileItem.prototype.cancel = function cancel() { this.uploader.cancelItem(this); }; /** * Removes a FileItem */ FileItem.prototype.remove = function remove() { this.uploader.removeFromQueue(this); }; /** * Callback * @private */ FileItem.prototype.onBeforeUpload = function onBeforeUpload() {}; /** * Callback * @param {Number} progress * @private */ FileItem.prototype.onProgress = function onProgress(progress) {}; /** * Callback * @param {*} response * @param {Number} status * @param {Object} headers */ FileItem.prototype.onSuccess = function onSuccess(response, status, headers) {}; /** * Callback * @param {*} response * @param {Number} status * @param {Object} headers */ FileItem.prototype.onError = function onError(response, status, headers) {}; /** * Callback * @param {*} response * @param {Number} status * @param {Object} headers */ FileItem.prototype.onCancel = function onCancel(response, status, headers) {}; /** * Callback * @param {*} response * @param {Number} status * @param {Object} headers */ FileItem.prototype.onComplete = function onComplete(response, status, headers) {}; /** * Callback */ FileItem.prototype.onTimeout = function onTimeout() {}; /********************** * PRIVATE **********************/ /** * Inner callback */ FileItem.prototype._onBeforeUpload = function _onBeforeUpload() { this.isReady = true; this.isUploading = false; this.isUploaded = false; this.isSuccess = false; this.isCancel = false; this.isError = false; this.progress = 0; this.onBeforeUpload(); }; /** * Inner callback * @param {Number} progress * @private */ FileItem.prototype._onProgress = function _onProgress(progress) { this.progress = progress; this.onProgress(progress); }; /** * Inner callback * @param {*} response * @param {Number} status * @param {Object} headers * @private */ FileItem.prototype._onSuccess = function _onSuccess(response, status, headers) { this.isReady = false; this.isUploading = false; this.isUploaded = true; this.isSuccess = true; this.isCancel = false; this.isError = false; this.progress = 100; this.index = null; this.onSuccess(response, status, headers); }; /** * Inner callback * @param {*} response * @param {Number} status * @param {Object} headers * @private */ FileItem.prototype._onError = function _onError(response, status, headers) { this.isReady = false; this.isUploading = false; this.isUploaded = true; this.isSuccess = false; this.isCancel = false; this.isError = true; this.progress = 0; this.index = null; this.onError(response, status, headers); }; /** * Inner callback * @param {*} response * @param {Number} status * @param {Object} headers * @private */ FileItem.prototype._onCancel = function _onCancel(response, status, headers) { this.isReady = false; this.isUploading = false; this.isUploaded = false; this.isSuccess = false; this.isCancel = true; this.isError = false; this.progress = 0; this.index = null; this.onCancel(response, status, headers); }; /** * Inner callback * @param {*} response * @param {Number} status * @param {Object} headers * @private */ FileItem.prototype._onComplete = function _onComplete(response, status, headers) { this.onComplete(response, status, headers); if (this.removeAfterUpload) this.remove(); }; /** * Inner callback * @private */ FileItem.prototype._onTimeout = function _onTimeout() { this.isReady = false; this.isUploading = false; this.isUploaded = false; this.isSuccess = false; this.isCancel = false; this.isError = true; this.progress = 0; this.index = null; this.onTimeout(); }; /** * Destroys a FileItem */ FileItem.prototype._destroy = function _destroy() { if (this._input) this._input.remove(); if (this._form) this._form.remove(); delete this._form; delete this._input; }; /** * Prepares to uploading * @private */ FileItem.prototype._prepareToUploading = function _prepareToUploading() { this.index = this.index || ++this.uploader._nextIndex; this.isReady = true; }; /** * Replaces input element on his clone * @param {JQLite|jQuery} input * @private */ FileItem.prototype._replaceNode = function _replaceNode(input) { var clone = $compile(input.clone())(input.scope()); clone.prop('value', null); // FF fix input.css('display', 'none'); input.after(clone); // remove jquery dependency }; return FileItem; }(); } __identity.$inject = ['$compile', 'FileLikeObject']; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _angular = angular, extend = _angular.extend; function __identity() { var FileDirective = function () { /** * Creates instance of {FileDirective} object * @param {Object} options * @param {Object} options.uploader * @param {HTMLElement} options.element * @param {Object} options.events * @param {String} options.prop * @constructor */ function FileDirective(options) { _classCallCheck(this, FileDirective); extend(this, options); this.uploader._directives[this.prop].push(this); this._saveLinks(); this.bind(); } /** * Binds events handles */ FileDirective.prototype.bind = function bind() { for (var key in this.events) { var prop = this.events[key]; this.element.bind(key, this[prop]); } }; /** * Unbinds events handles */ FileDirective.prototype.unbind = function unbind() { for (var key in this.events) { this.element.unbind(key, this.events[key]); } }; /** * Destroys directive */ FileDirective.prototype.destroy = function destroy() { var index = this.uploader._directives[this.prop].indexOf(this); this.uploader._directives[this.prop].splice(index, 1); this.unbind(); // this.element = null; }; /** * Saves links to functions * @private */ FileDirective.prototype._saveLinks = function _saveLinks() { for (var key in this.events) { var prop = this.events[key]; this[prop] = this[prop].bind(this); } }; return FileDirective; }(); /** * Map of events * @type {Object} */ FileDirective.prototype.events = {}; return FileDirective; } /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _angular = angular, extend = _angular.extend; function __identity($compile, FileDirective) { return function (_FileDirective) { _inherits(FileSelect, _FileDirective); /** * Creates instance of {FileSelect} object * @param {Object} options * @constructor */ function FileSelect(options) { _classCallCheck(this, FileSelect); var extendedOptions = extend(options, { // Map of events events: { $destroy: 'destroy', change: 'onChange' }, // Name of property inside uploader._directive object prop: 'select' }); var _this = _possibleConstructorReturn(this, _FileDirective.call(this, extendedOptions)); if (!_this.uploader.isHTML5) { _this.element.removeAttr('multiple'); } _this.element.prop('value', null); // FF fix return _this; } /** * Returns options * @return {Object|undefined} */ FileSelect.prototype.getOptions = function getOptions() {}; /** * Returns filters * @return {Array<Function>|String|undefined} */ FileSelect.prototype.getFilters = function getFilters() {}; /** * If returns "true" then HTMLInputElement will be cleared * @returns {Boolean} */ FileSelect.prototype.isEmptyAfterSelection = function isEmptyAfterSelection() { return !!this.element.attr('multiple'); }; /** * Event handler */ FileSelect.prototype.onChange = function onChange() { var files = this.uploader.isHTML5 ? this.element[0].files : this.element[0]; var options = this.getOptions(); var filters = this.getFilters(); if (!this.uploader.isHTML5) this.destroy(); this.uploader.addToQueue(files, options, filters); if (this.isEmptyAfterSelection()) { this.element.prop('value', null); this.element.replaceWith($compile(this.element.clone())(this.scope)); // IE fix } }; return FileSelect; }(FileDirective); } __identity.$inject = ['$compile', 'FileDirective']; /***/ }), /* 8 */ /***/ (function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; 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"); } } var _angular = angular, bind = _angular.bind, isUndefined = _angular.isUndefined; function __identity($q) { return function () { /** * @param {Array<Function>} pipes */ function Pipeline() { var pipes = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; _classCallCheck(this, Pipeline); this.pipes = pipes; } Pipeline.prototype.next = function next(args) { var pipe = this.pipes.shift(); if (isUndefined(pipe)) { this.onSuccessful.apply(this, _toConsumableArray(args)); return; } var err = new Error('The filter has not passed'); err.pipe = pipe; err.args = args; if (pipe.isAsync) { var deferred = $q.defer(); var onFulfilled = bind(this, this.next, args); var onRejected = bind(this, this.onThrown, err); deferred.promise.then(onFulfilled, onRejected); pipe.apply(undefined, _toConsumableArray(args).concat([deferred])); } else { var isDone = Boolean(pipe.apply(undefined, _toConsumableArray(args))); if (isDone) { this.next(args); } else { this.onThrown(err); } } }; Pipeline.prototype.exec = function exec() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } this.next(args); }; Pipeline.prototype.onThrown = function onThrown(err) {}; Pipeline.prototype.onSuccessful = function onSuccessful() {}; return Pipeline; }(); } __identity.$inject = ['$q']; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _angular = angular, extend = _angular.extend, forEach = _angular.forEach; function __identity(FileDirective) { return function (_FileDirective) { _inherits(FileDrop, _FileDirective); /** * Creates instance of {FileDrop} object * @param {Object} options * @constructor */ function FileDrop(options) { _classCallCheck(this, FileDrop); var extendedOptions = extend(options, { // Map of events events: { $destroy: 'destroy', drop: 'onDrop', dragover: 'onDragOver', dragleave: 'onDragLeave' }, // Name of property inside uploader._directive object prop: 'drop' }); return _possibleConstructorReturn(this, _FileDirective.call(this, extendedOptions)); } /** * Returns options * @return {Object|undefined} */ FileDrop.prototype.getOptions = function getOptions() {}; /** * Returns filters * @return {Array<Function>|String|undefined} */ FileDrop.prototype.getFilters = function getFilters() {}; /** * Event handler */ FileDrop.prototype.onDrop = function onDrop(event) { var transfer = this._getTransfer(event); if (!transfer) return; var options = this.getOptions(); var filters = this.getFilters(); this._preventAndStop(event); forEach(this.uploader._directives.over, this._removeOverClass, this); this.uploader.addToQueue(transfer.files, options, filters); }; /** * Event handler */ FileDrop.prototype.onDragOver = function onDragOver(event) { var transfer = this._getTransfer(event); if (!this._haveFiles(transfer.types)) return; transfer.dropEffect = 'copy'; this._preventAndStop(event); forEach(this.uploader._directives.over, this._addOverClass, this); }; /** * Event handler */ FileDrop.prototype.onDragLeave = function onDragLeave(event) { if (event.currentTarget === this.element[0]) return; this._preventAndStop(event); forEach(this.uploader._directives.over, this._removeOverClass, this); }; /** * Helper */ FileDrop.prototype._getTransfer = function _getTransfer(event) { return event.dataTransfer ? event.dataTransfer : event.originalEvent.dataTransfer; // jQuery fix; }; /** * Helper */ FileDrop.prototype._preventAndStop = function _preventAndStop(event) { event.preventDefault(); event.stopPropagation(); }; /** * Returns "true" if types contains files * @param {Object} types */ FileDrop.prototype._haveFiles = function _haveFiles(types) { if (!types) return false; if (types.indexOf) { return types.indexOf('Files') !== -1; } else if (types.contains) { return types.contains('Files'); } else { return false; } }; /** * Callback */ FileDrop.prototype._addOverClass = function _addOverClass(item) { item.addOverClass(); }; /** * Callback */ FileDrop.prototype._removeOverClass = function _removeOverClass(item) { item.removeOverClass(); }; return FileDrop; }(FileDirective); } __identity.$inject = ['FileDirective']; /***/ }), /* 10 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _angular = angular, extend = _angular.extend; function __identity(FileDirective) { return function (_FileDirective) { _inherits(FileOver, _FileDirective); /** * Creates instance of {FileDrop} object * @param {Object} options * @constructor */ function FileOver(options) { _classCallCheck(this, FileOver); var extendedOptions = extend(options, { // Map of events events: { $destroy: 'destroy' }, // Name of property inside uploader._directive object prop: 'over', // Over class overClass: 'nv-file-over' }); return _possibleConstructorReturn(this, _FileDirective.call(this, extendedOptions)); } /** * Adds over class */ FileOver.prototype.addOverClass = function addOverClass() { this.element.addClass(this.getOverClass()); }; /** * Removes over class */ FileOver.prototype.removeOverClass = function removeOverClass() { this.element.removeClass(this.getOverClass()); }; /** * Returns over class * @returns {String} */ FileOver.prototype.getOverClass = function getOverClass() { return this.overClass; }; return FileOver; }(FileDirective); } __identity.$inject = ['FileDirective']; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function __identity($parse, FileUploader, FileSelect) { return { link: function link(scope, element, attributes) { var uploader = scope.$eval(attributes.uploader); if (!(uploader instanceof FileUploader)) { throw new TypeError('"Uploader" must be an instance of FileUploader'); } var object = new FileSelect({ uploader: uploader, element: element, scope: scope }); object.getOptions = $parse(attributes.options).bind(object, scope); object.getFilters = function () { return attributes.filters; }; } }; } __identity.$inject = ['$parse', 'FileUploader', 'FileSelect']; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function __identity($parse, FileUploader, FileDrop) { return { link: function link(scope, element, attributes) { var uploader = scope.$eval(attributes.uploader); if (!(uploader instanceof FileUploader)) { throw new TypeError('"Uploader" must be an instance of FileUploader'); } if (!uploader.isHTML5) return; var object = new FileDrop({ uploader: uploader, element: element }); object.getOptions = $parse(attributes.options).bind(object, scope); object.getFilters = function () { return attributes.filters; }; } }; } __identity.$inject = ['$parse', 'FileUploader', 'FileDrop']; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = __identity; var _config = __webpack_require__(1); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function __identity(FileUploader, FileOver) { return { link: function link(scope, element, attributes) { var uploader = scope.$eval(attributes.uploader); if (!(uploader instanceof FileUploader)) { throw new TypeError('"Uploader" must be an instance of FileUploader'); } var object = new FileOver({ uploader: uploader, element: element }); object.getOverClass = function () { return attributes.overClass || object.overClass; }; } }; } __identity.$inject = ['FileUploader', 'FileOver']; /***/ }) /******/ ]) }); ; //# sourceMappingURL=angular-file-upload.js.map
import axios from 'axios'; import jwtDecode from 'jwt-decode'; import toastr from 'toastr'; import types from '../actions/actionTypes'; import setAuthorizationToken from '../utils/setAuthorizationToken'; /** * * * @export * @param {Object} user * @returns {Object} */ export function setCurrentUser(user) { return { type: types.SET_CURRENT_USER, user }; } /** * * * @export * @param {Object} loginDetails * @returns {Object} */ export function login(loginDetails) { return dispatch => axios.post('/users/login', loginDetails) .then((response) => { const token = response.data.token; localStorage.setItem('jwtToken', token); setAuthorizationToken(token); dispatch(setCurrentUser(jwtDecode(token))); console.log(jwtDecode(token)); }) .catch((error) => { console.log(error); dispatch({ type: types.VALIDATION_ERROR, response: error.response.data.message }); }); } /** * * * @export * @param {any} userDetails * @returns */ export function signUp(userDetails) { return dispatch => axios.post('/users/', userDetails) .then((response) => { const token = response.data.token; localStorage.setItem('jwtToken', token); setAuthorizationToken(token); dispatch({ type: types.SIGNUP_USER, response: response.data.user }); dispatch(setCurrentUser(jwtDecode(token))); dispatch({ type: types.CLEAR_ERROR }); }) .catch((error) => { dispatch({ type: types.VALIDATION_ERROR, response: error.response.data.message }); }); } /** * * * @export * @returns */ export function logout() { return dispatch => axios.post('/users/logout') .then(() => { localStorage.removeItem('jwtToken'); setAuthorizationToken(false); dispatch({ type: types.LOGOUT_USER }); }) .catch((error) => { dispatch({ type: types.VALIDATION_ERROR, response: error.response.data.message }); }); }
/*! * js-file-browser * Copyright(c) 2011 Biotechnology Computing Facility, University of Arizona. See included LICENSE.txt file. * * With components from: Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /*! * Ext JS Library 3.3.1 * Copyright(c) 2006-2010 Sencha Inc. * licensing@sencha.com * http://www.sencha.com/license */ /** * @class Ext.grid.CheckboxSelectionModel * @extends Ext.grid.RowSelectionModel * A custom selection model that renders a column of checkboxes that can be toggled to select or deselect rows. * @constructor * @param {Object} config The configuration options */ Ext.grid.CheckboxSelectionModel = Ext.extend(Ext.grid.RowSelectionModel, { /** * @cfg {Boolean} checkOnly <tt>true</tt> if rows can only be selected by clicking on the * checkbox column (defaults to <tt>false</tt>). */ /** * @cfg {String} header Any valid text or HTML fragment to display in the header cell for the * checkbox column. Defaults to:<pre><code> * '&lt;div class="x-grid3-hd-checker">&#38;#160;&lt;/div>'</tt> * </code></pre> * The default CSS class of <tt>'x-grid3-hd-checker'</tt> displays a checkbox in the header * and provides support for automatic check all/none behavior on header click. This string * can be replaced by any valid HTML fragment, including a simple text string (e.g., * <tt>'Select Rows'</tt>), but the automatic check all/none behavior will only work if the * <tt>'x-grid3-hd-checker'</tt> class is supplied. */ header : '<div class="x-grid3-hd-checker">&#160;</div>', /** * @cfg {Number} width The default width in pixels of the checkbox column (defaults to <tt>20</tt>). */ width : 20, /** * @cfg {Boolean} sortable <tt>true</tt> if the checkbox column is sortable (defaults to * <tt>false</tt>). */ sortable : false, // private menuDisabled : true, fixed : true, hideable: false, dataIndex : '', id : 'checker', isColumn: true, // So that ColumnModel doesn't feed this through the Column constructor constructor : function(){ Ext.grid.CheckboxSelectionModel.superclass.constructor.apply(this, arguments); if(this.checkOnly){ this.handleMouseDown = Ext.emptyFn; } }, // private initEvents : function(){ Ext.grid.CheckboxSelectionModel.superclass.initEvents.call(this); this.grid.on('render', function(){ Ext.fly(this.grid.getView().innerHd).on('mousedown', this.onHdMouseDown, this); }, this); }, /** * @private * Process and refire events routed from the GridView's processEvent method. */ processEvent : function(name, e, grid, rowIndex, colIndex){ if (name == 'mousedown') { this.onMouseDown(e, e.getTarget()); return false; } else { return Ext.grid.Column.prototype.processEvent.apply(this, arguments); } }, // private onMouseDown : function(e, t){ if(e.button === 0 && t.className == 'x-grid3-row-checker'){ // Only fire if left-click e.stopEvent(); var row = e.getTarget('.x-grid3-row'); if(row){ var index = row.rowIndex; if(this.isSelected(index)){ this.deselectRow(index); }else{ this.selectRow(index, true); this.grid.getView().focusRow(index); } } } }, // private onHdMouseDown : function(e, t) { if(t.className == 'x-grid3-hd-checker'){ e.stopEvent(); var hd = Ext.fly(t.parentNode); var isChecked = hd.hasClass('x-grid3-hd-checker-on'); if(isChecked){ hd.removeClass('x-grid3-hd-checker-on'); this.clearSelections(); }else{ hd.addClass('x-grid3-hd-checker-on'); this.selectAll(); } } }, // private renderer : function(v, p, record){ return '<div class="x-grid3-row-checker">&#160;</div>'; }, onEditorSelect: function(row, lastRow){ if(lastRow != row && !this.checkOnly){ this.selectRow(row); // *** highlight newly-selected cell and update selection } } });
import Parse from 'parse/node'; import { GraphQLID, GraphQLObjectType, GraphQLString, GraphQLNonNull, GraphQLList, } from 'graphql'; import Departments from './Departments'; const Contacts = Parse.Object.extend('Contacts'); const ContactsType = new GraphQLObjectType({ name: 'Contacts', description: 'A concise description of what Contacts is', fields: () => ({ id: { type: GraphQLID, }, // XX: you should probably replace this with something // relevant to your model name: { type: GraphQLString, resolve: contacts => contacts.get('name'), }, tel: { type: GraphQLString, resolve: contacts => contacts.get('tel'), }, email: { type: GraphQLString, resolve: contacts => contacts.get('email'), }, address: { type: GraphQLString, resolve: contacts => contacts.get('address'), }, updatedAt: { type: GraphQLString, resolve: contacts => contacts.get('updatedAt').toLocaleDateString(), }, avatar: { type: GraphQLString, resolve: contacts => contacts.get('avatar').url(), }, department: { type: Departments.SchemaType, resolve: contacts => contacts.get('department').fetch({ success: department => department, error: error => error, }), }, // more field defs here }), }); Contacts.SchemaType = ContactsType; Contacts.RootQuery = { type: new GraphQLList(Contacts.SchemaType), resolve: (_, args, { Query }) => { const query = new Query(Contacts); return query.find(); }, }; Contacts.Mutations = { addContacts: { type: Contacts.SchemaType, description: 'Create a new instance of Contacts', args: { name: { type: new GraphQLNonNull(GraphQLString) }, tel: { type: new GraphQLNonNull(GraphQLString) }, email: { type: new GraphQLNonNull(GraphQLString) }, address: { type: new GraphQLNonNull(GraphQLString) }, avatarData: { type: new GraphQLNonNull(GraphQLString) }, departmentId: { type: new GraphQLNonNull(GraphQLID) }, }, resolve: (_, { name, tel, email, address, avatarData, departmentId }, { Query }) => { let avatar = new Parse.File("avatar.jpg", { base64: avatarData }); return avatar.save().then(()=> new Query(Departments).get(departmentId) ).then((department) => new Query(Contacts).create({ name, tel, email, address, avatar, department }).save() ).then(td => td) }, }, deleteContacts: { type: Contacts.SchemaType, description: 'Delete an instance of Contacts', args: { id: { type: new GraphQLNonNull(GraphQLID) }, }, resolve: (_, { id }, { Query }) => new Query(Contacts).get(id).then((contacts) => { if (contacts) { return contacts.destroy(); } return contacts; }), }, editContactsAvatar: { type: Contacts.SchemaType, description: 'Edit avatar of an instance in Contacts', args: { id: { type: new GraphQLNonNull(GraphQLID) }, avatarData: { type: new GraphQLNonNull(GraphQLString) }, }, resolve: (_, { id, avatarData }, { Query }) => { let avatar = new Parse.File('avatar.jpg', { base64: avatarData }); return avatar.save().then(() => new Query(Contacts).get(id) ).then((contacts) => contacts.save({ avatar }) ).then(td => td); }, }, editContacts: { type: Contacts.SchemaType, description: 'Edit an instance of Contacts', args: { id: { type: new GraphQLNonNull(GraphQLID) }, name: { type: GraphQLString }, tel: { type: GraphQLString }, email: { type: GraphQLString }, address: { type: GraphQLString }, departmentId: { type: new GraphQLNonNull(GraphQLString) }, }, resolve: (_, { id, name, tel, email, address, departmentId }, { Query }) => { return new Query(Departments).get(departmentId).then((department) => new Query(Contacts).get(id).then((contacts) => contacts.save({name, tel, email, address, department})) ).then(td => td) }, }, }; export default Contacts;
const webpack = require('webpack'); module.exports = { entry: './src/bundle/wrapper.js', output: { libraryTarget: 'var', library: 'showChatTemplate', path: 'builds', filename: 'chat-template-min.js', }, module: { loaders: [ { test: /\.js/, loader: 'babel', include: __dirname + '/src', } ], }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }) ], };
import React from 'react' import styled from 'styled-components' import Nav from './Nav' import { colors } from '../constants' const Header = styled.header` display: flex; flex-flow: row nowrap; align-items: center; justify-content: space-between; height: 45px; background-color: ${colors.gray}; border-bottom: 2px solid ${colors.gray300}; ` const Logo = styled.div` font-size: 2rem; ` export default () => ( <Header> <Logo /> <Nav /> </Header> )
/*! jQuery centershow - v1.0.0 - 2014-12-19 * Copyright (c) 2014 kssfilo; Licensed MIT */ (function($){ $.fn.centershow=function(){ var back=$('<div onclick="$(this).hide()" style="position:fixed;top:0;left:0;width:100%;height:100%;background-color:rgba(0,0,0,0.8);">'); $('body').append(back); var close=$('<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAC0AAAAtCAMAAAANxBKoAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3gwTBCUV4ZteXwAAAFdQTFRFAAAAtra2////////iYmJjIyM////////////////////////1NTU////19fX////////////////////////////////6Ojo////////7Ozs7e3t////cG4hugAAABp0Uk5TAAEBAiorLi8wNzhuc3h7gIiRx8jJytHV/f7S9UgRAAAAAWJLR0QcnARBBwAAAY5JREFUSMetlduagyAMhAN2a7XVWGyr1Hn/59wLjgK2+u1yhfAbhzgJRNkYmDt0zAN9HYOChhka6uMLbUD9C20ZlY1CaahGFugbtsYth1/h49wTUc9B1iuD3Q5Hi+wivIqw6ikWKalXBdzCdeE4dYpLNvC5dHh5Nji7zQbbsMfR2Gf1Cfa4sn/QaHaw8JibSfMr2hD67bIweUjQ5DL0DsEBABdhYMyL/YqslxkGFxcAABHRoN2MiKD9eRoA2q8D0IMV4vJznwFgJCKiEQDme5Rj5YRQFAP6eapOT51vWCEqyS2uSP6BMlJ4ZSXZjKEe9BisbTEOqUzcuLJSa+guVhckFlc7ytYrp/laZTEOxt6pu49OuTsnq3wLWym42gquxTrf8TEFLVZCZQUtzpGOin0yZT6ZEp8c82Dqb+cNeUbB30nt3H1HieZR7Zi6vMnN1ruqy2M1f7Cf7OlVsVLrDaaUl7bPltqmRp302No4YKMl7+vfAS/cDTkcAuWD/3ynEdHPI7svHz//dBd/ved/ARv8V5YcG4VYAAAAAElFTkSuQmCC" />'); close.appendTo(back); this.each(function(){ var self=$(this); self.css({ position:'fixed', 'top':'50%', 'left':'50%', 'margin-left':-self.width()/2, 'margin-top':-self.height()/2, 'z-index':1, }); self.appendTo(back); }); }; })(jQuery);
app.factory('worker', ['$http', function($http) { return $http.get('http://localhost:3000/api/worker') .success(function(data) { return data; }) .error(function(err) { return err; }); }]);
exports.names = ['dctime', 'dctimer']; exports.hidden = false; exports.enabled = true; exports.matchStart = true; exports.cd_all = 0; exports.cd_user = 0; exports.cd_manager = 0; exports.min_role = PERMISSIONS.MANAGER; exports.handler = function (data) { var input = data.message.split(' '); var command = _.first(input); var params = _.rest(input); if (params.length < 1) { modMessage(data, 'Current DC timer length: ' + sec_to_str(settings['dctimer']) + '.'); } else { var new_length = parseFloat(params); if (!isNaN(new_length)) { set_setting('dctimer', Math.floor(new_length * 60), data); modMessage(data, 'DC timer length set to ' + sec_to_str(settings['dctimer']) + '.'); } } };
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. * * @flow */ import nullthrows from 'nullthrows'; import nuclideUri from '../../commons-node/nuclideUri'; import observeGrammarForTextEditors from '../observe-grammar-for-text-editors'; import observeLanguageTextEditors from '../observe-language-text-editors'; describe('observeLanguageTextEditors', () => { let objcGrammar: atom$Grammar = (null: any); let javaGrammar: atom$Grammar = (null: any); let jsGrammar: atom$Grammar = (null: any); let nullGrammar: atom$Grammar = (null: any); let grammarScopes: Array<string> = (null: any); beforeEach(() => { observeGrammarForTextEditors.__reset__(); atom.grammars.loadGrammarSync(nuclideUri.join(__dirname, 'grammars/objective-c.cson')); objcGrammar = nullthrows(atom.grammars.grammarForScopeName('source.objc')); atom.grammars.loadGrammarSync(nuclideUri.join(__dirname, 'grammars/java.cson')); javaGrammar = nullthrows(atom.grammars.grammarForScopeName('source.java')); atom.grammars.loadGrammarSync(nuclideUri.join(__dirname, 'grammars/javascript.cson')); jsGrammar = nullthrows(atom.grammars.grammarForScopeName('source.js')); nullGrammar = nullthrows(atom.grammars.grammarForScopeName('text.plain.null-grammar')); grammarScopes = [ objcGrammar.scopeName, javaGrammar.scopeName, ]; }); describe('without cleanup function', () => { it('calls for existing text editors that match the grammars', () => { waitsForPromise(async () => { const textEditor = await atom.workspace.open('file.m'); const fn: any = jasmine.createSpy('fn'); const subscription = observeLanguageTextEditors(grammarScopes, fn); expect(fn).toHaveBeenCalledWith(textEditor); expect(fn.callCount).toBe(1); subscription.dispose(); textEditor.destroy(); }); }); it('calls for new text editors that already match the grammars', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const subscription = observeLanguageTextEditors(grammarScopes, fn); const textEditor = await atom.workspace.open('file.m'); expect(fn).toHaveBeenCalledWith(textEditor); expect(fn.callCount).toBe(1); subscription.dispose(); textEditor.destroy(); }); }); it('calls for new text editors that change to match the grammars', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const subscription = observeLanguageTextEditors(grammarScopes, fn); const textEditor = await atom.workspace.open(); textEditor.setGrammar(objcGrammar); expect(fn).toHaveBeenCalledWith(textEditor); expect(fn.callCount).toBe(1); subscription.dispose(); textEditor.destroy(); }); }); it('does not call for new text editors that change and still don\'t match the grammars', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const subscription = observeLanguageTextEditors(grammarScopes, fn); const textEditor = await atom.workspace.open(); textEditor.setGrammar(jsGrammar); expect(fn.callCount).toBe(0); subscription.dispose(); textEditor.destroy(); }); }); it('does not call for text editors whose matching grammar changes but still matches', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const subscription = observeLanguageTextEditors(grammarScopes, fn); const textEditor = await atom.workspace.open('file.m'); textEditor.setGrammar(javaGrammar); expect(fn).toHaveBeenCalledWith(textEditor); expect(fn.callCount).toBe(1); subscription.dispose(); textEditor.destroy(); }); }); it('stops listening to grammar changes on text editors that are destroyed', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const subscription = observeLanguageTextEditors(grammarScopes, fn); const textEditor = await atom.workspace.open('file.m'); textEditor.destroy(); subscription.dispose(); }); }); }); describe('with cleanup function', () => { it('does not call for existing text editors that do not match the grammars', () => { waitsForPromise(async () => { const textEditor = await atom.workspace.open(); const fn: any = jasmine.createSpy('fn'); const cleanupFn: any = jasmine.createSpy('cleanupFn'); const subscription = observeLanguageTextEditors(grammarScopes, fn, cleanupFn); expect(cleanupFn.callCount).toBe(0); subscription.dispose(); textEditor.destroy(); }); }); it('does not call for new text editors that never matched the grammars', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const cleanupFn: any = jasmine.createSpy('cleanupFn'); const subscription = observeLanguageTextEditors(grammarScopes, fn, cleanupFn); const textEditor = await atom.workspace.open('file.js'); textEditor.setGrammar(nullGrammar); expect(cleanupFn.callCount).toBe(0); subscription.dispose(); textEditor.destroy(); }); }); it('calls for new text editors that stop matching the grammars', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const cleanupFn: any = jasmine.createSpy('cleanupFn'); const subscription = observeLanguageTextEditors(grammarScopes, fn, cleanupFn); const textEditor = await atom.workspace.open('file.m'); textEditor.setGrammar(nullGrammar); expect(cleanupFn).toHaveBeenCalledWith(textEditor); expect(cleanupFn.callCount).toBe(1); subscription.dispose(); textEditor.destroy(); }); }); it('does not call when new text editors that do not match the grammars are destroyed', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const cleanupFn: any = jasmine.createSpy('cleanupFn'); const subscription = observeLanguageTextEditors(grammarScopes, fn, cleanupFn); const textEditor = await atom.workspace.open('file.js'); textEditor.destroy(); expect(cleanupFn.callCount).toBe(0); subscription.dispose(); }); }); it('calls when new text editors matching the grammars are destroyed', () => { waitsForPromise(async () => { const fn: any = jasmine.createSpy('fn'); const cleanupFn: any = jasmine.createSpy('cleanupFn'); const subscription = observeLanguageTextEditors(grammarScopes, fn, cleanupFn); const textEditor = await atom.workspace.open('file.m'); textEditor.destroy(); expect(cleanupFn).toHaveBeenCalledWith(textEditor); expect(cleanupFn.callCount).toBe(1); subscription.dispose(); }); }); }); });
// Script met de functionaliteit voor .dropdown $(function () { $('.dropdown-dynamic .dropdown-title').on('click', function () { // Toggle class 'is-hiding' van ul $(this).next().find('ul').toggleClass('is-hiding'); // Toggle het icoontje $(this).find('i.fa').toggleClass('fa-chevron-down fa-chevron-up'); }); });
$(document).ready(function() { // Mobile navigation mobileNavigation(); }); // Mobile navigation function mobileNavigation() { $('#mobile-nav-btn').click(function() { $('#mobile-nav').toggle(); $('body, html').toggleClass('no-scroll'); if($('#mobile-nav').is(":visible")) { var mobile_nav_height = $(window).height() - $('#mobile-header').height(); $('#mobile-nav').css('height',mobile_nav_height+'px'); }; }); };
$(document).ready(function() { $("#logInBtn").click(function(){ $("#chatSection").slideToggle("slow",function() { }); }); }); var doTimeout = true; var lastid = 0; window.addEventListener("load", function() { /* var btn = document.getElementById("startBtn"); btn.addEventListener("click", function() { doTimeout = true; getChat(); }, true); var sbtn = document.getElementById("stopBtn"); sbtn.addEventListener("click", function() { doTimeout = false; }, true); */ var sendfrm = document.getElementById("sendmsg"); sendfrm.addEventListener("submit", function(e) { e.preventDefault(); e.stopPropagation(); sendMsgs(); }, true); getChat(); }, false); function getChat() { var xhr = null; if(window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } if(xhr) { xhr.onreadystatechange = function() { if(xhr.readyState === 4) { if(xhr.status === 200) { var value = xhr.responseXML; var msgs = value.getElementsByTagName('message'); console.log("Processing ", msgs.length, " messages"); var tbl = document.getElementById("messageDisplay"); for(var i = 0; i < msgs.length; i++) { var id = parseInt(msgs[i].getAttribute("id")); if(lastid < id) { lastid = id; } tbl.innerHTML += "<tr><td>" + msgs[i].childNodes[1].firstChild.nodeValue + "</td></tr>"; } if(doTimeout) { setTimeout(getChat, 1000); } } } }; xhr.open("GET", "http://itsuite.it.brighton.ac.uk/john10/ci227/a1/channel.php?username=guest&lastid=" + lastid, true); xhr.send(null); } else { console.error("Can't continue"); } } function sendMsgs() { var val = document.getElementById("messageInput").value; // Check val is ok before doing AJAX var xhr = null; if(window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } else if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } if(xhr) { xhr.onreadystatechange = function() { if(xhr.readyState === 4) { if(xhr.status === 200) { alert(xhr.responseText); } } }; xhr.open("POST", "http://itsuite.it.brighton.ac.uk/john10/ci227/a1/send.php", true); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send("from=guest&message=" + val); } else { console.error("Can't continue"); } } /* function addTable() { var html = "<table><tr><td>123</td><td>456</td></tr></table>"; document.getElementById("addtable").innerHTML = html; */
'use strict'; describe('aid.js', function() { describe('aid.math', function() { var math = aid.math; describe('.getSizeAspectFill()', function() { it('input arguments are not Number type, throw TypeError.', function() { var ERROR_MSG = '[aid.math.getSizeAspectFill] Type of parameters must be Number.'; expect(function() { math.getSizeAspectFill(undefined, 1, 1, 1); math.getSizeAspectFill(1, undefined, 1, 1); math.getSizeAspectFill(1, 1, undefined, 1); math.getSizeAspectFill(1, 1, 1, undefined); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill(null, 1, 1, 1); math.getSizeAspectFill(1, null, 1, 1); math.getSizeAspectFill(1, 1, null, 1); math.getSizeAspectFill(1, 1, 1, null); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill(false, 1, 1, 1); math.getSizeAspectFill(1, false, 1, 1); math.getSizeAspectFill(1, 1, false, 1); math.getSizeAspectFill(1, 1, 1, false); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill(true, 1, 1, 1); math.getSizeAspectFill(1, true, 1, 1); math.getSizeAspectFill(1, 1, true, 1); math.getSizeAspectFill(1, 1, 1, true); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill('', 1, 1, 1); math.getSizeAspectFill(1, '', 1, 1); math.getSizeAspectFill(1, 1, '', 1); math.getSizeAspectFill(1, 1, 1, ''); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill({}, 1, 1, 1); math.getSizeAspectFill(1, {}, 1, 1); math.getSizeAspectFill(1, 1, {}, 1); math.getSizeAspectFill(1, 1, 1, {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill([], 1, 1, 1); math.getSizeAspectFill(1, [], 1, 1); math.getSizeAspectFill(1, 1, [], 1); math.getSizeAspectFill(1, 1, 1, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill(function() {}, 1, 1, 1); math.getSizeAspectFill(1, function() {}, 1, 1); math.getSizeAspectFill(1, 1, function() {}, 1); math.getSizeAspectFill(1, 1, 1, function() {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill(new RegExp('^aid'), 1, 1, 1); math.getSizeAspectFill(1, new RegExp('^aid'), 1, 1); math.getSizeAspectFill(1, 1, new RegExp('^aid'), 1); math.getSizeAspectFill(1, 1, 1, new RegExp('^aid')); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill(/^aid/, 1, 1, 1); math.getSizeAspectFill(1, /^aid/, 1, 1); math.getSizeAspectFill(1, 1, /^aid/, 1); math.getSizeAspectFill(1, 1, 1, /^aid/); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFill(1, 1, 1, 1); math.getSizeAspectFill(1, 1, 1, 1); math.getSizeAspectFill(1, 1, 1, 1); math.getSizeAspectFill(1, 1, 1, 1); }).not.toThrowError(TypeError, ERROR_MSG); }); it('return object has width, height variables', function() { var size = math.getSizeAspectFill(1, 1, 1, 1); expect(aid.isObject(size)).toBeTruthy(); expect(aid.isNumber(size.width)).toBeTruthy(); expect(aid.isNumber(size.height)).toBeTruthy(); }); }); describe('.getSizeAspectFit()', function() { it('input arguments are not Number type, throw TypeError.', function() { var ERROR_MSG = '[aid.math.getSizeAspectFit] Type of parameters must be Number.'; expect(function() { math.getSizeAspectFit(undefined, 1, 1, 1); math.getSizeAspectFit(1, undefined, 1, 1); math.getSizeAspectFit(1, 1, undefined, 1); math.getSizeAspectFit(1, 1, 1, undefined); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit(null, 1, 1, 1); math.getSizeAspectFit(1, null, 1, 1); math.getSizeAspectFit(1, 1, null, 1); math.getSizeAspectFit(1, 1, 1, null); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit(false, 1, 1, 1); math.getSizeAspectFit(1, false, 1, 1); math.getSizeAspectFit(1, 1, false, 1); math.getSizeAspectFit(1, 1, 1, false); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit(true, 1, 1, 1); math.getSizeAspectFit(1, true, 1, 1); math.getSizeAspectFit(1, 1, true, 1); math.getSizeAspectFit(1, 1, 1, true); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit('', 1, 1, 1); math.getSizeAspectFit(1, '', 1, 1); math.getSizeAspectFit(1, 1, '', 1); math.getSizeAspectFit(1, 1, 1, ''); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit({}, 1, 1, 1); math.getSizeAspectFit(1, {}, 1, 1); math.getSizeAspectFit(1, 1, {}, 1); math.getSizeAspectFit(1, 1, 1, {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit([], 1, 1, 1); math.getSizeAspectFit(1, [], 1, 1); math.getSizeAspectFit(1, 1, [], 1); math.getSizeAspectFit(1, 1, 1, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit(function() {}, 1, 1, 1); math.getSizeAspectFit(1, function() {}, 1, 1); math.getSizeAspectFit(1, 1, function() {}, 1); math.getSizeAspectFit(1, 1, 1, function() {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit(new RegExp('^aid'), 1, 1, 1); math.getSizeAspectFit(1, new RegExp('^aid'), 1, 1); math.getSizeAspectFit(1, 1, new RegExp('^aid'), 1); math.getSizeAspectFit(1, 1, 1, new RegExp('^aid')); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit(/^aid/, 1, 1, 1); math.getSizeAspectFit(1, /^aid/, 1, 1); math.getSizeAspectFit(1, 1, /^aid/, 1); math.getSizeAspectFit(1, 1, 1, /^aid/); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeAspectFit(1, 1, 1, 1); math.getSizeAspectFit(1, 1, 1, 1); math.getSizeAspectFit(1, 1, 1, 1); math.getSizeAspectFit(1, 1, 1, 1); }).not.toThrowError(TypeError, ERROR_MSG); }); it('return object has width, height variables', function() { var size = math.getSizeAspectFit(1, 1, 1, 1); expect(aid.isObject(size)).toBeTruthy(); expect(aid.isNumber(size.width)).toBeTruthy(); expect(aid.isNumber(size.height)).toBeTruthy(); }); }); describe('.getSizeWidthFit()', function() { it('input arguments are not Number type, throw TypeError.', function() { var ERROR_MSG = '[aid.math.getSizeWidthFit] Type of parameters must be Number.'; expect(function() { math.getSizeWidthFit(undefined, 1, 1, 1); math.getSizeWidthFit(1, undefined, 1, 1); math.getSizeWidthFit(1, 1, undefined, 1); math.getSizeWidthFit(1, 1, 1, undefined); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit(null, 1, 1, 1); math.getSizeWidthFit(1, null, 1, 1); math.getSizeWidthFit(1, 1, null, 1); math.getSizeWidthFit(1, 1, 1, null); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit(false, 1, 1, 1); math.getSizeWidthFit(1, false, 1, 1); math.getSizeWidthFit(1, 1, false, 1); math.getSizeWidthFit(1, 1, 1, false); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit(true, 1, 1, 1); math.getSizeWidthFit(1, true, 1, 1); math.getSizeWidthFit(1, 1, true, 1); math.getSizeWidthFit(1, 1, 1, true); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit('', 1, 1, 1); math.getSizeWidthFit(1, '', 1, 1); math.getSizeWidthFit(1, 1, '', 1); math.getSizeWidthFit(1, 1, 1, ''); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit({}, 1, 1, 1); math.getSizeWidthFit(1, {}, 1, 1); math.getSizeWidthFit(1, 1, {}, 1); math.getSizeWidthFit(1, 1, 1, {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit([], 1, 1, 1); math.getSizeWidthFit(1, [], 1, 1); math.getSizeWidthFit(1, 1, [], 1); math.getSizeWidthFit(1, 1, 1, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit(function() {}, 1, 1, 1); math.getSizeWidthFit(1, function() {}, 1, 1); math.getSizeWidthFit(1, 1, function() {}, 1); math.getSizeWidthFit(1, 1, 1, function() {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit(new RegExp('^aid'), 1, 1, 1); math.getSizeWidthFit(1, new RegExp('^aid'), 1, 1); math.getSizeWidthFit(1, 1, new RegExp('^aid'), 1); math.getSizeWidthFit(1, 1, 1, new RegExp('^aid')); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit(/^aid/, 1, 1, 1); math.getSizeWidthFit(1, /^aid/, 1, 1); math.getSizeWidthFit(1, 1, /^aid/, 1); math.getSizeWidthFit(1, 1, 1, /^aid/); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getSizeWidthFit(1, 1, 1, 1); math.getSizeWidthFit(1, 1, 1, 1); math.getSizeWidthFit(1, 1, 1, 1); math.getSizeWidthFit(1, 1, 1, 1); }).not.toThrowError(TypeError, ERROR_MSG); }); it('return object has width, height variables', function() { var size = math.getSizeWidthFit(1, 1, 1, 1); expect(aid.isObject(size)).toBeTruthy(); expect(aid.isNumber(size.width)).toBeTruthy(); expect(aid.isNumber(size.height)).toBeTruthy(); }); }); describe('.isEpsilonEqual()', function() { it('arguments are not Number type, throw TypeError.', function() { expect(function() { math.isEpsilonEqual(1, undefined); math.isEpsilonEqual(undefined, 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, null); math.isEpsilonEqual(null, 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, false); math.isEpsilonEqual(false, 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, true); math.isEpsilonEqual(true, 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, ''); math.isEpsilonEqual('', 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, {}); math.isEpsilonEqual({}, 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, []); math.isEpsilonEqual([], 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, function() {}); math.isEpsilonEqual(function() {}, 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, new RegExp('^aid')); math.isEpsilonEqual(new RegExp('^aid'), 1); }).toThrowError(TypeError); expect(function() { math.isEpsilonEqual(1, /^aid/); math.isEpsilonEqual(/^aid/, 1); }).toThrowError(TypeError); }); it('return true, when Number.EPSILON > Math.abs(number_a - number_b)', function() { expect(math.isEpsilonEqual(0.1 + 0.2, 0.3)).toBe(true); }); }); describe('.isIndexInLoop()', function() { it('throw Error, input 1 or 2 or 3 parameters.', function() { expect(function() { math.isIndexInLoop(8); }).toThrowError(Error); expect(function() { math.isIndexInLoop(8, 5); }).toThrowError(Error); expect(function() { math.isIndexInLoop(8, 5, 6); }).toThrowError(Error); }); it('throw TypeError, input arguments are not Number type.', function() { expect(function() { math.isIndexInLoop(8, 5, 6, undefined); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, null); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, false); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, true); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, ''); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, {}); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, []); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, function() {}); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, new RegExp('^aid')); }).toThrowError(TypeError); expect(function() { math.isIndexInLoop(8, 5, 6, /^aid/); }).toThrowError(TypeError); }); it('return false, when searchIndex is not in (6, 7, 8, 1, 2) in 1 ~ 8.', function() { expect(math.isIndexInLoop(8, 5, 6, 3)).toEqual(false); expect(math.isIndexInLoop(8, 5, 6, 4)).toEqual(false); expect(math.isIndexInLoop(8, 5, 6, 5)).toEqual(false); }); it('return true, when searchIndex is in (6, 7, 8, 1, 2) in 1 ~ 8.', function() { expect(math.isIndexInLoop(8, 5, 6, 6)).toEqual(true); expect(math.isIndexInLoop(8, 5, 6, 7)).toEqual(true); expect(math.isIndexInLoop(8, 5, 6, 8)).toEqual(true); expect(math.isIndexInLoop(8, 5, 6, 1)).toEqual(true); expect(math.isIndexInLoop(8, 5, 6, 2)).toEqual(true); }); it('return false, when searchIndex is not in (4, 1) in 1 ~ 4.', function() { expect(math.isIndexInLoop(4, 2, 4, 2)).toEqual(false); expect(math.isIndexInLoop(4, 2, 4, 3)).toEqual(false); }); it('return true, when searchIndex is in (4, 1) in 1 ~ 4.', function() { expect(math.isIndexInLoop(4, 2, 4, 4)).toEqual(true); expect(math.isIndexInLoop(4, 2, 4, 1)).toEqual(true); }); it('return true, when searchIndex is in (3, 4, 1, 2) in 1 ~ 4.', function() { expect(math.isIndexInLoop(4, 4, 3, 3)).toEqual(true); expect(math.isIndexInLoop(4, 4, 3, 4)).toEqual(true); expect(math.isIndexInLoop(4, 4, 3, 1)).toEqual(true); expect(math.isIndexInLoop(4, 4, 3, 2)).toEqual(true); }); }); describe('.getLoopedLastIndex()', function() { it('throw Error, input 1 or 2 parameters.', function() { expect(function() { math.getLoopedLastIndex(8); }).toThrowError(Error); expect(function() { math.getLoopedLastIndex(8, 1); }).toThrowError(Error); }); it('throw TypeError, input arguments are not Number type.', function() { expect(function() { math.getLoopedLastIndex(8, 1, undefined); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, null); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, false); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, true); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, ''); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, {}); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, []); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, function() {}); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, new RegExp('^aid')); }).toThrowError(TypeError); expect(function() { math.getLoopedLastIndex(8, 1, /^aid/); }).toThrowError(TypeError); }); it('return 7, when firstIndex is 7, loopGap is 1 in 1 ~ 8.', function() { expect(math.getLoopedLastIndex(8, 1, 7)).toEqual(7); }); it('return 8, when firstIndex is 7, loopGap is 2 in 1 ~ 8.', function() { expect(math.getLoopedLastIndex(8, 2, 7)).toEqual(8); }); it('return 1, when firstIndex is 7, loopGap is 3 in 1 ~ 8.', function() { expect(math.getLoopedLastIndex(8, 3, 7)).toEqual(1); }); it('return 2, when firstIndex is 7, loopGap is 4 in 1 ~ 8.', function() { expect(math.getLoopedLastIndex(8, 4, 7)).toEqual(2); }); it('return 3, when firstIndex is 7, loopGap is 5 in 1 ~ 8.', function() { expect(math.getLoopedLastIndex(8, 5, 7)).toEqual(3); }); it('return 4, when firstIndex is 7, loopGap is 6 in 1 ~ 8.', function() { expect(math.getLoopedLastIndex(8, 6, 7)).toEqual(4); }); it('return 5, when firstIndex is 7, loopGap is 7 in 1 ~ 8.', function() { expect(math.getLoopedLastIndex(8, 7, 7)).toEqual(5); }); it('return 6, when firstIndex is 7, loopGap is 8 in 1 ~ 8.', function() { expect(math.getLoopedLastIndex(8, 8, 7)).toEqual(6); }); }); describe('.getReverseLoopedFirstIndex()', function() { it('throw Error, input 1 or 2 parameters.', function() { expect(function() { math.getReverseLoopedFirstIndex(8); }).toThrowError(Error); expect(function() { math.getReverseLoopedFirstIndex(8, 1); }).toThrowError(Error); }); it('throw TypeError, input arguments are not Number type.', function() { expect(function() { math.getReverseLoopedFirstIndex(8, 1, undefined); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, null); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, false); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, true); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, ''); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, {}); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, []); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, function() {}); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, new RegExp('^aid')); }).toThrowError(TypeError); expect(function() { math.getReverseLoopedFirstIndex(8, 1, /^aid/); }).toThrowError(TypeError); }); it('return 2, when lastIndex is 2, loopGap is 1 in 1 ~ 8.', function() { expect(math.getReverseLoopedFirstIndex(8, 1, 2)).toEqual(2); }); it('return 1, when lastIndex is 2, loopGap is 2 in 1 ~ 8.', function() { expect(math.getReverseLoopedFirstIndex(8, 2, 2)).toEqual(1); }); it('return 8, when lastIndex is 2, loopGap is 3 in 1 ~ 8.', function() { expect(math.getReverseLoopedFirstIndex(8, 3, 2)).toEqual(8); }); it('return 7, when lastIndex is 2, loopGap is 4 in 1 ~ 8.', function() { expect(math.getReverseLoopedFirstIndex(8, 4, 2)).toEqual(7); }); it('return 6, when lastIndex is 2, loopGap is 5 in 1 ~ 8.', function() { expect(math.getReverseLoopedFirstIndex(8, 5, 2)).toEqual(6); }); it('return 5, when lastIndex is 2, loopGap is 6 in 1 ~ 8.', function() { expect(math.getReverseLoopedFirstIndex(8, 6, 2)).toEqual(5); }); it('return 4, when lastIndex is 2, loopGap is 7 in 1 ~ 8.', function() { expect(math.getReverseLoopedFirstIndex(8, 7, 2)).toEqual(4); }); it('return 3, when lastIndex is 2, loopGap is 8 in 1 ~ 8.', function() { expect(math.getReverseLoopedFirstIndex(8, 8, 2)).toEqual(3); }); }); describe('.factorial()', function() { it('throw TypeError, input argument is not Integer Number type.', function() { expect(function() { math.factorial(undefined); }).toThrowError(TypeError); expect(function() { math.factorial(null); }).toThrowError(TypeError); expect(function() { math.factorial(false); }).toThrowError(TypeError); expect(function() { math.factorial(true); }).toThrowError(TypeError); expect(function() { math.factorial(''); }).toThrowError(TypeError); expect(function() { math.factorial(0.5); }).toThrowError(TypeError); expect(function() { math.factorial({}); }).toThrowError(TypeError); expect(function() { math.factorial([]); }).toThrowError(TypeError); expect(function() { math.factorial(function() {}); }).toThrowError(TypeError); expect(function() { math.factorial(new RegExp('^aid')); }).toThrowError(TypeError); expect(function() { math.factorial(/^aid/); }).toThrowError(TypeError); }); it('return 1, when factorial param is minus value', function() { expect(math.factorial(-99)).toEqual(1); }); it('return 1, when factorial param is 0', function() { expect(math.factorial(0)).toEqual(1); }); it('return 1, when factorial param is 1', function() { expect(math.factorial(1)).toEqual(1); }); it('return 2, when factorial param is 2', function() { expect(math.factorial(2)).toEqual(2); }); it('return 3, when factorial param is 3', function() { expect(math.factorial(3)).toEqual(6); }); it('return 120, when factorial param is 5', function() { expect(math.factorial(5)).toEqual(120); }); }); describe('.getObjForPagination()', function() { it('throw Error, input 1 or 2 or 3 parameters.', function() { expect(function() { math.getObjForPagination(10); }).toThrowError(Error); expect(function() { math.getObjForPagination(10, 10); }).toThrowError(Error); expect(function() { math.getObjForPagination(10, 10, 10); }).toThrowError(Error); }); it('throw TypeError, input arguments are not Int Number type.', function() { expect(function() { math.getObjForPagination(undefined, 10, 10, 1); }).toThrowError(TypeError); expect(function() { math.getObjForPagination(10, null, 10, 1); }).toThrowError(TypeError); expect(function() { math.getObjForPagination(10, 10, true, 1); }).toThrowError(TypeError); expect(function() { math.getObjForPagination(10, 10, '10', 1); }).toThrowError(TypeError); }); it('throw TypeError, input arguments are not positive Int Number type.', function() { expect(function() { math.getObjForPagination(-1, 10, 10, 1); }).toThrowError(TypeError); expect(function() { math.getObjForPagination(10, 0, 10, 1); }).toThrowError(TypeError); expect(function() { math.getObjForPagination(10, 10, 0, 1); }).toThrowError(TypeError); expect(function() { math.getObjForPagination(10, 10, 10, -1); }).toThrowError(TypeError); }); it('return obj has pagination infos, when input arguments.', function() { expect(math.getObjForPagination(1, 10, 5, 1)).toEqual({ totalPostNum: 1, displayPostNumPerPage: 10, displayPaginationBtnNum: 5, pageIndex: 1, totalPageNum: 1, prevPageIndex: 0, firstPageIndex: 1, lastPageIndex: 1, nextPageIndex: 0, }); expect(math.getObjForPagination(15, 10, 5, 1)).toEqual({ totalPostNum: 15, displayPostNumPerPage: 10, displayPaginationBtnNum: 5, pageIndex: 1, totalPageNum: 2, prevPageIndex: 0, firstPageIndex: 1, lastPageIndex: 2, nextPageIndex: 0, }); expect(math.getObjForPagination(39, 10, 5, 1)).toEqual({ totalPostNum: 39, displayPostNumPerPage: 10, displayPaginationBtnNum: 5, pageIndex: 1, totalPageNum: 4, prevPageIndex: 0, firstPageIndex: 1, lastPageIndex: 4, nextPageIndex: 0, }); }); }); describe('.degreeToRadian()', function() { it('if func parameter type is not Number, throw Error.', function() { expect(function() { math.degreeToRadian(undefined); }).toThrowError(); expect(function() { math.degreeToRadian(null); }).toThrowError(); expect(function() { math.degreeToRadian(false); }).toThrowError(); expect(function() { math.degreeToRadian(true); }).toThrowError(); expect(function() { math.degreeToRadian(0); }).not.toThrowError(); expect(function() { math.degreeToRadian(''); }).toThrowError(); expect(function() { math.degreeToRadian([]); }).toThrowError(); expect(function() { math.degreeToRadian(NaN); }).toThrowError(); expect(function() { math.degreeToRadian(function() {}); }).toThrowError(); }); it('return number when input number', function() { var radian = math.degreeToRadian(90); expect(aid.isNumber(radian)).toBe(true); }); }); describe('.radianToDegree()', function() { it('if func parameter type is not Number, throw Error.', function() { expect(function() { math.radianToDegree(undefined); }).toThrowError(); expect(function() { math.radianToDegree(null); }).toThrowError(); expect(function() { math.radianToDegree(false); }).toThrowError(); expect(function() { math.radianToDegree(true); }).toThrowError(); expect(function() { math.radianToDegree(0); }).not.toThrowError(); expect(function() { math.radianToDegree(''); }).toThrowError(); expect(function() { math.radianToDegree([]); }).toThrowError(); expect(function() { math.radianToDegree(NaN); }).toThrowError(); expect(function() { math.radianToDegree(function() {}); }).toThrowError(); }); it('return number when input number', function() { var degree = math.radianToDegree(90); expect(aid.isNumber(degree)).toBe(true); }); }); describe('.getHeightOfRightTriangle()', function() { it('input arguments are not Object type, throw TypeError.', function() { var ERROR_MSG = '[aid.math.getHeightOfRightTriangle] Type of parameters must be Number.'; expect(function() { math.getHeightOfRightTriangle(undefined, 30); math.getHeightOfRightTriangle(100, undefined); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle(null, 30); math.getHeightOfRightTriangle(100, null); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle(false, 30); math.getHeightOfRightTriangle(100, false); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle(true, 30); math.getHeightOfRightTriangle(100, true); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle('', 30); math.getHeightOfRightTriangle(100, ''); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle([], 30); math.getHeightOfRightTriangle(100, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle(function() {}, 30); math.getHeightOfRightTriangle(100, function() {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle(new RegExp('^aid'), 30); math.getHeightOfRightTriangle(100, new RegExp('^aid')); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle(/^aid/, 30); math.getHeightOfRightTriangle(100, /^aid/); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle(100, 30); }).not.toThrowError(TypeError, ERROR_MSG); }); it('acuteAngleDegree parameter is greater than or equal to 90, throw Error.', function() { var ERROR_MSG = '[aid.math.getHeightOfRightTriangle] acuteAngleDegree parameter cannot greater than or equal to 90.'; expect(function() { math.getHeightOfRightTriangle(100, 90); }).toThrowError(Error, ERROR_MSG); expect(function() { math.getHeightOfRightTriangle(100, 180); }).toThrowError(Error, ERROR_MSG); }); it('return number', function() { var degree = math.getHeightOfRightTriangle(100, 30); expect(aid.isNumber(degree)).toBe(true); }); }); describe('.getDistanceBetweenTwoPoints()', function() { var point1 = { x: 0, y: 0, }, point2 = { x: 100, y: 100, }; it('input arguments are not Object type, throw TypeError.', function() { var ERROR_MSG = '[aid.math.getDistanceBetweenTwoPoints] Type of parameters must be Object.'; expect(function() { math.getDistanceBetweenTwoPoints(undefined, point2); math.getDistanceBetweenTwoPoints(point1, undefined); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints(null, point2); math.getDistanceBetweenTwoPoints(point1, null); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints(false, point2); math.getDistanceBetweenTwoPoints(point1, false); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints(true, point2); math.getDistanceBetweenTwoPoints(point1, true); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints('', point2); math.getDistanceBetweenTwoPoints(point1, ''); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints([], point2); math.getDistanceBetweenTwoPoints(point1, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints(function() {}, point2); math.getDistanceBetweenTwoPoints(point1, function() {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints(new RegExp('^aid'), point2); math.getDistanceBetweenTwoPoints(point1, new RegExp('^aid')); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints(/^aid/, point2); math.getDistanceBetweenTwoPoints(point1, /^aid/); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints(1, point2); math.getDistanceBetweenTwoPoints(point1, 1); }).toThrowError(TypeError, ERROR_MSG); }); it('input arguments are not object has x, y property of Number type, throw Error.', function() { var ERROR_MSG = '[aid.math.getDistanceBetweenTwoPoints] Type of parameters must be Object that has x, y properties.'; expect(function() { math.getDistanceBetweenTwoPoints({}, point2); math.getDistanceBetweenTwoPoints(point1, {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints( { foo: 0, bar: 0, }, point2 ); math.getDistanceBetweenTwoPoints(point1, { foo: 0, bar: 0, }); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints( { x: 0, }, point2 ); math.getDistanceBetweenTwoPoints(point1, { y: 0, }); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints( { x: 0, y: NaN, }, point2 ); math.getDistanceBetweenTwoPoints(point1, { x: NaN, y: 0, }); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getDistanceBetweenTwoPoints(point1, point2); }).not.toThrowError(TypeError, ERROR_MSG); }); it('return number.', function() { var distance = math.getDistanceBetweenTwoPoints(point1, point2); expect(aid.isNumber(distance)).toBeTruthy(); }); }); describe('.getOrthogonalPointBetweenLineAndSomePoint()', function() { var point1 = { x: 0, y: 0, }, point2 = { x: 100, y: 100, }, somePoint = { x: 50, y: 100, }; it('input arguments are not Object type, throw TypeError.', function() { var ERROR_MSG = '[aid.math.getOrthogonalPointBetweenLineAndSomePoint] Type of parameters must be Object.'; expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(undefined, point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, undefined, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, undefined); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(null, point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, null, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, null); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(false, point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, false, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, false); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(true, point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, true, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, true); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint('', point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, '', somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, ''); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint([], point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, [], somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(function() {}, point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, function() {}, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, function() {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(new RegExp('^aid'), point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, new RegExp('^aid'), somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, new RegExp('^aid')); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(/^aid/, point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, /^aid/, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, /^aid/); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(1, point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, 1, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, 1); }).toThrowError(TypeError, ERROR_MSG); }); it('input arguments are not object has x, y property of Number type, throw Error.', function() { var ERROR_MSG = '[aid.math.getOrthogonalPointBetweenLineAndSomePoint] Type of parameters must be Object that has x, y properties.'; expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint({}, point2, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, {}, somePoint); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint( { foo: 0, bar: 0, }, point2, somePoint ); math.getOrthogonalPointBetweenLineAndSomePoint( point1, { foo: 0, bar: 0, }, somePoint ); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, { foo: 0, bar: 0, }); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint( { x: 0, }, point2, somePoint ); math.getOrthogonalPointBetweenLineAndSomePoint( point1, { y: 0, }, somePoint ); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, { x: 0, }); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint( { x: 0, y: NaN, }, point2, somePoint ); math.getOrthogonalPointBetweenLineAndSomePoint( point1, { x: NaN, y: 0, }, somePoint ); math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, { x: NaN, y: 0, }); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, somePoint); }).not.toThrowError(TypeError, ERROR_MSG); }); it('return null, when collinearPoint1 is equal to collinearPoint2.', function() { var point = math.getOrthogonalPointBetweenLineAndSomePoint( { x: 99, y: 99, }, { x: 99, y: 99, }, somePoint ); expect(point).toBeNull(); }); it('return object has x, y properties.', function() { var point = math.getOrthogonalPointBetweenLineAndSomePoint(point1, point2, somePoint); expect(aid.isObject(point)).toBeTruthy(); expect(aid.isNumber(point.x)).toBeTruthy(); expect(aid.isNumber(point.y)).toBeTruthy(); }); }); describe('.getRandomPositiveNegative()', function() { it('return -1 or 1', function() { var val = math.getRandomPositiveNegative(); expect(val === -1 || val === 1).toBeTruthy(); }); }); describe('.getRandomFloat()', function() { it('input arguments are not Number type, throw TypeError.', function() { var ERROR_MSG = '[aid.math.getRandomFloat] Type of parameters must be Number.'; expect(function() { math.getRandomFloat(undefined, 99.999); math.getRandomFloat(99.999, undefined); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomFloat(null, 99.999); math.getRandomFloat(99.999, null); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomFloat(false, 99.999); math.getRandomFloat(99.999, false); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomFloat('aid.js', 99.999); math.getRandomFloat(99.999, 'aid.js'); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomFloat({}, 99.999); math.getRandomFloat(99.999, {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomFloat([], 99.999); math.getRandomFloat(99.999, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomFloat(new RegExp('^aid'), 99.999); math.getRandomFloat(99.999, new RegExp('^aid')); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomFloat(/^aid/, 99.999); math.getRandomFloat(99.999, /^aid/); }).toThrowError(TypeError, ERROR_MSG); }); it('return random Float number.', function() { var val = math.getRandomFloat(-99.999, 99.999); expect(val >= -99.999 && val < 99.999).toBeTruthy(); }); }); describe('.getRandomInt()', function() { it('input arguments are not Integer Number type, throw TypeError.', function() { var ERROR_MSG = '[aid.math.getRandomInt] Type of parameters must be Integer Number.'; expect(function() { math.getRandomInt(undefined, 99); math.getRandomInt(99, undefined); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomInt(null, 99); math.getRandomInt(99, null); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomInt(false, 99); math.getRandomInt(99, false); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomInt('aid.js', 99); math.getRandomInt(99, 'aid.js'); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomInt({}, 99); math.getRandomInt(99, {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomInt([], 99); math.getRandomInt(99, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomInt(new RegExp('^aid'), 99); math.getRandomInt(99, new RegExp('^aid')); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomInt(/^aid/, 99); math.getRandomInt(99, /^aid/); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.getRandomInt(-99, 99.999); math.getRandomInt(-99.999, 99); }).toThrowError(TypeError, ERROR_MSG); }); it('return random Int number.', function() { var val = math.getRandomInt(-99, 99); expect(aid.isInteger(val)).toBeTruthy(); expect(val >= -99 && val <= 99).toBeTruthy(); }); }); describe('.remap()', function() { it('if func parameter type is not function, throw Error', function() { var ERROR_MSG = '[aid.math.remap] Type of parameters must be Number.'; expect(function() { math.remap(undefined, 0, 1, 0, 100); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, null, 1, 0, 100); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, false, 1, 0, 100); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, true, 1, 0, 100); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, 0, 1, 0, 100); }).not.toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, 0, 1, 'aid.js', 100); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, 0, 1, 0, []); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, 0, 1, 0, NaN); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, 0, 1, 0, function() {}); }).toThrowError(TypeError, ERROR_MSG); expect(function() { math.remap(0.5, 0, 1, 0, /aid.js/); }).toThrowError(TypeError, ERROR_MSG); }); it('return remaped value', function() { expect(math.remap(0, -1, 1, 0, 100)).toEqual(50); expect(math.remap(0.5, 0, 1, 0, 100)).toEqual(50); expect(math.remap(0, -100, 100, 0, 10)).toEqual(5); expect(math.remap(50, 0, 100, 0, 10)).toEqual(5); }); }); describe('.gt()', function() { it('return function if input only one parameter.', function() { expect(function() { aid.isFunction(math.gt(undefined)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gt(null)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gt(false)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gt(true)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gt(0)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gt('')); }).toBeTruthy(); expect(function() { aid.isFunction(math.gt([])); }).toBeTruthy(); expect(function() { aid.isFunction(math.gt(NaN)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gt(function() {})); }).toBeTruthy(); }); it('if arguments are not Number type, throw Error.', function() { expect(function() { aid.isFunction(math.gt(undefined)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(null)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(false)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(true)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(0)(99)); }).not.toThrowError(); expect(function() { aid.isFunction(math.gt('')(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gt([])(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(NaN)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(function() {})(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(99)(undefined)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(99)(null)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(99)(false)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(99)(true)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(99)(0)); }).not.toThrowError(); expect(function() { aid.isFunction(math.gt(99)('')); }).toThrowError(); expect(function() { aid.isFunction(math.gt(99)([])); }).toThrowError(); expect(function() { aid.isFunction(math.gt(99)(NaN)); }).toThrowError(); expect(function() { aid.isFunction(math.gt(99)(function() {})); }).toThrowError(); }); it('if lhs argument is greater than rhs argument, return true.', function() { expect(math.gt(-1)(-1)).toEqual(false); expect(math.gt(-1)(-9)).toEqual(false); expect(math.gt(0)(0)).toEqual(false); expect(math.gt(1)(1)).toEqual(false); expect(math.gt(9)(1)).toEqual(false); expect(math.gt(-9)(-1)).toEqual(true); expect(math.gt(1)(9)).toEqual(true); }); }); describe('.lt()', function() { it('return function if input only one parameter.', function() { expect(function() { aid.isFunction(math.lt(undefined)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lt(null)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lt(false)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lt(true)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lt(0)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lt('')); }).toBeTruthy(); expect(function() { aid.isFunction(math.lt([])); }).toBeTruthy(); expect(function() { aid.isFunction(math.lt(NaN)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lt(function() {})); }).toBeTruthy(); }); it('if arguments are not Number type, throw Error.', function() { expect(function() { aid.isFunction(math.lt(undefined)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(null)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(false)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(true)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(0)(99)); }).not.toThrowError(); expect(function() { aid.isFunction(math.lt('')(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lt([])(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(NaN)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(function() {})(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(99)(undefined)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(99)(null)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(99)(false)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(99)(true)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(99)(0)); }).not.toThrowError(); expect(function() { aid.isFunction(math.lt(99)('')); }).toThrowError(); expect(function() { aid.isFunction(math.lt(99)([])); }).toThrowError(); expect(function() { aid.isFunction(math.lt(99)(NaN)); }).toThrowError(); expect(function() { aid.isFunction(math.lt(99)(function() {})); }).toThrowError(); }); it('if lhs argument is less than rhs argument, return true.', function() { expect(math.lt(-1)(-1)).toEqual(false); expect(math.lt(-1)(-9)).toEqual(true); expect(math.lt(0)(0)).toEqual(false); expect(math.lt(1)(1)).toEqual(false); expect(math.lt(9)(1)).toEqual(true); expect(math.lt(-9)(-1)).toEqual(false); expect(math.lt(1)(9)).toEqual(false); }); }); describe('.gte()', function() { it('return function if input only one parameter.', function() { expect(function() { aid.isFunction(math.gte(undefined)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gte(null)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gte(false)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gte(true)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gte(0)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gte('')); }).toBeTruthy(); expect(function() { aid.isFunction(math.gte([])); }).toBeTruthy(); expect(function() { aid.isFunction(math.gte(NaN)); }).toBeTruthy(); expect(function() { aid.isFunction(math.gte(function() {})); }).toBeTruthy(); }); it('if arguments are not Number type, throw Error.', function() { expect(function() { aid.isFunction(math.gte(undefined)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(null)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(false)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(true)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(0)(99)); }).not.toThrowError(); expect(function() { aid.isFunction(math.gte('')(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gte([])(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(NaN)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(function() {})(99)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(99)(undefined)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(99)(null)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(99)(false)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(99)(true)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(99)(0)); }).not.toThrowError(); expect(function() { aid.isFunction(math.gte(99)('')); }).toThrowError(); expect(function() { aid.isFunction(math.gte(99)([])); }).toThrowError(); expect(function() { aid.isFunction(math.gte(99)(NaN)); }).toThrowError(); expect(function() { aid.isFunction(math.gte(99)(function() {})); }).toThrowError(); }); it('if lhs argument is greater than equal rhs argument, return true.', function() { expect(math.gte(-1)(-1)).toEqual(true); expect(math.gte(-1)(-9)).toEqual(false); expect(math.gte(0)(0)).toEqual(true); expect(math.gte(1)(1)).toEqual(true); expect(math.gte(9)(1)).toEqual(false); expect(math.gte(-9)(-1)).toEqual(true); expect(math.gte(1)(9)).toEqual(true); }); }); describe('.lte()', function() { it('return function if input only one parameter.', function() { expect(function() { aid.isFunction(math.lte(undefined)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lte(null)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lte(false)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lte(true)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lte(0)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lte('')); }).toBeTruthy(); expect(function() { aid.isFunction(math.lte([])); }).toBeTruthy(); expect(function() { aid.isFunction(math.lte(NaN)); }).toBeTruthy(); expect(function() { aid.isFunction(math.lte(function() {})); }).toBeTruthy(); }); it('if arguments are not Number type, throw Error.', function() { expect(function() { aid.isFunction(math.lte(undefined)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(null)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(false)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(true)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(0)(99)); }).not.toThrowError(); expect(function() { aid.isFunction(math.lte('')(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lte([])(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(NaN)(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(function() {})(99)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(99)(undefined)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(99)(null)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(99)(false)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(99)(true)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(99)(0)); }).not.toThrowError(); expect(function() { aid.isFunction(math.lte(99)('')); }).toThrowError(); expect(function() { aid.isFunction(math.lte(99)([])); }).toThrowError(); expect(function() { aid.isFunction(math.lte(99)(NaN)); }).toThrowError(); expect(function() { aid.isFunction(math.lte(99)(function() {})); }).toThrowError(); }); it('if lhs argument is less than equal rhs argument, return true.', function() { expect(math.lte(-1)(-1)).toEqual(true); expect(math.lte(-1)(-9)).toEqual(true); expect(math.lte(0)(0)).toEqual(true); expect(math.lte(1)(1)).toEqual(true); expect(math.lte(9)(1)).toEqual(true); expect(math.lte(-9)(-1)).toEqual(false); expect(math.lte(1)(9)).toEqual(false); }); }); }); });
var Java = require('java'); var Browser = require('./browser'); var fs = require('fs'); var which = require('which'); var os = require('os'); var request = require('request'); var iOS = function(options){ Browser.prototype.constructor.apply(this,arguments); this.options.deviceURL = this.options.deviceURL || "http://localhost:3001/"; this.name="ios"; } iOS.prototype=new Browser(); iOS.prototype.constructor=iOS; iOS.prototype.isAvailable=function(onComplete){ if(os.platform()=="darwin"){ var url = this.options.deviceURL+"wd/hub"; request(url,function(err,request,body){ if(!err && request.statusCode==200 && body.indexOf("iWebDriver")!=-1){ return onComplete(null,true); } else { return onComplete(null,false); } }); } else return onComplete(null,false); } iOS.prototype.openBrowser=function(url,onComplete){ var iOSWrapper = Java.import('iOSWrapper'); var f = new iOSWrapper(); f.setDeviceURL(this.options.deviceURL); f.openBrowser(url,onComplete); } module.exports=iOS;
import { PERSON_REQUEST, PERSON_SUCCESS, PERSON_FAILURE, PERSON_CLEAN, PERSON_UPDATE, PERSON_DELETE } from '../constants/PersonActionTypes'; import PersonSchemas from '../models/PersonSchemas'; import {CALL_API} from '../middleware/api'; function fetchPersonList(pageNo) { return { entity: 'personPagination', [CALL_API]: { types: [PERSON_REQUEST, PERSON_SUCCESS, PERSON_FAILURE], jsonUrl: `json/person/${pageNo}.json`, url: 'path/persons', options: {body: {pageNo}}, schema: PersonSchemas.PERSON_LIST } }; } //获取 person 分页列表 export function getPersonList() { return (dispatch, getState) => { const { pageNo = 1, //请求传递的页面 isFetching, lastPage //最后一页 } = getState().person.personPagination || {}; if (isFetching || lastPage) { return null; } return dispatch(fetchPersonList(pageNo)); }; } //清空数据 export function cleanPersonList() { return { type: PERSON_CLEAN, entity: 'personPagination', clean: true } } //修改 export function updatePerson(person) { return { type: PERSON_UPDATE, person }; } //删除 export function deletePerson(id) { return { type: PERSON_DELETE, id }; }
var get = Ember.get; var store, adapter, Person, PhoneNumber; module("Basic Adapter - Finding", { setup: function() { adapter = DS.BasicAdapter.create(); store = DS.Store.create({ adapter: adapter }); var attr = DS.attr, hasMany = DS.hasMany, belongsTo = DS.belongsTo; Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), createdAt: attr('date') }); PhoneNumber = DS.Model.extend({ areaCode: attr('number'), number: attr('number'), person: belongsTo(Person) }); Person.reopen({ phoneNumbers: hasMany(PhoneNumber) }); DS.registerTransforms('test', { date: { serialize: function(value) { return value.toString(); }, deserialize: function(string) { return new Date(string); } } }); }, teardown: function() { Ember.run(function() { DS.clearTransforms(); store.destroy(); adapter.destroy(); }); } }); test("The sync object is consulted to load data", function() { Person.sync = { find: function(id, process) { equal(id, "1", "The correct ID is passed through"); setTimeout(async(function() { process({ id: 1, firstName: "Tom", lastName: "Dale" }).load(); })); } }; var person = Person.find(1); equal(get(person, 'id'), "1", "The id is the coerced ID passed to find"); person.on('didLoad', async(function() { equal(get(person, 'firstName'), "Tom"); equal(get(person, 'lastName'), "Dale"); equal(get(person, 'id'), "1", "The id is still the same"); })); }); test("A camelizeKeys() convenience will camelize all of the keys", function() { Person.sync = { find: function(id, process) { setTimeout(async(function() { process({ id: 1, first_name: "Tom", last_name: "Dale" }) .camelizeKeys() .load(); })); } }; var person = Person.find(1); equal(get(person, 'id'), "1", "The id is the coerced ID passed to find"); person.on('didLoad', async(function() { equal(get(person, 'firstName'), "Tom"); equal(get(person, 'lastName'), "Dale"); equal(get(person, 'id'), "1", "The id is still the same"); })); }); test("An applyTransforms method will apply registered transforms", function() { Person.sync = { find: function(id, process) { setTimeout(async(function() { process({ id: 1, firstName: "Tom", lastName: "Dale", createdAt: "1986-06-09" }) .applyTransforms('test') .load(); })); } }; var person = Person.find(1); equal(get(person, 'id'), "1", "The id is the coerced ID passed to find"); person.on('didLoad', async(function() { equal(get(person, 'firstName'), "Tom"); equal(get(person, 'lastName'), "Dale"); equal(get(person, 'createdAt').valueOf(), new Date("1986-06-09").valueOf(), "The date was properly transformed"); equal(get(person, 'id'), "1", "The id is still the same"); })); }); test("An adapter can use `munge` for arbitrary transformations", function() { Person.sync = { find: function(id, process) { setTimeout(async(function() { process({ id: 1, FIRST_NAME: "Tom", LAST_NAME: "Dale", didCreateAtTime: "1986-06-09" }) .munge(function(json) { json.firstName = json.FIRST_NAME; json.lastName = json.LAST_NAME; json.createdAt = json.didCreateAtTime; }) .applyTransforms('test') .load(); })); } }; var person = Person.find(1); equal(get(person, 'id'), "1", "The id is the coerced ID passed to find"); person.on('didLoad', async(function() { equal(get(person, 'firstName'), "Tom"); equal(get(person, 'lastName'), "Dale"); equal(get(person, 'createdAt').valueOf(), new Date("1986-06-09").valueOf(), "The date was properly transformed"); equal(get(person, 'id'), "1", "The id is still the same"); })); }); test("A query will invoke the findQuery hook on the sync object", function() { Person.sync = { query: function(query, process) { deepEqual(query, { all: true }, "The query was passed through"); setTimeout(async(function() { process([ { id: 1, first_name: "Yehuda", last_name: "Katz" }, { id: 2, first_name: "Tom", last_name: "Dale" } ]).camelizeKeys().load(); })); } }; var people = Person.query({ all: true }); people.then(function() { equal(get(people, 'length'), 2, "The people are loaded in"); deepEqual(people.objectAt(0).getProperties('id', 'firstName', 'lastName'), { id: "1", firstName: "Yehuda", lastName: "Katz" }); deepEqual(people.objectAt(1).getProperties('id', 'firstName', 'lastName'), { id: "2", firstName: "Tom", lastName: "Dale" }); }); }); test("A query's processor supports munge across all elements in its Array", function() { Person.sync = { query: function(query, process) { deepEqual(query, { all: true }, "The query was passed through"); setTimeout(async(function() { process([ { id: 1, "name,first": "Yehuda", "name,last": "Katz" }, { id: 2, "name,first": "Tom", "name,last": "Dale" } ]) .munge(function(json) { json.firstName = json["name,first"]; json.lastName = json["name,last"]; }) .load(); })); } }; var people = Person.query({ all: true }); people.then(function() { equal(get(people, 'length'), 2, "The people are loaded in"); deepEqual(people.objectAt(0).getProperties('id', 'firstName', 'lastName'), { id: "1", firstName: "Yehuda", lastName: "Katz" }); deepEqual(people.objectAt(1).getProperties('id', 'firstName', 'lastName'), { id: "2", firstName: "Tom", lastName: "Dale" }); }); }); test("A basic adapter receives a call to find<Relationship> for relationships", function() { expect(3); Person.sync = { find: function(id, process) { setTimeout(async(function() { process({ id: 1, firstName: "Tom", lastName: "Dale" }).load(); })); }, findPhoneNumbers: function(person, options, process) { setTimeout(async(function() { process([ { id: 1, areaCode: 703, number: 1234567 }, { id: 2, areaCode: 904, number: 9543256 } ]).load(); })); } }; Person.find(1).then(function(person) { return person.get('phoneNumbers'); }).then(async(function(phoneNumbers) { equal(phoneNumbers.get('length'), 2, "There are now two phone numbers"); equal(phoneNumbers.objectAt(0).get('number'), 1234567, "The first phone number was loaded in"); equal(phoneNumbers.objectAt(1).get('number'), 9543256, "The second phone number was loaded in"); })); }); test("A basic adapter receives a call to find<Relationship> for relationships", function() { expect(4); Person.sync = { find: function(id, process) { setTimeout(async(function() { process({ id: 1, firstName: "Tom", lastName: "Dale" }).load(); })); }, findHasMany: function(person, options, process) { equal(options.relationship, 'phoneNumbers'); setTimeout(async(function() { process([ { id: 1, areaCode: 703, number: 1234567 }, { id: 2, areaCode: 904, number: 9543256 } ]).load(); })); } }; Person.find(1).then(function(person) { return person.get('phoneNumbers'); }).then(async(function(phoneNumbers) { equal(phoneNumbers.get('length'), 2, "There are now two phone numbers"); equal(phoneNumbers.objectAt(0).get('number'), 1234567, "The first phone number was loaded in"); equal(phoneNumbers.objectAt(1).get('number'), 9543256, "The second phone number was loaded in"); })); }); test("Metadata passed for a relationship will get passed to find<Relationship>", function() { expect(4); Person.sync = { find: function(id, process) { setTimeout(async(function() { process({ id: 1, firstName: "Tom", lastName: "Dale", phoneNumbers: 'http://example.com/people/1/phone_numbers' }).load(); })); }, findPhoneNumbers: function(person, options, process) { equal(options.data, 'http://example.com/people/1/phone_numbers', "The metadata was passed"); setTimeout(async(function() { process([ { id: 1, areaCode: 703, number: 1234567 }, { id: 2, areaCode: 904, number: 9543256 } ]).load(); })); } }; Person.find(1).then(function(person) { return person.get('phoneNumbers'); }).then(async(function(phoneNumbers) { equal(phoneNumbers.get('length'), 2, "There are now two phone numbers"); equal(phoneNumbers.objectAt(0).get('number'), 1234567, "The first phone number was loaded in"); equal(phoneNumbers.objectAt(1).get('number'), 9543256, "The second phone number was loaded in"); })); }); test("Metadata passed for a relationship will get passed to findHasMany", function() { expect(5); Person.sync = { find: function(id, process) { setTimeout(async(function() { process({ id: 1, firstName: "Tom", lastName: "Dale", phoneNumbers: 'http://example.com/people/1/phone_numbers' }).load(); })); }, findHasMany: function(person, options, process) { equal(options.data, 'http://example.com/people/1/phone_numbers', "The metadata was passed"); equal(options.relationship, 'phoneNumbers', "The relationship name was passed"); setTimeout(async(function() { process([ { id: 1, areaCode: 703, number: 1234567 }, { id: 2, areaCode: 904, number: 9543256 } ]).load(); })); } }; Person.find(1).then(function(person) { return person.get('phoneNumbers'); }).then(async(function(phoneNumbers) { equal(phoneNumbers.get('length'), 2, "There are now two phone numbers"); equal(phoneNumbers.objectAt(0).get('number'), 1234567, "The first phone number was loaded in"); equal(phoneNumbers.objectAt(1).get('number'), 9543256, "The second phone number was loaded in"); })); });
/** * Created by Vicky on 6/13/2017. */ function systemComponents(strArr) { let components = new Map(); for (let line of strArr) { let [system, component, subcomponent] = line.split(' | '); if (!components.has(system)) { components.set(system, new Map()); } if (!components.get(system).has(component)) { components.get(system).set(component, []); } components.get(system).get(component).push(subcomponent); } components = [...components].sort(compareSystems); for (let [system, innerMap] of components) { console.log(system); innerMap = [...innerMap].sort(subCompSort); for (let [component, subCompArr] of innerMap) { console.log('|||' + component); for (let subComp of subCompArr) { console.log('||||||' + subComp); } } } function subCompSort(a, b) { return a[1].length < b[1].length; } function compareSystems(a, b) { if ([...a[1]].length > [...b[1]].length) { return -1; } else if ([...a[1]].length < [...b[1]].length) { return 1; } else { if (a < b) { return -1; } else if (a > b) { return 1; } else { return 0; } } } } systemComponents([ 'SULS | Main Site | Home Page', 'SULS | Main Site | Login Page', 'SULS | Main Site | Register Page', 'SULS | Judge Site | Login Page', 'SULS | Judge Site | Submittion Page', 'Lambda | CoreA | A23', 'SULS | Digital Site | Login Page', 'Lambda | CoreB | B24', 'Lambda | CoreA | A24', 'Lambda | CoreA | A25', 'Lambda | CoreC | C4', 'Indice | Session | Default Storage', 'Indice | Session | Default Security', ])
/* le slider */ jQuery(document).ready(function($) { console.log( "ready!" ); $('#slider').bjqs({ // PARAMETROS OPCIONALES QUE NOS OFRECE EL PLUGIN height : 500, width:1600, // animacion animtype : 'fade', // ‘fade’ o ‘slide’ animduration : 500, // rapidez de transicion animspeed : 4000, // delay entre animaciones automatic : true, // automatico // controles showcontrols : true, // Mostrar controles prev y next centercontrols : true, // centrar controles prev y next nexttext : 'Siguiente', // Texto para boton next prevtext : 'Anterior', // Texto para boton prev showmarkers : true, // Mostrar botones de navegacion centermarkers : true, // Centrar botones de navegacion // interaccion keyboardnav : true, // habilita navegacion por teclado hoverpause : true, // pausa slide cuando el mouse esta encima // presentacion usecaptions : true, // muestra texto introducido en el tag title responsive : true // habilita modo responsive (beta) }); });
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { files: ['app/js/*.js'] }, copy: { deploy: { files: [ {expand: true, cwd: "app", src: ['**/*'], dest: '/var/www/html/status/'}, ] } }, watch : { files : [ 'app/**' ], tasks : ['test', 'deploy'] } }); // concat was used at one point but I decided to keep it simple... for now // grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('test', ['jshint']); grunt.registerTask('deploy', ['copy:deploy']); grunt.registerTask('default', ['test', 'deploy', 'watch']); }
(function() { 'use strict'; angular.module('material.components.tabs') .directive('mdTabs', TabsDirective); /** * @ngdoc directive * @name mdTabs * @module material.components.tabs * * @restrict E * * @description * The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to produces a Tabs components. * In turn, the nested `<md-tab>` directive is used to specify a tab label for the **header button** and a [optional] tab view * content that will be associated with each tab button. * * Below is the markup for its simplest usage: * * <hljs lang="html"> * <md-tabs> * <md-tab label="Tab #1"></md-tab> * <md-tab label="Tab #2"></md-tab> * <md-tab label="Tab #3"></md-tab> * </md-tabs> * </hljs> * * Tabs supports three (3) usage scenarios: * * 1. Tabs (buttons only) * 2. Tabs with internal view content * 3. Tabs with external view content * * **Tab-only** support is useful when tab buttons are used for custom navigation regardless of any other components, content, or views. * **Tabs with internal views** are the traditional usages where each tab has associated view content and the view switching is managed internally by the Tabs component. * **Tabs with external view content** is often useful when content associated with each tab is independently managed and data-binding notifications announce tab selection changes. * * > As a performance bonus, if the tab content is managed internally then the non-active (non-visible) tab contents are temporarily disconnected from the `$scope.$digest()` processes; which restricts and optimizes DOM updates to only the currently active tab. * * Additional features also include: * * * Content can include any markup. * * If a tab is disabled while active/selected, then the next tab will be auto-selected. * * If the currently active tab is the last tab, then next() action will select the first tab. * * Any markup (other than **`<md-tab>`** tags) will be transcluded into the tab header area BEFORE the tab buttons. * * ### Explanation of tab stretching * * Initially, tabs will have an inherent size. This size will either be defined by how much space is needed to accommodate their text or set by the user through CSS. Calculations will be based on this size. * * On mobile devices, tabs will be expanded to fill the available horizontal space. When this happens, all tabs will become the same size. * * On desktops, by default, stretching will never occur. * * This default behavior can be overridden through the `md-stretch-tabs` attribute. Here is a table showing when stretching will occur: * * `md-stretch-tabs` | mobile | desktop * ------------------|-----------|-------- * `auto` | stretched | --- * `always` | stretched | stretched * `never` | --- | --- * * @param {integer=} md-selected Index of the active/selected tab * @param {boolean=} md-no-ink If present, disables ink ripple effects. * @param {boolean=} md-no-bar If present, disables the selection ink bar. * @param {string=} md-align-tabs Attribute to indicate position of tab buttons: `bottom` or `top`; default is `top` * @param {string=} md-stretch-tabs Attribute to indicate whether or not to stretch tabs: `auto`, `always`, or `never`; default is `auto` * * @usage * <hljs lang="html"> * <md-tabs md-selected="selectedIndex" > * <img ng-src="img/angular.png" class="centered"> * * <md-tab * ng-repeat="tab in tabs | orderBy:predicate:reversed" * md-on-select="onTabSelected(tab)" * md-on-deselect="announceDeselected(tab)" * disabled="tab.disabled" > * * <md-tab-label> * {{tab.title}} * <img src="img/removeTab.png" * ng-click="removeTab(tab)" * class="delete" > * </md-tab-label> * * {{tab.content}} * * </md-tab> * * </md-tabs> * </hljs> * */ function TabsDirective($mdTheming) { return { restrict: 'E', controller: '$mdTabs', require: 'mdTabs', transclude: true, scope: { selectedIndex: '=?mdSelected' }, template: '<section class="md-header" ' + 'ng-class="{\'md-paginating\': pagination.active}">' + '<button class="md-paginator md-prev" ' + 'ng-if="pagination.active && pagination.hasPrev" ' + 'ng-click="pagination.clickPrevious()" ' + 'aria-hidden="true">' + '<md-icon md-svg-icon="tabs-arrow"></md-icon>' + '</button>' + // overflow: hidden container when paginating '<div class="md-header-items-container" md-tabs-pagination>' + // flex container for <md-tab> elements '<div class="md-header-items">' + '<md-tabs-ink-bar></md-tabs-ink-bar>' + '</div>' + '</div>' + '<button class="md-paginator md-next" ' + 'ng-if="pagination.active && pagination.hasNext" ' + 'ng-click="pagination.clickNext()" ' + 'aria-hidden="true">' + '<md-icon md-svg-icon="tabs-arrow"></md-icon>' + '</button>' + '</section>' + '<section class="md-tabs-content"></section>', link: postLink }; function postLink(scope, element, attr, tabsCtrl, transclude) { scope.stretchTabs = attr.hasOwnProperty('mdStretchTabs') ? attr.mdStretchTabs || 'always' : 'auto'; $mdTheming(element); configureAria(); watchSelected(); transclude(scope.$parent, function(clone) { angular.element(element[0].querySelector('.md-header-items')).append(clone); }); function checkHeight() { setTimeout(function() { var w = angular.element(window), wh = w.height(), ww = w.width(), hh = angular.element('.mobile-header').height(), th = angular.element('.md-header').height(), maxHeight = wh - hh - th, tabsContent = angular.element(element).find('.md-tabs-content'); if (ww < 600 && tabsContent.height() > maxHeight) { tabsContent.css({ maxHeight: maxHeight, overflowY: 'scroll' }); } else { tabsContent.removeAttr('style'); } }, 1); } checkHeight(); function configureAria() { element.attr('role', 'tablist'); } function watchSelected() { scope.$watch('selectedIndex', function watchSelectedIndex(newIndex, oldIndex) { if (oldIndex == newIndex) return; var rightToLeft = oldIndex > newIndex; tabsCtrl.deselect(tabsCtrl.itemAt(oldIndex), rightToLeft); if (tabsCtrl.inRange(newIndex)) { var newTab = tabsCtrl.itemAt(newIndex); while (newTab && newTab.isDisabled()) { newTab = newIndex > oldIndex ? tabsCtrl.next(newTab) : tabsCtrl.previous(newTab); } tabsCtrl.select(newTab, rightToLeft); } checkHeight(); }); } } } })();